From ramit.prasad at jpmorgan.com Thu Mar 1 00:41:29 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Wed, 29 Feb 2012 23:41:29 +0000 Subject: [Tutor] FW: python dictionary and loop Message-ID: <5B80DD153D7D744689F57F4FB69AF47416A5BD@SCACMX008.exchad.jpmchase.net> Please do not top post and also please remember to reply back to the list. >Okay thanks for clarifying that that code doesn't split anything. I've been playing around a little bit. I think this is closer to what I am trying to do: >>>>paragraph = 'This is line one\nLet me show you how' >>>> paragraph.split('\n') >['This is line one', 'Let me show you how'] >>>> first_sentence,second_sentence = paragraph.split('\n') >>>> d = {first_sentence:second_sentence} >>>> d >{'This is line one': 'Let me show you how'} ># wouldn't the above code capture what I am trying to do as far as split the string 'paragraph' into two sentences and then create a dictionary {d} that will separate the two sentences so that one sentence {first_sentence} represents a key value and the other sentence {second_sentence} represents the value of the key? Yes. it does seem to. What is the reason that you want to do this though? I usually use this when loading some tabular data like from a csv/Excel file. Not sure I see the point when done for a 'paragraph'. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From steve at pearwood.info Thu Mar 1 13:03:05 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 1 Mar 2012 23:03:05 +1100 Subject: [Tutor] new to programming and wondering about an IDE for Python on Linux In-Reply-To: <1330356140.95758.YahooMailNeo@web125601.mail.ne1.yahoo.com> References: <1330356140.95758.YahooMailNeo@web125601.mail.ne1.yahoo.com> Message-ID: <20120301120305.GA11790@ando> On Mon, Feb 27, 2012 at 07:22:20AM -0800, John Jensen wrote: > Hi All, > > I'm?new to programming and wondering about an IDE for Python on Linux. > I'd appreciate any feedback on this and good tutorials or books on > Python 3 and the IDEs suggested. There are many available and I'm > wondering what you as users find effective. Personally, I find that Linux and the standard tool chain it provides is an IDE, no need for a dedicated IDE application. http://blog.sanctum.geek.nz/series/unix-as-ide/ My IDE of choice is KDE's "kate" text editor, plus a terminal app that supports multiple tabs. I run at least one Python interactive interpreter in one tab, for testing code snippets, calling interactive help, etc., and other tabs for controlling my source repository (mercurial), running scripts, etc. Oh, and a browser for searching the web. I prefer DDG: http://duckduckgo.com/ which has dedicated Python support. -- Steven From brad.hudson at gmail.com Fri Mar 2 18:03:03 2012 From: brad.hudson at gmail.com (Brad Hudson) Date: Fri, 2 Mar 2012 11:03:03 -0600 Subject: [Tutor] python + sharepoint Message-ID: Can someone assist in a very basic task of retrieving a '.txt' file from a sharepoint document library using Python 2.4 standard libraries? I'm certain, I need to build up some form of authentication to pass, but do not know where to begin. Also, I do not want to attempt to customize or install additional packages to the server for this (Solaris). Note: url is changed below for obvious reasons, but the traceback is untouched. # ./get_file.py Traceback (most recent call last): File "./get_file.py", line 7, in ? result = urllib2.urlopen(url).readlines() File "/usr/lib/python2.4/urllib2.py", line 130, in urlopen return _opener.open(url, data) File "/usr/lib/python2.4/urllib2.py", line 364, in open response = meth(req, response) File "/usr/lib/python2.4/urllib2.py", line 471, in http_response response = self.parent.error( File "/usr/lib/python2.4/urllib2.py", line 402, in error return self._call_chain(*args) File "/usr/lib/python2.4/urllib2.py", line 337, in _call_chain result = func(*args) File "/usr/lib/python2.4/urllib2.py", line 480, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) urllib2.HTTPError: HTTP Error 400: Bad Request [root at ilhsf001h001]# cat get_file.py #!/usr/bin/env python import urllib2 url = 'http://myserver.com/myfile.txt' result = urllib2.urlopen(url).readlines() print result # From ilhs_hs at yahoo.com Fri Mar 2 20:11:30 2012 From: ilhs_hs at yahoo.com (Hs Hs) Date: Fri, 2 Mar 2012 11:11:30 -0800 (PST) Subject: [Tutor] number of mismatches in a string Message-ID: <1330715490.17262.YahooMailNeo@web111210.mail.gq1.yahoo.com> Hi: I have the following table and I am interested in calculating mismatch ratio. I am not completely clear how to do this and any help is deeply appreciated.? Length ? ? Matches 77 ? ? ?24A0T9T36 71 ? ? ?25^T9^T37 60 ? ? ?25^T9^T26 62 ? ? ?42A19 In length column I have length of the character string.? In the second column I have the matches my reference string.? In fist case, where 77 is length, in matches from left to right, first 24 matched my reference string following by a extra character A, a null (does not account to proble) and extra T, 9 matches, extra T and 36 matches. ?Totally there are 3 mismatches In case 2, I lost 2 characters (^ = loss of character compared to reference sentence) ? -? TOMISAGOODBOY T^MISAGOOD^OY ? (here I lost 2 characters) ?= I have 2 mismatches TOMISAGOOODBOOY (here I have 2 extra characters O and O) = I have two mismatches In case 4: I have 42 matches, extra A and 19 matches = so I have 1 mismatch How can that mismatch number from matches string. 1. I have to count how many A or T or G or C (believe me only these 4 letters will appear in this, i will not see Z or B or K etc) 2. ^T or ^A or ^G or ^C will also be a mismatch desired output: Length ? ? Matches ? mismatches 77 ? ? ?24A0T9T36 ? ?3? 71 ? ? ?25^T9^T37 ? ? 2 60 ? ? ?25^T9^T26 ? ? 2 62 ? ? ?42A19 ? ? ? ? ? ? 1 10 ? ? ?6^TTT1 ? ? ? ? ? 3 thanks? Hs. -------------- next part -------------- An HTML attachment was scrubbed... URL: From fomcl at yahoo.com Fri Mar 2 22:14:26 2012 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Fri, 2 Mar 2012 13:14:26 -0800 (PST) Subject: [Tutor] number of mismatches in a string In-Reply-To: <1330715490.17262.YahooMailNeo@web111210.mail.gq1.yahoo.com> References: <1330715490.17262.YahooMailNeo@web111210.mail.gq1.yahoo.com> Message-ID: <1330722866.96429.YahooMailNeo@web110702.mail.gq1.yahoo.com> Hi, I do not completely follow you, but perhaps you could check out this page: http://code.activestate.com/recipes/576869-longest-common-subsequence-problem-solver/ Another source of inspiration could be the levenshtein distance. ? Regards, Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~? >________________________________ > From: Hs Hs >To: "tutor at python.org" >Sent: Friday, March 2, 2012 8:11 PM >Subject: [Tutor] number of mismatches in a string > > >Hi: >I have the following table and I am interested in calculating mismatch ratio. I am not completely clear how to do this and any help is deeply appreciated.? > > >Length ? ? Matches >77 ? ? ?24A0T9T36 > >71 ? ? ?25^T9^T37 > >60 ? ? ?25^T9^T26 >62 ? ? ?42A19 > > > > > >In length column I have length of the character string.? >In the second column I have the matches my reference string.? > > > > >In fist case, where 77 is length, in matches from left to right, first 24 matched my reference string following by a extra character A, a null (does not account to proble) and extra T, 9 matches, extra T and 36 matches. ?Totally there are 3 mismatches > > >In case 2, I lost 2 characters (^ = loss of character compared to reference sentence) ? -? > > >TOMISAGOODBOY >T^MISAGOOD^OY ? (here I lost 2 characters) ?= I have 2 mismatches >TOMISAGOOODBOOY (here I have 2 extra characters O and O) = I have two mismatches > > > > >In case 4: I have 42 matches, extra A and 19 matches = so I have 1 mismatch > > > > >How can that mismatch number from matches string. >1. I have to count how many A or T or G or C (believe me only these 4 letters will appear in this, i will not see Z or B or K etc) >2. ^T or ^A or ^G or ^C will also be a mismatch > > > > >desired output: > > >Length ? ? Matches ? mismatches >77 ? ? ?24A0T9T36 ? ?3? > >71 ? ? ?25^T9^T37 ? ? 2 > >60 ? ? ?25^T9^T26 ? ? 2 >62 ? ? ?42A19 ? ? ? ? ? ? 1 >10 ? ? ?6^TTT1 ? ? ? ? ? 3 > > > > >thanks? >Hs. > > >_______________________________________________ >Tutor maillist? -? Tutor at python.org >To unsubscribe or change subscription options: >http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Fri Mar 2 22:47:44 2012 From: bgailer at gmail.com (bob gailer) Date: Fri, 02 Mar 2012 16:47:44 -0500 Subject: [Tutor] number of mismatches in a string In-Reply-To: <1330715490.17262.YahooMailNeo@web111210.mail.gq1.yahoo.com> References: <1330715490.17262.YahooMailNeo@web111210.mail.gq1.yahoo.com> Message-ID: <4F514000.3040803@gmail.com> On 3/2/2012 2:11 PM, Hs Hs wrote: > Hi: > I have the following table and I am interested in calculating mismatch > ratio. I am not completely clear how to do this and any help is deeply > appreciated. > > Length Matches > 77 24A0T9T36 > 71 25^T9^T37 > 60 25^T9^T26 > 62 42A19 > > > In length column I have length of the character string. > In the second column I have the matches my reference string. > > > In fist case, where 77 is length, in matches from left to right, first > 24 matched my reference string following by a extra character A, a > null (does not account to proble) and extra T, 9 matches, extra T and > 36 matches. Totally there are 3 mismatches > > In case 2, I lost 2 characters (^ = loss of character compared to > reference sentence) - > > TOMISAGOODBOY > T^MISAGOOD^OY (here I lost 2 characters) = I have 2 mismatches > TOMISAGOOODBOOY (here I have 2 extra characters O and O) = I have two > mismatches > > > In case 4: I have 42 matches, extra A and 19 matches = so I have 1 > mismatch > > > How can that mismatch number from matches string. > 1. I have to count how many A or T or G or C (believe me only these 4 > letters will appear in this, i will not see Z or B or K etc) > 2. ^T or ^A or ^G or ^C will also be a mismatch > > > desired output: > > Length Matches mismatches > 77 24A0T9T36 3 > 71 25^T9^T37 2 > 60 25^T9^T26 2 > 62 42A19 1 > 10 6^TTT1 3 > I am sorry but I do not understand, and do not have the patience to wade through all the above in the hopes of gaining insight. Perhaps you could restate the problem in a way that makes it crystal clear. -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From carroll at tjc.com Fri Mar 2 22:34:11 2012 From: carroll at tjc.com (Terry Carroll) Date: Fri, 2 Mar 2012 13:34:11 -0800 (PST) Subject: [Tutor] Which computer operating system is best for Python developers? In-Reply-To: <4F464A16.1080802@timgolden.me.uk> References: <4F464A16.1080802@timgolden.me.uk> Message-ID: (Re Python on Windows 7) On Thu, 23 Feb 2012, Tim Golden wrote: > On 23/02/2012 09:00, Alan Gauld wrote: > >> If you do a reinstall, download the ActiveState version rather >> than the Python.org version. > > I also recommend the ActiveState distro. I am going to "third" Alan's and Tim's recommendations of the Activestate distribution; and further suggest that you use the 32-bit version, anod not the 64-bit version, even if you have the 64-bit Windows 7. Some Python extensions are built only for 32-bit Python and will not work with 64-bit. I recently ran into this on two modules; one was PIL and I cannot remember the other. The easy fix was to uninstall the 64-bit Python and install 32-bit in its place. I'm referrng to Python 2.7 above. From malaclypse2 at gmail.com Fri Mar 2 23:00:50 2012 From: malaclypse2 at gmail.com (Jerry Hill) Date: Fri, 2 Mar 2012 17:00:50 -0500 Subject: [Tutor] number of mismatches in a string In-Reply-To: <1330715490.17262.YahooMailNeo@web111210.mail.gq1.yahoo.com> References: <1330715490.17262.YahooMailNeo@web111210.mail.gq1.yahoo.com> Message-ID: On Fri, Mar 2, 2012 at 2:11 PM, Hs Hs wrote: > Hi: > I have the following table and I am interested in calculating mismatch > ratio. I am not completely clear how to do this and any help is deeply > appreciated. > > Length ? ? Matches > 77 ? ? ?24A0T9T36 > 71 ? ? ?25^T9^T37 > 60 ? ? ?25^T9^T26 > 62 ? ? ?42A19 > > > In length column I have length of the character string. > In the second column I have the matches my reference string. > > > In fist case, where 77 is length, in matches from left to right, first 24 > matched my reference string following by a extra character A, a null (does > not account to proble) and extra T, 9 matches, extra T and 36 matches. > ?Totally there are 3 mismatches > > In case 2, I lost 2 characters (^ = loss of character compared to reference > sentence) ? - > > TOMISAGOODBOY > T^MISAGOOD^OY ? (here I lost 2 characters) ?= I have 2 mismatches > TOMISAGOOODBOOY (here I have 2 extra characters O and O) = I have two > mismatches > > > In case 4: I have 42 matches, extra A and 19 matches = so I have 1 mismatch > > > How can that mismatch number from matches string. > 1. I have to count how many A or T or G or C (believe me only these 4 > letters will appear in this, i will not see Z or B or K etc) > 2. ^T or ^A or ^G or ^C will also be a mismatch > > > desired output: > > Length ? ? Matches ? mismatches > 77 ? ? ?24A0T9T36 ? ?3 > 71 ? ? ?25^T9^T37 ? ? 2 > 60 ? ? ?25^T9^T26 ? ? 2 > 62 ? ? ?42A19 ? ? ? ? ? ? 1 > 10 ? ? ?6^TTT1 ? ? ? ? ? 3 > It looks like all you need to do is count the number of A, T, C, and G characters in your Matches column. Maybe something like this: differences = [ [77, '24A0T9T36'], [71, '25^T9^T37'], [60, '25^T9^T26'], [62, '42A19'] ] for length, matches in differences: mismatches = 0 for char in matches: if char in ('A', 'T', 'G', 'C'): mismatches += 1 print length, matches, mismatches which produces the following output: 77 24A0T9T36 3 71 25^T9^T37 2 60 25^T9^T26 2 62 42A19 1 -- Jerry From brad.hudson at gmail.com Fri Mar 2 23:14:44 2012 From: brad.hudson at gmail.com (Brad Hudson) Date: Fri, 2 Mar 2012 16:14:44 -0600 Subject: [Tutor] python + sharepoint In-Reply-To: References: Message-ID: On Fri, Mar 2, 2012 at 11:03 AM, Brad Hudson wrote: > Can someone assist in a very basic task of retrieving a '.txt' file > from a sharepoint document library using Python 2.4 standard > libraries? I'm certain, I need to build up some form of authentication > to pass, but do not know where to begin. Also, I do not want to > attempt to customize or install additional packages to the server for > this (Solaris). > > Note: url is changed below for obvious reasons, but the traceback is untouched. > > # ./get_file.py > Traceback (most recent call last): > ?File "./get_file.py", line 7, in ? > ? ?result = urllib2.urlopen(url).readlines() > ?File "/usr/lib/python2.4/urllib2.py", line 130, in urlopen > ? ?return _opener.open(url, data) > ?File "/usr/lib/python2.4/urllib2.py", line 364, in open > ? ?response = meth(req, response) > ?File "/usr/lib/python2.4/urllib2.py", line 471, in http_response > ? ?response = self.parent.error( > ?File "/usr/lib/python2.4/urllib2.py", line 402, in error > ? ?return self._call_chain(*args) > ?File "/usr/lib/python2.4/urllib2.py", line 337, in _call_chain > ? ?result = func(*args) > ?File "/usr/lib/python2.4/urllib2.py", line 480, in http_error_default > ? ?raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) > urllib2.HTTPError: HTTP Error 400: Bad Request > [root at ilhsf001h001]# cat get_file.py > #!/usr/bin/env python > > import urllib2 > > url = 'http://myserver.com/myfile.txt' > > result = urllib2.urlopen(url).readlines() > > print result > # Still no response on this one, but I did find a 'rather ugly' solution using subprocess for wget to get a file from sharepoint... #!/usr/bin/env python import getpass import re import shlex from subprocess import Popen, PIPE # build sharepoint user/pw # note: shlex.split requires both a raw and escaped domain string user = r'DOMAIN\\ID' pw = getpass.getpass('password: ') url = 'http://myserver.com/myfile.txt' cmd = 'wget --no-proxy --user=%s --password=%s -O- %s' % (user, pw, url) # create the args for subprocess.Popen args = shlex.split(cmd) # get the tuple from the command s = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE).communicate() # parse the stdout part of the tuple to get the exact list I want vms = s[0].rstrip().split('\n') vms[:] = (re.sub('\|.*$', '', vm.rstrip()) for vm in sorted(vms)) vms[:] = (vm for vm in vms if not re.search('primary', vm)) print vms From alan.gauld at btinternet.com Sat Mar 3 00:22:59 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 02 Mar 2012 23:22:59 +0000 Subject: [Tutor] number of mismatches in a string In-Reply-To: <1330715490.17262.YahooMailNeo@web111210.mail.gq1.yahoo.com> References: <1330715490.17262.YahooMailNeo@web111210.mail.gq1.yahoo.com> Message-ID: On 02/03/12 19:11, Hs Hs wrote: > 1. I have to count how many A or T or G or C (believe me only these 4 > letters will appear in this, i will not see Z or B or K etc) This suggests to me that its related to chromosome analysis or somesuch? There are some python libraries for biochemistry work. Maybe you should Google for that and see if there is something already out there that can do what you want? Your explanation doesn't really make sense to me outside that context and, since I'm not a biologist, it doesn't mean that much in that context either! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Sat Mar 3 03:28:36 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 03 Mar 2012 13:28:36 +1100 Subject: [Tutor] python + sharepoint In-Reply-To: References: Message-ID: <4F5181D4.9030802@pearwood.info> Brad Hudson wrote: > Can someone assist in a very basic task of retrieving a '.txt' file > from a sharepoint document library using Python 2.4 standard > libraries? What's a sharepoint document library? How would you retrieve a text file from it *without* using Python? [...] > Note: url is changed below for obvious reasons, but the traceback is untouched. Not obvious to me. [...] > urllib2.HTTPError: HTTP Error 400: Bad Request Does this help? http://www.checkupdown.com/status/E400.html My wild guess is that sharepoint (whatever that is) is expecting something in the url request that you're not giving; or that it doesn't like your useragent and/or referer and lies about the problem. -- Steven From steve at pearwood.info Sat Mar 3 03:35:10 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 03 Mar 2012 13:35:10 +1100 Subject: [Tutor] python + sharepoint In-Reply-To: References: Message-ID: <4F51835E.9080305@pearwood.info> Brad Hudson wrote: > Still no response on this one, but I did find a 'rather ugly' solution > using subprocess for wget to get a file from sharepoint... > > #!/usr/bin/env python > > import getpass > import re > import shlex > from subprocess import Popen, PIPE > > # build sharepoint user/pw > # note: shlex.split requires both a raw and escaped domain string > user = r'DOMAIN\\ID' > pw = getpass.getpass('password: ') > url = 'http://myserver.com/myfile.txt' > cmd = 'wget --no-proxy --user=%s --password=%s -O- %s' % (user, pw, url) Ah. Well that explains why your version using urllib2 failed -- you don't give a username or password, and sharepoint (whatever that is!) requires one. You might have said. You can read the Fine Manual, which describes how to fetch Internet resources: http://docs.python.org/howto/urllib2.html That is written for Python 2.7, here's one for 2.4: http://docs.python.org/dev/howto/urllib2.html Since you need to authenticate, this will probably be helpful: http://www.voidspace.org.uk/python/articles/authentication.shtml -- Steven From ccsentient at myopera.com Sat Mar 3 04:49:32 2012 From: ccsentient at myopera.com (Christopher Conner) Date: Fri, 02 Mar 2012 21:49:32 -0600 Subject: [Tutor] mentorship Message-ID: Hello folks - I'm a little lost and seek a mentor to accelerate the learning curve associated with open-source development, with python in particular but not exclusively. I've been an computer enthusiast / amateur programmer for 20 years. Too, in the past few years I've researched a variety of related topics: historical computer culture, modern security and cryptography, Linux administration and the philosophy of software development. I also have some working knowledge of apache, website design and a compsci degree from 10 years ago. NOW WHAT? HELP! I've got some free time and I feel like I should pick an open source project and begin contributing, but the options are just staggering. I've narrowed things down to the Python language - maybe the Plone project? maybe helping with documentation at first? Maybe testing? I welcome any suggestions on any point or question given. From steve at pearwood.info Sat Mar 3 07:10:25 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 03 Mar 2012 17:10:25 +1100 Subject: [Tutor] mentorship In-Reply-To: References: Message-ID: <4F51B5D1.80803@pearwood.info> Christopher Conner wrote: > I've got some free time and I feel like I should pick an open source > project and begin contributing, but the options are just staggering. > I've narrowed things down to the Python language - maybe the Plone > project? maybe helping with documentation at first? Maybe testing? Think of a subject you are interested in. Are there any useful projects related to that subject written in Python? If not, write one! You can put code up on PyPI or Google's code hosting: http://code.google.com/hosting/ http://pypi.python.org/ If there are existing projects, find one that does something you are interested in, and try improving it: - fix a bug - write some tests - add some documentation - add some missing functionality In other words: find an itch you have, and scratch it. -- Steven From breamoreboy at yahoo.co.uk Sat Mar 3 07:41:00 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 03 Mar 2012 06:41:00 +0000 Subject: [Tutor] mentorship In-Reply-To: References: Message-ID: On 03/03/2012 03:49, Christopher Conner wrote: > Hello folks - > > I'm a little lost and seek a mentor to accelerate the learning curve > associated with open-source development, with python in particular but > not exclusively. > > I've been an computer enthusiast / amateur programmer for 20 years. Too, > in the past few years I've researched a variety of related topics: > historical computer culture, modern security and cryptography, Linux > administration and the philosophy of software development. > > I also have some working knowledge of apache, website design and a > compsci degree from 10 years ago. > > NOW WHAT? HELP! > > I've got some free time and I feel like I should pick an open source > project and begin contributing, but the options are just staggering. > I've narrowed things down to the Python language - maybe the Plone > project? maybe helping with documentation at first? Maybe testing? > > I welcome any suggestions on any point or question given. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Start with http://pythonmentors.com/ ? -- Cheers. Mark Lawrence. From ccsentient at myopera.com Sat Mar 3 21:06:23 2012 From: ccsentient at myopera.com (Christopher Conner) Date: Sat, 03 Mar 2012 14:06:23 -0600 Subject: [Tutor] mentorship In-Reply-To: <4F525E91.4050506@gmail.com> References: <4F525E91.4050506@gmail.com> Message-ID: Bob, Fascinating - I am intrigued. I'll do some historical research in the mean time; please let me know how to get started. Thank you very much, Chris On Sat, 03 Mar 2012 12:10:25 -0600, bob gailer wrote: > I head an open-source project "Python Pipelines" and am currently > seeking folk like you who have some computer background and a desire to > contribute. > > I am creating a pure Python cross-platform version of IBM's CMS/TSO > Pipelilnes. See http://en.wikipedia.org/wiki/Hartmann_pipeline for a > description of IBM's project. > > There are many folk who (like me) work(ed) at IBM; encountered > Pipeliines and became happily dependent on it for solving problems with > ease. When we were not at IBM we wondered "where is Pipelines for my PC?" > > Others have created PC versions, so mine is not the only one. I think > mine has some special features and will find good use once it is > releasable. > > The only publicly accessible site for this project is at > http://code.google.com/p/python-pipelines > > There is no code there, just another description. Please read it. > > This project involves (of course) Python, regular expressions, parsing, > dynamically linking class instances, threads, etc etc. > > Would you like a more in-depth look, and possibly be willing to learn > and contribute? From cariepigeon81 at gmail.com Sun Mar 4 05:21:26 2012 From: cariepigeon81 at gmail.com (Carie Pigeon) Date: Sat, 3 Mar 2012 23:21:26 -0500 Subject: [Tutor] Creating a Polyline Feature class Message-ID: I have an assignment to create a polyline feature class of rhino tracks from a csv file. I am getting an error that says "unbound method add() must be called with Array instance as first argument (got type instance)". this is for line 104, the line I underlined and put in bold below in my code. What does this mean? If there are other obvious code issues, please feel free to comment. I am unsure if my code is correct. Thank you for your time! Cheers, Carie # Reads rhino positions from an Excel-originating CSV file import arcpy from arcpy import env import fileinput import string import os env.overwriteOutput = True # Hard code file paths spreadsheet = "C:/WCGIS/Geog485/Lesson4/ RhinoObservations.csv" # Sample of data ###Observer,X,Y,Rhino,Comments ##Ben,26.99391,-19.10447,Bo, ##Ben,27.00071,-19.1089,Tulip,Bathing ##Ben,26.9919,-19.10511,Bo, ##Ben,27.00071,-19.1059,Tulip, ##Ben,26.96809,-19.09578,Patches, ##Ben,26.97808,-19.11016,Dinky, ##Ben,26.99213,-19.10395,Bo, ##Ben,27.00083,-19.10326,Tulip, ##Ben,26.97038,-19.09863,Patches,Not doing much of anything ##Ben,26.97768,-19.11153,Dinky, ##Ben,26.99107,-19.10421,Bo, ##Ben,27.00138,-19.1021,Tulip, ##Ben,26.97122,-19.0991,Patches, ##Ben,26.97551,-19.11269,Dinky, ##Ben,26.9904,-19.10553,Bo, ##Ben,26.99893,-19.10342,Tulip, # output feature class?? feature class doesn't exist yet, so not sure how to do this?? fcname = "C:/WCGIS/Geog485/Lesson4" outname = "C:/WCGIS/Geog485/Lesson4/Rhino.shp" # Open the CSV file & read the header line observations = open(spreadsheet, "r") headerline = observations.readline() fieldList = headerline.split(",") ### 0 1 2 3 4 ### Observer,X,Y,Rhino,Comments # Look through the header to find "X", "Y" and the "Rhino" field indices rhinoIndex = fieldList.index("Rhino") xIndex = fieldList.index("X") yIndex = fieldList.index("Y") ## print "Rhino "+str(rhinoIndex) +" X "+str(xIndex)+" Y "+str(yIndex) # Create a list / array for RhinoTracks rhinoTracks = {} # create the output feature class arcpy.CreateFeatureclass_management ("C:/WCGIS/Geog485/Lesson4", "Rhino.shp", "POLYLINE") # open an insert cursor for the new feature class cur = arcpy.InsertCursor(outname) # Loop through the rest of the file to read in all of the rhinos for line in observations.readlines(): ##Ben,26.99391,-19.10447,Bo, segmentedLine = line.split(",") rhino = segmentedLine[rhinoIndex] #print rhino # If rhino exists in dictionary - get the array from its key & add a point if rhino in rhinoTracks: coordArray = rhinoTracks[rhino] # create a new row or feature, in the feature class ## coordArray { [x,y] } lineArray = arcpy.Array() coord = arcpy.Point coord.X = segmentedLine[xIndex] coord.Y = segmentedLine[yIndex] ## add point to coordinate array coordArray.add(coord) #print "Rhino is "+rhino+" added point "+str(segmentedLine[xIndex])+" "+str(segmentedLine[yIndex]) ## coordArray { [x,y],[x1,y1] } feat = cur.newRow() # set the geometry of the new feature to the array of points feat.shape = lineArray #insert the feature cur.insertRow(feat) lineArray.removeAll() lineArray.add(coord) # If rhino doesn't exist in dictionary - make a new array & add a point else: cur = arcpy.InsertCursor(outname) ## Create a coordinate array coordArray = arcpy.Array ## Create a point object coord = arcpy.Point coord.X = segmentedLine[xIndex] coord.Y = segmentedLine[yIndex] ## add point to coordinate array *coordArray.add(coord) * feat = cur.newRow() # set the geometry of the new feature to the array of points feat.shape = lineArray #insert the feature cur.insertRow(feat) lineArray.removeAll() lineArray.add(coord) ## add coordinate array to my Dictionary (list of rhinos) rhinoTracks[rhino] = coordArray -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Sun Mar 4 05:49:35 2012 From: bgailer at gmail.com (bob gailer) Date: Sat, 03 Mar 2012 23:49:35 -0500 Subject: [Tutor] Creating a Polyline Feature class In-Reply-To: References: Message-ID: <4F52F45F.9030500@gmail.com> On 3/3/2012 11:21 PM, Carie Pigeon wrote: > I have an assignment to create a polyline feature class of rhino > tracks from a csv file. I am getting an error that says "unbound > method add() must be called with Array instance as first argument (got > type instance)". this is for line 104, the line I underlined and put > in bold below in my code. What does this mean? If there are other > obvious code issues, please feel free to comment. I am unsure if my > code is correct. Thank you for your time! > Cheers, > Carie > > # Reads rhino positions from an Excel-originating CSV file > > import arcpy > from arcpy import env > import fileinput > import string > import os > > env.overwriteOutput = True > > # Hard code file paths > spreadsheet = "C:/WCGIS/Geog485/Lesson4/ > RhinoObservations.csv" > > # Sample of data > ###Observer,X,Y,Rhino,Comments > ##Ben,26.99391,-19.10447,Bo, > ##Ben,27.00071,-19.1089,Tulip,Bathing > ##Ben,26.9919,-19.10511,Bo, > ##Ben,27.00071,-19.1059,Tulip, > ##Ben,26.96809,-19.09578,Patches, > ##Ben,26.97808,-19.11016,Dinky, > ##Ben,26.99213,-19.10395,Bo, > ##Ben,27.00083,-19.10326,Tulip, > ##Ben,26.97038,-19.09863,Patches,Not doing much of anything > ##Ben,26.97768,-19.11153,Dinky, > ##Ben,26.99107,-19.10421,Bo, > ##Ben,27.00138,-19.1021,Tulip, > ##Ben,26.97122,-19.0991,Patches, > ##Ben,26.97551,-19.11269,Dinky, > ##Ben,26.9904,-19.10553,Bo, > ##Ben,26.99893,-19.10342,Tulip, > > # output feature class?? feature class doesn't exist yet, so not sure > how to do this?? > fcname = "C:/WCGIS/Geog485/Lesson4" > outname = "C:/WCGIS/Geog485/Lesson4/Rhino.shp" > > > > # Open the CSV file & read the header line > observations = open(spreadsheet, "r") > headerline = observations.readline() > fieldList = headerline.split(",") > > ### 0 1 2 3 4 > ### Observer,X,Y,Rhino,Comments > # Look through the header to find "X", "Y" and the "Rhino" field indices > rhinoIndex = fieldList.index("Rhino") > xIndex = fieldList.index("X") > yIndex = fieldList.index("Y") > ## print "Rhino "+str(rhinoIndex) +" X "+str(xIndex)+" Y "+str(yIndex) > > # Create a list / array for RhinoTracks > rhinoTracks = {} > > # create the output feature class > arcpy.CreateFeatureclass_management ("C:/WCGIS/Geog485/Lesson4", > "Rhino.shp", "POLYLINE") > > # open an insert cursor for the new feature class > cur = arcpy.InsertCursor(outname) > > # Loop through the rest of the file to read in all of the rhinos > for line in observations.readlines(): > ##Ben,26.99391,-19.10447,Bo, > segmentedLine = line.split(",") > rhino = segmentedLine[rhinoIndex] > #print rhino > # If rhino exists in dictionary - get the array from its key & add > a point > if rhino in rhinoTracks: > coordArray = rhinoTracks[rhino] > # create a new row or feature, in the feature class > > > ## coordArray { [x,y] } > lineArray = arcpy.Array() > coord = arcpy.Point I am making educated guesses - try coord = arcpy.Point() > coord.X = segmentedLine[xIndex] > coord.Y = segmentedLine[yIndex] > ## add point to coordinate array > coordArray.add(coord) > #print "Rhino is "+rhino+" added point > "+str(segmentedLine[xIndex])+" "+str(segmentedLine[yIndex]) > ## coordArray { [x,y],[x1,y1] } > > feat = cur.newRow() > > # set the geometry of the new feature to the array of points > feat.shape = lineArray > > #insert the feature > cur.insertRow(feat) > lineArray.removeAll() > lineArray.add(coord) > > # If rhino doesn't exist in dictionary - make a new array & add a > point > else: > > cur = arcpy.InsertCursor(outname) > ## Create a coordinate array > coordArray = arcpy.Array try coordArray = arcpy.Array() > ## Create a point object > coord = arcpy.Point also try coord = arcpy.Point() > coord.X = segmentedLine[xIndex] > coord.Y = segmentedLine[yIndex] > ## add point to coordinate array > *_coordArray.add(coord) > > _* feat = cur.newRow() > > # set the geometry of the new feature to the array of points > feat.shape = lineArray > > #insert the feature > cur.insertRow(feat) > lineArray.removeAll() > lineArray.add(coord) > ## add coordinate array to my Dictionary (list of rhinos) > rhinoTracks[rhino] = coordArray Do you understand the difference between coord = arcpy.Point and coord = arcpy.Point() ? The first gets you a reference to the class. The 2nd gets you an instance of the class. Quite different. -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Sun Mar 4 06:06:55 2012 From: d at davea.name (Dave Angel) Date: Sun, 04 Mar 2012 00:06:55 -0500 Subject: [Tutor] Creating a Polyline Feature class In-Reply-To: References: Message-ID: <4F52F86F.9060204@davea.name> I see Bob Gailer has responded to your message while I was still trying to make sense of it. His "guesses" are probably right on. I have no knowledge of arcpy, so I can't directly answer your query. But I may be able to help you formulate a question that will solicit some answers. On 03/03/2012 11:21 PM, Carie Pigeon wrote: > I have an assignment to create a polyline feature class of rhino > tracks from a csv file. I am getting an error that says "unbound > method add() must be called with Array instance as first argument (got > type instance)". this is for line 104, the line I underlined and put > in bold below in my code. What does this mean? If there are other > obvious code issues, please feel free to comment. I am unsure if my > code is correct. Thank you for your time! > Cheers, > Carie > > coordArray.add(coord) There's no underline or bold here; this mailing list is a text based one, and attributes are dropped for most of us. If you want to tag a particular line, use a comment in the code, or put a row of dashes after it, or something. If you import a non-standard library, then give a web link so that interested people could actually look it up. In addition, tell the version that you're using. Similarly, you need to supply the python version, and probably the OS environment Windows 94, Atari 4.3, ...) When giving error messages, supply the whole stacktrace, not just the abbreviated error. The stacktrace would have shown the line that actually triggered the error. And in more complex code, it also would have shown the functions that called the one that had the error. As you surmise, there seem to be a number of problems with the code. But judicious use of print statements could have probably given you a lot of clues as to what was wrong. -- DaveA From ejjyrex at gmail.com Sun Mar 4 07:32:37 2012 From: ejjyrex at gmail.com (Ejaj Hassan) Date: Sun, 4 Mar 2012 12:02:37 +0530 Subject: [Tutor] Porting Message-ID: Hello, I am a novice in python development. I just came across this "Python porting 2.7 to 3.x" . I am just confused with this. Please tell me the whole meaning of it. Regards. Ejaj -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sun Mar 4 08:49:15 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 4 Mar 2012 18:49:15 +1100 Subject: [Tutor] Porting In-Reply-To: References: Message-ID: <20120304074915.GB1909@ando> On Sun, Mar 04, 2012 at 12:02:37PM +0530, Ejaj Hassan wrote: > Hello, > I am a novice in python development. I just came across this "Python > porting 2.7 to 3.x" . > I am just confused with this. Please tell me the whole meaning of it. Programmers talk about "porting" when they take code written in one language (say Java) and re-write it in another language (say, Python). Python 2.x (2.5, 2.6, 2.7) code is *slightly* different from Python 3.x code, like British English and American English. Just enough that many Python 2.x programs almost, but not quite, work in Python 3.x, and the same the other way around. So when you take a Python program written for version 2.7, and change it to work in Python 3.x, that's called "porting" too. -- Steven From mylesbroomes at hotmail.co.uk Sun Mar 4 12:59:55 2012 From: mylesbroomes at hotmail.co.uk (myles broomes) Date: Sun, 4 Mar 2012 11:59:55 +0000 Subject: [Tutor] Simple GUI Message-ID: Im trying to code a simple GUI but I'm having a bit of a problem. Heres my code: from tkinter import *class Application(Frame): def __init__(self,master=None): Frame.__init__(self,master) self.grid(sticky=N+S+E+W) self.createWidgets() def createWidgets(self): top=self.winfo_toplevel() top.rowconfigure(0,weight=1) top.columnconfigure(0,weight=1) self.rowconfigure(0,weight=1) self.columnconfigure(0,weight=1) self.Nothing = Button(self,text='Nothing',activebackground='red',cursor='gumby',command=self.configure()) self.Nothing.grid(row=0,column=0,sticky=N+S+E+W) def configure(self): self.Nothing.configure(text='Hello!')app = Application() app.master.title("The Nothing Button") app.mainloop() when I run the batch file, i get this error:Traceback (most recent call last): File "C:\Python32\gui2.py", line 21, in app = Application() File "C:\Python32\gui2.py", line 7, in __init__ self.createWidgets() File "C:\Python32\gui2.py", line 15, in createWidgets self.Nothing = Button(self,text='Nothing',activebackground='red',cursor='gumby',command=self.configure()) File "C:\Python32\gui2.py", line 19, in configure self.Nothing.configure(text='Hello!') AttributeError: 'Application' object has no attribute 'Nothing' What I get from that is that its claiming that my Application class doesnt have an attribute called 'Nothing' but I clearly defined it in the 'createWidgets()' method. Can anyone explain to me exactly what the problem is. Thanks. Myles Broomes -------------- next part -------------- An HTML attachment was scrubbed... URL: From evert.rol at gmail.com Sun Mar 4 13:29:18 2012 From: evert.rol at gmail.com (Evert Rol) Date: Sun, 4 Mar 2012 13:29:18 +0100 Subject: [Tutor] Simple GUI In-Reply-To: References: Message-ID: <5E3C658B-3485-4A7B-83B0-A4894583F967@gmail.com> > Im trying to code a simple GUI but I'm having a bit of a problem. Heres my code: > > from tkinter import * > class Application(Frame): > def __init__(self,master=None): > Frame.__init__(self,master) > self.grid(sticky=N+S+E+W) > self.createWidgets() > def createWidgets(self): > top=self.winfo_toplevel() > top.rowconfigure(0,weight=1) > top.columnconfigure(0,weight=1) > self.rowconfigure(0,weight=1) > self.columnconfigure(0,weight=1) > self.Nothing = Button(self,text='Nothing',activebackground='red',cursor='gumby',command=self.configure()) Here's your problem: you're setting command=self.configure(), but you mean command=self.configure. In the first way, you are actively calling the configure method. In the second, you're setting the command option to point to the method, but not calling it. In the latter case, an instance of Button can then latter call the configure method by running self.command(). So, when you now create a Button, you instantly run the configure method. Of course, at that point self.Nothing has not been defined yet. If you look carefully at the traceback, you can see exactly this: you go from line 15 in createWidgets immediately to line 19 in configure, because of the last part of line 15. In short: self.Nothing = Button(self,text='Nothing',activebackground='red',cursor='gumby',command=self.configure) is what you want. Evert > self.Nothing.grid(row=0,column=0,sticky=N+S+E+W) > def configure(self): > self.Nothing.configure(text='Hello!') > app = Application() > app.master.title("The Nothing Button") > app.mainloop() > > when I run the batch file, i get this error: > > Traceback (most recent call last): > File "C:\Python32\gui2.py", line 21, in > app = Application() > File "C:\Python32\gui2.py", line 7, in __init__ > self.createWidgets() > File "C:\Python32\gui2.py", line 15, in createWidgets > self.Nothing = Button(self,text='Nothing',activebackground='red',cursor='gumby',command=self.configure()) > File "C:\Python32\gui2.py", line 19, in configure > self.Nothing.configure(text='Hello!') > AttributeError: 'Application' object has no attribute 'Nothing' > > What I get from that is that its claiming that my Application class doesnt have an attribute called 'Nothing' but I clearly defined it in the 'createWidgets()' method. Can anyone explain to me exactly what the problem is. Thanks. > > Myles Broomes > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From d at davea.name Sun Mar 4 13:37:04 2012 From: d at davea.name (Dave Angel) Date: Sun, 04 Mar 2012 07:37:04 -0500 Subject: [Tutor] Simple GUI In-Reply-To: References: Message-ID: <4F5361F0.8070401@davea.name> On 03/04/2012 06:59 AM, myles broomes wrote: > Im trying to code a simple GUI but I'm having a bit of a problem. Heres my code: from tkinter import *class Application(Frame): > def __init__(self,master=None): > Frame.__init__(self,master) > self.grid(sticky=N+S+E+W) > self.createWidgets() def createWidgets(self): > top=self.winfo_toplevel() > top.rowconfigure(0,weight=1) > top.columnconfigure(0,weight=1) > self.rowconfigure(0,weight=1) > self.columnconfigure(0,weight=1) > self.Nothing = Button(self,text='Nothing',activebackground='red',cursor='gumby',command=self.configure()) > self.Nothing.grid(row=0,column=0,sticky=N+S+E+W) def configure(self): > self.Nothing.configure(text='Hello!')app = Application() > app.master.title("The Nothing Button") > app.mainloop() when I run the batch file, i get this error:Traceback (most recent call last): > File "C:\Python32\gui2.py", line 21, in > app = Application() > File "C:\Python32\gui2.py", line 7, in __init__ > self.createWidgets() > File "C:\Python32\gui2.py", line 15, in createWidgets > self.Nothing = Button(self,text='Nothing',activebackground='red',cursor='gumby',command=self.configure()) > File "C:\Python32\gui2.py", line 19, in configure > self.Nothing.configure(text='Hello!') > AttributeError: 'Application' object has no attribute 'Nothing' What I get from that is that its claiming that my Application class doesnt have an attribute called 'Nothing' but I clearly defined it in the 'createWidgets()' method. Can anyone explain to me exactly what the problem is. Thanks. > > Myles Broomes > > Please post in plain-text. Your indentation got messed up in a couple of places. In this case, i didn't have any trouble deciphering it, but I've seen cases where the source was totally useless when posted in html. The problem is simply that you're calling Application.configure() during the call to create the Button, and you don't assign it to self.Nothing till the Button object is created. I don't know tkinter well enough (I've never used it) to know how to fix it, but generally, you want to fully create a object before you try to call your own methods on it. One possibility (since I don't know tkinter) is that the command= argument is supposed to be a function object, which will be called at some later point. IF that's the case, you want to omit the parentheses here. .... cursor='gumby', command=self.configure) HTH, -- DaveA From bgailer at gmail.com Mon Mar 5 01:03:58 2012 From: bgailer at gmail.com (bob gailer) Date: Sun, 04 Mar 2012 19:03:58 -0500 Subject: [Tutor] Creating a Polyline Feature class In-Reply-To: References: <4F52F45F.9030500@gmail.com> Message-ID: <4F5402EE.1010807@gmail.com> Please always reply-all so a copy goes to the list. I' copying the list on this reply. Also we like it better when you put your responses in the body of the email close to what they apply to rather than at top. Also remove irrelevant text to keep the emails short and to the point. On 3/4/2012 5:39 PM, Carie Pigeon wrote: > Ok, cool, that makes sense! Thank you for pointing that out. I ran > it with that correction...but now I am getting another error... > "Traceback (most recent call last): > File > "C:\Python26\ArcGIS10.0\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", > line 312, in RunScript > exec codeObject in __main__.__dict__ > File "C:\WCGIS\Geog485\Lesson4\Lesson4.py", line 109, in > feat.shape = arcpy.Array() > File "C:\Program Files > (x86)\ArcGIS\Desktop10.0\arcpy\arcpy\arcobjects\_base.py", line 35, in > __setattr__ > return setattr(self._arc_object, attr, ao) > RuntimeError: ERROR 999999: Error executing function." > > Any ideas? I'm feeling a little lost at this point. Diagnosing that requires a knowledge of ArcGIS which I lack. -- Bob Gailer 919-636-4239 Chapel Hill NC From sweetnivi88 at gmail.com Mon Mar 5 07:24:12 2012 From: sweetnivi88 at gmail.com (nivedita datta) Date: Mon, 5 Mar 2012 11:54:12 +0530 Subject: [Tutor] Blum blum shub pseudorandom generator Message-ID: Hi, Can anyone send me a working code of BBS pseudorandom number generator. Regards, Nivedita -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Mar 5 09:33:46 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 05 Mar 2012 08:33:46 +0000 Subject: [Tutor] Blum blum shub pseudorandom generator In-Reply-To: References: Message-ID: On 05/03/12 06:24, nivedita datta wrote: > Hi, > > Can anyone send me a working code of BBS pseudorandom number generator. This list is for people learning the Python programming language. You might get lucky and someone has this code but you're far more likely to find somebody by posting on a more specific forum, or even on the main python usenet list at comp.lang.python. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From bugcy013 at gmail.com Mon Mar 5 10:31:14 2012 From: bugcy013 at gmail.com (Ganesh Kumar) Date: Mon, 5 Mar 2012 15:01:14 +0530 Subject: [Tutor] How to start with Glade. Message-ID: Hi Guys, I am new to GUI, I know little bit python, But I do know, How to start with Glade and how to combine with .glade file to python. please guide me.. -Ganesh Did I learn something today? If not, I wasted it. -------------- next part -------------- An HTML attachment was scrubbed... URL: From timomlists at gmail.com Mon Mar 5 10:45:20 2012 From: timomlists at gmail.com (Timo) Date: Mon, 05 Mar 2012 10:45:20 +0100 Subject: [Tutor] How to start with Glade. In-Reply-To: References: Message-ID: <4F548B30.1070708@gmail.com> Op 05-03-12 10:31, Ganesh Kumar schreef: > Hi Guys, > > I am new to GUI, I know little bit python, But I do know, How to start > with Glade > and how to combine with .glade file to python. please guide me.. This is more of a question for the PyGTK mailing list. This is the bare minimum you need: import gtk builder = gtk.Builder() builder.add_from_file("mywindow.ui") gtk.main() Ofcourse, alot more can/needs to be done, like connecting signals. You should have a google session for "pygtk glade" or something similar and plenty of good tutorials and blogposts will show up that will explain these things. Timo > > -Ganesh > > Did I learn something today? If not, I wasted it. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From steve at pearwood.info Mon Mar 5 12:40:57 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 05 Mar 2012 22:40:57 +1100 Subject: [Tutor] Blum blum shub pseudorandom generator In-Reply-To: References: Message-ID: <4F54A649.8090407@pearwood.info> nivedita datta wrote: > Hi, > > Can anyone send me a working code of BBS pseudorandom number generator. I'll do even better than send you working code for BBS -- I'll send you a link to how you can find working code for nearly ANYTHING! https://duckduckgo.com/html/?q=download+%22blum+blum+shub%22&b= When you have a question about learning Python, please come back and we'll be happy to help you. -- Steven From marko.limbek at valicon.net Mon Mar 5 13:37:05 2012 From: marko.limbek at valicon.net (Marko Limbek) Date: Mon, 5 Mar 2012 13:37:05 +0100 Subject: [Tutor] Question about writing to Excel with slavic characters Message-ID: Hi everyone. I am new to list and few months old to Python. I am writing some text to Excel and I open the new book and try to write to the book and the save it using book.save Now when I write slavic characters in the text to Excel (?, ?, ?, for instance 0xc5), I get an error, I can't save it. I have declared appropriate encoding # -*- coding: utf-8 -*- # coding= #!/E:/Python and those characters appear normally in the code, but there seems to be the problem with the function book.save. Does anyone have any ideas, what would be the problem and how to solve it? Some additional encoding or some changes or parameters to the book.save method? Is that the right forum for my question? Thank you, Marko From cwitts at compuscan.co.za Mon Mar 5 13:46:02 2012 From: cwitts at compuscan.co.za (Christian Witts) Date: Mon, 05 Mar 2012 14:46:02 +0200 Subject: [Tutor] Question about writing to Excel with slavic characters In-Reply-To: References: Message-ID: <4F54B58A.7020402@compuscan.co.za> On 2012/03/05 02:37 PM, Marko Limbek wrote: > Hi everyone. > > > I am new to list and few months old to Python. I am writing some text > to Excel and I open the new book and try to write to the book and the > save it using > > book.save > > Now when I write slavic characters in the text to Excel (?, ?, ?, for > instance 0xc5), I get an error, I can't save it. > I have declared appropriate encoding > > # -*- coding: utf-8 -*- > # coding= > #!/E:/Python > > and those characters appear normally in the code, but there seems to > be the problem with the function book.save. > Does anyone have any ideas, what would be the problem and how to solve > it? Some additional encoding or some changes or parameters to the > book.save method? > > Is that the right forum for my question? > > > Thank you, > > Marko > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor What package are you using to create your Excel workbook ? If it's xlwt you can set your encoding type when you create your workbook book = xlwt.Workbook(encoding="utf-8") -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From marko.limbek at valicon.net Mon Mar 5 14:05:10 2012 From: marko.limbek at valicon.net (Marko Limbek) Date: Mon, 5 Mar 2012 14:05:10 +0100 Subject: [Tutor] Question about writing to Excel with slavic characters In-Reply-To: <4F54B58A.7020402@compuscan.co.za> References: <4F54B58A.7020402@compuscan.co.za> Message-ID: Thank you! That was easy. Now I have another problem. I use RPy and read the spss database with method read.spss inside a nested R code in Python, that looks like that: import rpy r(""" library(foreign) baza <- read.spss(""" + analysis[0] + """) print(baza$demo_izob0) """) Now when my text data labels in spss have slavic characters, they are not recognised and output is something like that: stiriletna srednja ?ola nedokon?ana osnovna ?ola What should I do here? Thanks a lot, Marko On Mon, Mar 5, 2012 at 1:46 PM, Christian Witts wrote: > On 2012/03/05 02:37 PM, Marko Limbek wrote: > > Hi everyone. > > > I am new to list and few months old to Python. I am writing some text > to Excel and I open the new book and try to write to the book and the > save it using > > book.save > > Now when I write slavic characters in the text to Excel (?, ?, ?, for > instance 0xc5), I get an error, I can't save it. > I have declared appropriate encoding > > # -*- coding: utf-8 -*- > # coding= > #!/E:/Python > > and those characters appear normally in the code, but there seems to > be the problem with the function book.save. > Does anyone have any ideas, what would be the problem and how to solve > it? Some additional encoding or some changes or parameters to the > book.save method? > > Is that the right forum for my question? > > > Thank you, > > Marko > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > What package are you using to create your Excel workbook ? > If it's xlwt you can set your encoding type when you create your workbook > book = xlwt.Workbook(encoding="utf-8") > -- > > Christian Witts > Python Developer From cwitts at compuscan.co.za Mon Mar 5 14:24:52 2012 From: cwitts at compuscan.co.za (Christian Witts) Date: Mon, 05 Mar 2012 15:24:52 +0200 Subject: [Tutor] Question about writing to Excel with slavic characters In-Reply-To: References: <4F54B58A.7020402@compuscan.co.za> Message-ID: <4F54BEA4.3070009@compuscan.co.za> On 2012/03/05 03:05 PM, Marko Limbek wrote: > Thank you! > > That was easy. Now I have another problem. > I use RPy and read the spss database with method read.spss inside a > nested R code in Python, that looks like that: > > > import rpy > > r(""" > > library(foreign) > > baza<- read.spss(""" + analysis[0] + """) > > print(baza$demo_izob0) > > """) > > Now when my text data labels in spss have slavic characters, they are > not recognised and output is something like that: > > stiriletna srednja ?ola > nedokon?ana osnovna ?ola > > > What should I do here? > > > Thanks a lot, > > > Marko > > > > > On Mon, Mar 5, 2012 at 1:46 PM, Christian Witts wrote: >> On 2012/03/05 02:37 PM, Marko Limbek wrote: >> >> Hi everyone. >> >> >> I am new to list and few months old to Python. I am writing some text >> to Excel and I open the new book and try to write to the book and the >> save it using >> >> book.save >> >> Now when I write slavic characters in the text to Excel (?, ?, ?, for >> instance 0xc5), I get an error, I can't save it. >> I have declared appropriate encoding >> >> # -*- coding: utf-8 -*- >> # coding= >> #!/E:/Python >> >> and those characters appear normally in the code, but there seems to >> be the problem with the function book.save. >> Does anyone have any ideas, what would be the problem and how to solve >> it? Some additional encoding or some changes or parameters to the >> book.save method? >> >> Is that the right forum for my question? >> >> >> Thank you, >> >> Marko >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> What package are you using to create your Excel workbook ? >> If it's xlwt you can set your encoding type when you create your workbook >> book = xlwt.Workbook(encoding="utf-8") >> -- >> >> Christian Witts >> Python Developer > > Hi, you should avoid top-posting as it makes it hard to follow the thread if people have to bounce between the top and bottom of the post. As for the answer to your question, I would suggest the R Mailing List if they have any issues with Unicode or need any encodings set when loading data etc. There was a bug with Unicode support & RPy <2.2 but that was fixed last year so if you have a recent version of RPy that shouldn't be the issue. -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Mon Mar 5 15:17:35 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 06 Mar 2012 01:17:35 +1100 Subject: [Tutor] Question about writing to Excel with slavic characters In-Reply-To: References: <4F54B58A.7020402@compuscan.co.za> Message-ID: <4F54CAFF.5070706@pearwood.info> Marko Limbek wrote: > Thank you! > > That was easy. Now I have another problem. > I use RPy and read the spss database with method read.spss inside a > nested R code in Python, that looks like that: > > > import rpy > > r(""" > library(foreign) > baza <- read.spss(""" + analysis[0] + """) > print(baza$demo_izob0) > """) > > Now when my text data labels in spss have slavic characters, they are > not recognised and output is something like that: > > stiriletna srednja ?ola > nedokon?ana osnovna ?ola > > > What should I do here? Since the SPSS labels are being read by R, not Python, my guess is that this is likely a problem with R, not Python. You might find the rpy mailing list more helpful for solving rpy problems. https://lists.sourceforge.net/lists/listinfo/rpy-list Good luck! -- Steven From wprins at gmail.com Mon Mar 5 18:14:28 2012 From: wprins at gmail.com (Walter Prins) Date: Mon, 5 Mar 2012 17:14:28 +0000 Subject: [Tutor] Blum blum shub pseudorandom generator In-Reply-To: <4F54A649.8090407@pearwood.info> References: <4F54A649.8090407@pearwood.info> Message-ID: Nivedita Steven D'Aprano wrote: > I'll do even better than send you working code for BBS -- I'll send you a > link to how you can find working code for nearly ANYTHING! > > https://duckduckgo.com/html/?q=download+%22blum+blum+shub%22&b= I'd like to just add to Steven's response and point out that there's actually even a python BBS implementation available as well if you include python in the search terms: https://duckduckgo.com/html/?q=python+%22blum+blum+shub%22&b= (... darn but these seach engine thingies are clever eh? Might be an idea to try them first next time prior to posting.) Walter From fomcl at yahoo.com Mon Mar 5 20:20:45 2012 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Mon, 5 Mar 2012 11:20:45 -0800 (PST) Subject: [Tutor] Question about writing to Excel with slavic characters In-Reply-To: References: <4F54B58A.7020402@compuscan.co.za> Message-ID: <1330975245.71342.YahooMailNeo@web110714.mail.gq1.yahoo.com> Hi, The R package foreign, in particular the read.spss function has some known problems reading spss system files. The memisc package also has a function to read .sav files. The big advantage of that function is that you can select rows and columns prior to actually reading the data into memory. If you're just using R and Rpy to read .sav files, you could also consider using a Python program that I wrote a while ago: http://code.activestate.com/recipes/577811-python-reader-writer-for-spss-sav-files-linux-mac-/ It runs on Windows, Mac and Linux and requires no installation of spss. I'd be interested to hear your experiences. ? Regards, Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~? >________________________________ > From: Marko Limbek >To: cwitts at compuscan.co.za >Cc: tutor at python.org >Sent: Monday, March 5, 2012 2:05 PM >Subject: Re: [Tutor] Question about writing to Excel with slavic characters > >Thank you! > >That was easy. Now I have another problem. >I use RPy and read the spss database with method read.spss inside a >nested R code in Python, that looks like that: > > >import rpy > >r(""" > >library(foreign) > >baza <- read.spss(""" + analysis[0] + """) > >print(baza$demo_izob0) > >""") > >Now when my text data labels in spss have slavic characters, they are >not recognised and output is something like that: > >stiriletna srednja ?ola >nedokon?ana osnovna ?ola > > >What should I do here? > > >Thanks a lot, > > >Marko > > > > >On Mon, Mar 5, 2012 at 1:46 PM, Christian Witts wrote: >> On 2012/03/05 02:37 PM, Marko Limbek wrote: >> >> Hi everyone. >> >> >> I am new to list and few months old to Python. I am writing some text >> to Excel and I open the new book and try to write to the book and the >> save it using >> >> book.save >> >> Now when I write slavic characters in the text to Excel (?, ?, ?, for >> instance 0xc5), I get an error, I can't save it. >> I have declared appropriate encoding >> >> # -*- coding: utf-8 -*- >> # coding= >> #!/E:/Python >> >> and those characters appear normally in the code, but there seems to >> be the problem with the function book.save. >> Does anyone have any ideas, what would be the problem and how to solve >> it? Some additional encoding or some changes or parameters to the >> book.save method? >> >> Is that the right forum for my question? >> >> >> Thank you, >> >> Marko >> _______________________________________________ >> Tutor maillist? -? Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> What package are you using to create your Excel workbook ? >> If it's xlwt you can set your encoding type when you create your workbook >> book = xlwt.Workbook(encoding="utf-8") >> -- >> >> Christian Witts >> Python Developer >_______________________________________________ >Tutor maillist? -? Tutor at python.org >To unsubscribe or change subscription options: >http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From fomcl at yahoo.com Mon Mar 5 21:16:13 2012 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Mon, 5 Mar 2012 12:16:13 -0800 (PST) Subject: [Tutor] question about operator overloading Message-ID: <1330978573.3874.YahooMailNeo@web110704.mail.gq1.yahoo.com> Hi, I am extending a program for a hobby project where potentially huge spss files are read. I would like to add functionality to append files. I thought it would be nice and intuitive to overload + and += for this. The code below is a gross simplification, but I want to get the basics right. Is this the way how operator overloading is usually done? class Append(object): ??? def __init__(self, file1, file2=None): ??????? """ file1 and file2 will actually be of a class of my own, ??????? which has a readFile method that is a generator that returns ??????? one record at a time """ ??????? self.file1 = file1 ??????? self.file2 = file2 ??????? self.merged = [] ??? def __add__(self): ??????? self.file1.extend(self.file2) ??????? return self.file1 ??? def __iadd__(self): ??????? self.merged.extend(self.file1) ??????? return self.merged ??????? ??? def writerows(self): ??????? rows = self.file1 ??????? for row in rows: ??????????? yield row # overloading '+' file1 = [[1, 2, 3], [4, 5, 6], [6, 6, 6]]??????? file2 = [[1, 2, 3]] app = Append(file1, file2) merged = app.file1 + app.file2 # 'merged'? will not actually hold data for line in app.writerows(): ??? print line # overloading '+=' files = [file1, file2] for i, f in enumerate(files): ??? if i == 0: ??????? app = Append(f) ??????? app.merged = f ??? else: ??????? app.merged += f print app.merged ? Thank you in advance! Regards, Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~? -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Mon Mar 5 21:36:34 2012 From: d at davea.name (Dave Angel) Date: Mon, 05 Mar 2012 15:36:34 -0500 Subject: [Tutor] question about operator overloading In-Reply-To: <1330978573.3874.YahooMailNeo@web110704.mail.gq1.yahoo.com> References: <1330978573.3874.YahooMailNeo@web110704.mail.gq1.yahoo.com> Message-ID: <4F5523D2.7070601@davea.name> On 03/05/2012 03:16 PM, Albert-Jan Roskam wrote: > Hi, > > I am extending a program for a hobby project where potentially huge spss files are read. I would like to add functionality to append files. I thought it would be nice and intuitive to overload + and += for this. The code below is a gross simplification, but I want to get the basics right. Is this the way how operator overloading is usually done? > > > class Append(object): > > def __init__(self, file1, file2=None): > """ file1 and file2 will actually be of a class of my own, > which has a readFile method that is a generator that returns > one record at a time """ > self.file1 = file1 > self.file2 = file2 > self.merged = [] > > def __add__(self): > self.file1.extend(self.file2) > return self.file1 > > def __iadd__(self): > self.merged.extend(self.file1) > return self.merged > > def writerows(self): > rows = self.file1 > for row in rows: > yield row > > # overloading '+' > file1 = [[1, 2, 3], [4, 5, 6], [6, 6, 6]] > file2 = [[1, 2, 3]] > app = Append(file1, file2) > merged = app.file1 + app.file2 # 'merged' will not actually hold data > for line in app.writerows(): > print line > > # overloading '+=' > files = [file1, file2] > for i, f in enumerate(files): > if i == 0: > app = Append(f) > app.merged = f > else: > app.merged += f > print app.merged > I hate to say it, but it's not even close. When you say app.file1 + app.file2, you're not calling either of your special methods you defined in Append. You're just adding the file1 and file2 attributes. Since in your example these are lists, they do the usual thing. Similarly, your app.merged += f does NOT call your __iadd__() method. Just what kind of an object is an Append object supposed to be? Classes are usually for encapsulating data and behavior, not just to bundle up some functions. Normally, you should be defining the __add__() and __iadd__() methods in the class that file1 and file2 are instances of. So if you want to make a dummy example, start by defining a (single) class that holds just one of these. Then create two instances, and try adding and +='ing the two instances. DaveA -- DaveA From fomcl at yahoo.com Mon Mar 5 22:10:26 2012 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Mon, 5 Mar 2012 13:10:26 -0800 (PST) Subject: [Tutor] question about operator overloading In-Reply-To: <4F5523D2.7070601@davea.name> References: <1330978573.3874.YahooMailNeo@web110704.mail.gq1.yahoo.com> <4F5523D2.7070601@davea.name> Message-ID: <1330981826.96115.YahooMailNeo@web110712.mail.gq1.yahoo.com> Hi Dave, aha! Good thing I asked. ;-) I've indeed been thinking where this __add__ method should live. The program as it is now has a Generic class, a Reader class and a Writer class. I thought an Append class was appropriate because it uses Reader and Writer (and probably also Generic) methods and the data is from multiple files. It reads a bunch of files (even though the term 'reading' is more a conceptual term here, as none of the data will be held in memory), appends them (__add__), and writes them to one merged file. Doesn't adding __add__ change the responsibility from 'thou shallt read one and only one file' into something less precise? So if I understand you correctly, the following pseudocode is better? merged = Reader.readFile(somefile1) + Reader.readFile(somefile2) # ..which is the same as: Reader.readFile(somefile1).__add__(Reader.readFile(somefile2)) for line in merged: ? Writer.writerow(line) Maybe this is why my 'top-down code' (what I posted earlier) and my 'bottom-up code' (some code that I wrote earlier) don't add up (pun intended!). In the bottom-up code there was no need for an Append class! ? Regards, Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~? >________________________________ > From: Dave Angel >To: Albert-Jan Roskam >Cc: Python Mailing List >Sent: Monday, March 5, 2012 9:36 PM >Subject: Re: [Tutor] question about operator overloading > >On 03/05/2012 03:16 PM, Albert-Jan Roskam wrote: >> Hi, >> >> I am extending a program for a hobby project where potentially huge spss files are read. I would like to add functionality to append files. I thought it would be nice and intuitive to overload + and += for this. The code below is a gross simplification, but I want to get the basics right. Is this the way how operator overloading is usually done? >> >> >> class Append(object): >> >>? ? ? def __init__(self, file1, file2=None): >>? ? ? ? ? """ file1 and file2 will actually be of a class of my own, >>? ? ? ? ? which has a readFile method that is a generator that returns >>? ? ? ? ? one record at a time """ >>? ? ? ? ? self.file1 = file1 >>? ? ? ? ? self.file2 = file2 >>? ? ? ? ? self.merged = [] >> >>? ? ? def __add__(self): >>? ? ? ? ? self.file1.extend(self.file2) >>? ? ? ? ? return self.file1 >> >>? ? ? def __iadd__(self): >>? ? ? ? ? self.merged.extend(self.file1) >>? ? ? ? ? return self.merged >>? ? ? ? ? ? ? def writerows(self): >>? ? ? ? ? rows = self.file1 >>? ? ? ? ? for row in rows: >>? ? ? ? ? ? ? yield row >> >> # overloading '+' >> file1 = [[1, 2, 3], [4, 5, 6], [6, 6, 6]]? ? ? file2 = [[1, 2, 3]] >> app = Append(file1, file2) >> merged = app.file1 + app.file2 # 'merged'? will not actually hold data >> for line in app.writerows(): >>? ? ? print line >> >> # overloading '+=' >> files = [file1, file2] >> for i, f in enumerate(files): >>? ? ? if i == 0: >>? ? ? ? ? app = Append(f) >>? ? ? ? ? app.merged = f >>? ? ? else: >>? ? ? ? ? app.merged += f >> print app.merged >> > >I hate to say it, but it's not even close. > >When you say? app.file1 + app.file2,? you're not calling either of your special methods you defined in Append.? You're just adding the file1 and file2 attributes.? Since in your example these are lists, they do the usual thing. > >Similarly, your app.merged += f? does NOT call your __iadd__() method. > >Just what kind of an object is an Append object supposed to be?? Classes are usually for encapsulating data and behavior, not just to bundle up some functions. > >Normally, you should be defining the __add__() and __iadd__() methods in the class that file1 and file2 are instances of.? So if you want to make a dummy example, start by defining a (single) class that holds just one of these.? Then create two instances, and try adding and +='ing the two instances. > > > >DaveA > > >-- >DaveA > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Mon Mar 5 22:25:33 2012 From: d at davea.name (Dave Angel) Date: Mon, 05 Mar 2012 16:25:33 -0500 Subject: [Tutor] question about operator overloading In-Reply-To: <1330981826.96115.YahooMailNeo@web110712.mail.gq1.yahoo.com> References: <1330978573.3874.YahooMailNeo@web110704.mail.gq1.yahoo.com> <4F5523D2.7070601@davea.name> <1330981826.96115.YahooMailNeo@web110712.mail.gq1.yahoo.com> Message-ID: <4F552F4D.4070805@davea.name> On 03/05/2012 04:10 PM, Albert-Jan Roskam wrote: > Hi Dave, > > aha! Good thing I asked. ;-) I've indeed been thinking where this __add__ method should live. The program as it is now has a Generic class, a Reader class and a Writer class. I thought an Append class was appropriate because it uses Reader and Writer (and probably also Generic) methods and the data is from multiple files. It reads a bunch of files (even though the term 'reading' is more a conceptual term here, as none of the data will be held in memory), appends them (__add__), and writes them to one merged file. Doesn't adding __add__ change the responsibility from 'thou shallt read one and only one file' into something less precise? > > > So if I understand you correctly, the following pseudocode is better? > > merged = Reader.readFile(somefile1) + Reader.readFile(somefile2) > # ..which is the same as: Reader.readFile(somefile1).__add__(Reader.readFile(somefile2)) > for line in merged: > Writer.writerow(line) > > > Maybe this is why my 'top-down code' (what I posted earlier) and my 'bottom-up code' (some code that I wrote earlier) don't add up (pun intended!). In the bottom-up code there was no need for an Append class! > Please don't top-post. We've now lost all the context of what happened before. You still don't get it. If you're going to add objects, they should be objects that represent what's being added. So the objects are of type MyFile, not type Reader, whatever that is. Reader and Writer sounds like a java approach. So you combine two files something like this: file1 = MyFile(whatever, moreargs) file2 = MyFile(whateverelse, lessargs) file1 += file2 that last line will call the method __iadd__() of class MyFile. Self will be file1, and the other parameter will be file2. By convention, it'd add file2 to the end of already-existing file1. It's not clear what __add__() should mean for physical files. It builds something (MyFile instance) that represents two of them, but there's no way to assign a filename to it, except after the fact. So it might be an in-memory equivalent (eg. a list). It should NOT just extend the first file. Generally, it shouldn't modify either of its arguments. By the way, you could have learned a lot in your original example by just adding print statements in the two methods. -- DaveA From alan.gauld at btinternet.com Tue Mar 6 00:20:21 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 05 Mar 2012 23:20:21 +0000 Subject: [Tutor] question about operator overloading In-Reply-To: <4F552F4D.4070805@davea.name> References: <1330978573.3874.YahooMailNeo@web110704.mail.gq1.yahoo.com> <4F5523D2.7070601@davea.name> <1330981826.96115.YahooMailNeo@web110712.mail.gq1.yahoo.com> <4F552F4D.4070805@davea.name> Message-ID: On 05/03/12 21:25, Dave Angel wrote: > It's not clear what __add__() should mean for physical files. My guess would be similar to the cat operator in Unix: $ cat file1, file2 > file3 is equivalent to file3 = file1 + file2 But of course, thats just my interpretation of file addition... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From joel.goldstick at gmail.com Tue Mar 6 00:35:57 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 5 Mar 2012 18:35:57 -0500 Subject: [Tutor] question about operator overloading In-Reply-To: References: <1330978573.3874.YahooMailNeo@web110704.mail.gq1.yahoo.com> <4F5523D2.7070601@davea.name> <1330981826.96115.YahooMailNeo@web110712.mail.gq1.yahoo.com> <4F552F4D.4070805@davea.name> Message-ID: On Mon, Mar 5, 2012 at 6:20 PM, Alan Gauld wrote: > On 05/03/12 21:25, Dave Angel wrote: > >> It's not clear what __add__() should mean for physical files. > > > My guess would be similar to the cat operator in Unix: > > $ cat file1, file2 > file3 > > is equivalent to > > file3 = file1 + file2 > > But of course, thats just my interpretation of file addition... > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor if spss files are text (not binary) why not: f1 = open("f1")read() f2 = open("f2")read() outfile = open("outfile", "w") outfile.write(f1 + f2) outfile.close() You could put this in a function and pass all infiles as *filenames, then loop to read each file and output result -- Joel Goldstick From joel.goldstick at gmail.com Tue Mar 6 00:37:31 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 5 Mar 2012 18:37:31 -0500 Subject: [Tutor] question about operator overloading In-Reply-To: References: <1330978573.3874.YahooMailNeo@web110704.mail.gq1.yahoo.com> <4F5523D2.7070601@davea.name> <1330981826.96115.YahooMailNeo@web110712.mail.gq1.yahoo.com> <4F552F4D.4070805@davea.name> Message-ID: On Mon, Mar 5, 2012 at 6:35 PM, Joel Goldstick wrote: > On Mon, Mar 5, 2012 at 6:20 PM, Alan Gauld wrote: >> On 05/03/12 21:25, Dave Angel wrote: >> >>> It's not clear what __add__() should mean for physical files. >> >> >> My guess would be similar to the cat operator in Unix: >> >> $ cat file1, file2 > file3 >> >> is equivalent to >> >> file3 = file1 + file2 >> >> But of course, thats just my interpretation of file addition... >> >> -- >> Alan G >> Author of the Learn to Program web site >> http://www.alan-g.me.uk/ >> >> >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > if spss files are text (not binary) why not: > oops forgot the dots. > f1 = open("f1").read() > f2 = open("f2").read() > > outfile = open("outfile", "w") > outfile.write(f1 + f2) > outfile.close() > > You could put this in a function and pass all infiles as *filenames, > then loop to read each file and output result > > > > -- > Joel Goldstick -- Joel Goldstick From steve at pearwood.info Tue Mar 6 01:58:45 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 06 Mar 2012 11:58:45 +1100 Subject: [Tutor] question about operator overloading In-Reply-To: References: <1330978573.3874.YahooMailNeo@web110704.mail.gq1.yahoo.com> <4F5523D2.7070601@davea.name> <1330981826.96115.YahooMailNeo@web110712.mail.gq1.yahoo.com> <4F552F4D.4070805@davea.name> Message-ID: <4F556145.8050706@pearwood.info> Alan Gauld wrote: > On 05/03/12 21:25, Dave Angel wrote: > >> It's not clear what __add__() should mean for physical files. > > My guess would be similar to the cat operator in Unix: > > $ cat file1, file2 > file3 > > is equivalent to > > file3 = file1 + file2 > > But of course, thats just my interpretation of file addition... I think that's what Albert-Jan is probably thinking, but the two models are not quite the same. I think that what he wants is probably closer to something like the fileinput module. I think what he wants is to avoid this: for f in (file1, file2, file3, file4): for record in f: process(record) in favour of this: all_the_files = file1 + file2 + file3 + file4 # merge file contents for record in all_the_files: process(record) Albert-Jan, am I close? If not, please explain what you are trying to accomplish. If the files are small, the easy way is to just read their contents, add them together as strings or lists, and then process the lot. But if the files are big, or you want to process them on-demand instead of up-front, you need an approach similar to fileinput. Personally, all these Reader and Append objects make my brain hurt, and I hardly ever use operator overloading, except perhaps for numeric types. Reader objects, I can just get. But "Append" objects? This may be useful: http://steve-yegge.blogspot.com.au/2006/03/execution-in-kingdom-of-nouns.html and also itertools: from itertools import chain merged = chain(file1, file2, file3, file4) for record in merged: process(record) -- Steven From d at davea.name Tue Mar 6 03:42:33 2012 From: d at davea.name (Dave Angel) Date: Mon, 05 Mar 2012 21:42:33 -0500 Subject: [Tutor] question about operator overloading In-Reply-To: References: <1330978573.3874.YahooMailNeo@web110704.mail.gq1.yahoo.com> <4F5523D2.7070601@davea.name> <1330981826.96115.YahooMailNeo@web110712.mail.gq1.yahoo.com> <4F552F4D.4070805@davea.name> Message-ID: <4F557999.4010309@davea.name> On 03/05/2012 06:20 PM, Alan Gauld wrote: > On 05/03/12 21:25, Dave Angel wrote: > >> It's not clear what __add__() should mean for physical files. > > My guess would be similar to the cat operator in Unix: > > $ cat file1, file2 > file3 > > is equivalent to > > file3 = file1 + file2 > > But of course, thats just my interpretation of file addition... > So somehow assigning the object to file3 will write the data to a file by the name "file3" ? I know about __add__(), but didn't know we had __assign__() -- DaveA From __peter__ at web.de Tue Mar 6 09:35:08 2012 From: __peter__ at web.de (Peter Otten) Date: Tue, 06 Mar 2012 09:35:08 +0100 Subject: [Tutor] question about operator overloading References: <1330978573.3874.YahooMailNeo@web110704.mail.gq1.yahoo.com> <4F5523D2.7070601@davea.name> <1330981826.96115.YahooMailNeo@web110712.mail.gq1.yahoo.com> <4F552F4D.4070805@davea.name> <4F557999.4010309@davea.name> Message-ID: Dave Angel wrote: > On 03/05/2012 06:20 PM, Alan Gauld wrote: >> On 05/03/12 21:25, Dave Angel wrote: >> >>> It's not clear what __add__() should mean for physical files. >> >> My guess would be similar to the cat operator in Unix: >> >> $ cat file1, file2 > file3 >> >> is equivalent to >> >> file3 = file1 + file2 >> >> But of course, thats just my interpretation of file addition... >> > > So somehow assigning the object to file3 will write the data to a file > by the name "file3" ? I know about __add__(), but didn't know we had > __assign__() That is indeed one problem that makes an approach based on operator overloading clumsy here. You can either invent a name for file3 or defer writing the file: file3 = file1 + file2 file3.save_as(filename) Below is an implementation with a made-up destination file name: $ cat roskam.py import os def remove(filename): try: os.remove(filename) except OSError: pass class File(object): def __init__(self, filename): self.filename = filename def __iadd__(self, other): with self.open("a") as dest, other.open() as source: dest.writelines(source) return self def __add__(self, other): result = File("+".join([self.filename, other.filename])) remove(result.filename) result += self result += other return result def open(self, *mode): return open(self.filename, *mode) def __str__(self): return self.filename + ":\n" + "".join(" " + line for line in self.open()) if __name__ == "__main__": remove("file3") remove("file4") with open("file1", "w") as f: f.write("""\ alpha beta gamma """) with open("file2", "w") as f: f.write("""\ DELTA EPSILON """) file1, file2, file3 = map(File, ["file1", "file2", "file3"]) file3 += File("file1") file3 += File("file2") file4 = file2 + file1 + file2 for f in file1, file2, file3, file4: print f $ python roskam.py file1: alpha beta gamma file2: DELTA EPSILON file3: alpha beta gamma DELTA EPSILON file2+file1+file2: DELTA EPSILON alpha beta gamma DELTA EPSILON The code is meant to illustrate the implementation of __add__() and __iadd__(), I don't recommend that you actually use it. You can easily achieve the same with a for loop that is concise and easy to understand: with open(destname, "wb") as dest: for sourcename in sourcenames: with open(sourcename, "rb") as source: shutil.copyfileobj(source, dest) From alan.gauld at btinternet.com Tue Mar 6 09:48:25 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 06 Mar 2012 08:48:25 +0000 Subject: [Tutor] question about operator overloading In-Reply-To: <4F557999.4010309@davea.name> References: <1330978573.3874.YahooMailNeo@web110704.mail.gq1.yahoo.com> <4F5523D2.7070601@davea.name> <1330981826.96115.YahooMailNeo@web110712.mail.gq1.yahoo.com> <4F552F4D.4070805@davea.name> <4F557999.4010309@davea.name> Message-ID: On 06/03/12 02:42, Dave Angel wrote: >> My guess would be similar to the cat operator in Unix: >> >> file3 = file1 + file2 >> > > So somehow assigning the object to file3 will write the data to a file > by the name "file3" ? I know about __add__(), but didn't know we had > __assign__() We don't need any special assign behavior, its just standard Python assignment of the returned object to a name. class MyFile(file): .... def __add__(self, file2): newFile = MyFile('foo.dat','wb') newFile.write(self.read()) newFile.write(file2.read()) return newFile file3 = MyFile('spam.dat') + MyFile('baz.dat') -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From fedka2 at gmail.com Tue Mar 6 10:51:33 2012 From: fedka2 at gmail.com (Paul Douglas Grant) Date: Tue, 6 Mar 2012 10:51:33 +0100 Subject: [Tutor] IDLE problems Message-ID: Hello folks, I am new to programming and choosing python as my first language to learn, thus excuse the perhaps naivet? of this question and the way it is formulated. For the last few weeks I've been trying to solve an issue running python on mac snow leopard 10.6.8. I was running a version of python that was preinstalled on my computer. At some point in reading the python website I saw that version 3.2.2 was available and recommended. After downloading and installing it along with ActiveTcl 8.5.11. When I opened IDLE to run *hello world* nothing happened, just a hard return...I tried reinstalling an earlier version 2.7, same problem. Reinstalled 3.2.2, same issue. Not sure how to get python up and running. Any suggestions will be greatly appreciated. Thanks so much. p From alan.gauld at btinternet.com Tue Mar 6 11:47:24 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 06 Mar 2012 10:47:24 +0000 Subject: [Tutor] IDLE problems In-Reply-To: References: Message-ID: On 06/03/12 09:51, Paul Douglas Grant wrote: > issue running python on mac snow leopard 10.6.8. I was running a > version of python that was preinstalled on my computer. At some point > in reading the python website I saw that version 3.2.2 was available > and recommended. After downloading and installing it along with > ActiveTcl 8.5.11. When I opened IDLE to run *hello world* nothing > happened, just a hard return...I tried reinstalling an earlier version > 2.7, same problem. Reinstalled 3.2.2, same issue. Sorry, it's not really clear what you mean here. I'll try asking some questions to clarify things: Did you uninstall the version that came with MacOS? (If so that was probably a mistake!) What happens if you open a terminal and type 'python'? Do you get to the python >>> prompt? If so with which version? Did you have IDLE working in the original install? (My iBook didn't have IDLE support included, I had to add that myself, but I don't know about newer Macs) You probably didn't need ActiveTcl, the Mac ActivePython should have had all that you needed. OTOH it shouldn't do any harm either... Can you run wish in a terminal and get the Tcl/Tk prompt/window? How did you try to open IDLE? (Finder, Terminal, or shortcut?) What do you mean by a "hard return"? regards, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From fomcl at yahoo.com Tue Mar 6 13:05:06 2012 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Tue, 6 Mar 2012 04:05:06 -0800 (PST) Subject: [Tutor] question about operator overloading In-Reply-To: <4F556145.8050706@pearwood.info> References: <1330978573.3874.YahooMailNeo@web110704.mail.gq1.yahoo.com> <4F5523D2.7070601@davea.name> <1330981826.96115.YahooMailNeo@web110712.mail.gq1.yahoo.com> <4F552F4D.4070805@davea.name> <4F556145.8050706@pearwood.info> Message-ID: <1331035506.87845.YahooMailNeo@web110711.mail.gq1.yahoo.com> From: Steven D'Aprano To: tutor at python.org Sent: Tuesday, March 6, 2012 1:58 AM Subject: Re: [Tutor] question about operator overloading Alan Gauld wrote: >> On 05/03/12 21:25, Dave Angel wrote: >> >>> It's not clear what __add__() should mean for physical files. >> >> My guess would be similar to the cat operator in Unix: >> >> $ cat file1, file2 > file3 >> >> is equivalent to >> >> file3 = file1 + file2 >> >> But of course, thats just my interpretation of file addition... > >I think that's what Albert-Jan is probably thinking, but the two models are not quite the same. I think that what he wants is probably closer to something like the fileinput module. I think what he wants is to avoid this: >-----> First off, thank you all for your replies, including the replies after this mail. And sorry for top-posting in an earlier mail >-----> And yes indeed Steven and Alan,?this is what I had in mind. >for f in (file1, file2, file3, file4): >? ? for record in f: >? ? ? ? process(record) > >in favour of this: > >all_the_files = file1 + file2 + file3 + file4? # merge file contents >for record in all_the_files: >? ? process(record) > >Albert-Jan, am I close? If not, please explain what you are trying to accomplish. >----> What I had in mind was something like Peter Otten suggested: >merged?= file1 + file2 >merged.save_as(filename) >Your solution looks intuitive, but won't "all_the_files" become very large if file1 through file4 contain, say, 100 billion values each? > >If the files are small, the easy way is to just read their contents, add them together as strings or lists, and then process the lot. But if the files are big, or you want to process them on-demand instead of up-front, you need an approach similar to fileinput. >----> see above. Btw, contrary to what somebody in this thread said, Spss files are binary files, not text files. > >Personally, all these Reader and Append objects make my brain hurt, and I hardly ever use operator overloading, except perhaps for numeric types. Reader objects, I can just get. But "Append" objects? > >This may be useful: > >http://steve-yegge.blogspot.com.au/2006/03/execution-in-kingdom-of-nouns.html >----> Nice one ;-)) > >and also itertools: > > >from itertools import chain >merged = chain(file1, file2, file3, file4) >for record in merged: >? ? process(record) >----> Very, *very* useful function, thank you! >----> this is (incomplete) code that I created without bothering about __add__: >with SavWriter(mergedSavFileName, varNames, varTypes) as sav_merged: >? for savFileName in glob.glob("d:/temp/*.sav"): >??? with SavReader(savFileName) as sav_r: >????? header = sav_r.next() >????? for row in sav_r: >??????? sav_merged.writerow(row) >http://code.activestate.com/recipes/577811-python-reader-writer-for-spss-sav-files-linux-mac-/ >---> Maybe I am making my life too difficult by trying to use __add__? > >-- Steven >_______________________________________________ >Tutor maillist? -? Tutor at python.org >To unsubscribe or change subscription options: >http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Tue Mar 6 14:21:51 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 6 Mar 2012 08:21:51 -0500 Subject: [Tutor] question about operator overloading In-Reply-To: <1331035506.87845.YahooMailNeo@web110711.mail.gq1.yahoo.com> References: <1330978573.3874.YahooMailNeo@web110704.mail.gq1.yahoo.com> <4F5523D2.7070601@davea.name> <1330981826.96115.YahooMailNeo@web110712.mail.gq1.yahoo.com> <4F552F4D.4070805@davea.name> <4F556145.8050706@pearwood.info> <1331035506.87845.YahooMailNeo@web110711.mail.gq1.yahoo.com> Message-ID: On Tue, Mar 6, 2012 at 7:05 AM, Albert-Jan Roskam wrote: > From: Steven D'Aprano > To: tutor at python.org > Sent: Tuesday, March 6, 2012 1:58 AM > > Subject: Re: [Tutor] question about operator overloading > > Alan Gauld wrote: > >> On 05/03/12 21:25, Dave Angel wrote: >> >>> It's not clear what __add__() should mean for physical files. >> >> My guess would be similar to the cat operator in Unix: >> >> $ cat file1, file2 > file3 >> >> is equivalent to >> >> file3 = file1 + file2 >> >> But of course, thats just my interpretation of file addition... > > I think that's what Albert-Jan is probably thinking, but the two models are > not quite the same. I think that what he wants is probably closer to > something like the fileinput module. I think what he wants is to avoid this: > -----> First off, thank you all for your replies, including the replies > after this mail. And sorry for top-posting in an earlier mail > -----> And yes indeed Steven and Alan,?this is what I had in mind. > for f in (file1, file2, file3, file4): > ? ? for record in f: > ? ? ? ? process(record) > > in favour of this: > > all_the_files = file1 + file2 + file3 + file4? # merge file contents > for record in all_the_files: > ? ? process(record) > > Albert-Jan, am I close? If not, please explain what you are trying to > accomplish. > ----> What I had in mind was something like Peter Otten suggested: > merged?= file1 + file2 > merged.save_as(filename) > Your solution looks intuitive, but won't "all_the_files" become very large > if file1 through file4 contain, say, 100 billion values each? > > > If the files are small, the easy way is to just read their contents, add > them together as strings or lists, and then process the lot. But if the > files are big, or you want to process them on-demand instead of up-front, > you need an approach similar to fileinput. > ----> see above. Btw, contrary to what somebody in this thread said, Spss > files are binary files, not text files. I chimed in with an assumption that these are were text files. Since i wasn't right assuming that, and if I read the discussion correctly there are two methods being contemplated. One way is to read a file, process it, write the result to an output file, read the next file, process it and append to the output file. The second method is to concatinate all of the input files, then open it up and process it. But, if the spss files aren't text, then I assume they have some structure that might not be concatinatable. Not sure if that is a word. > > > Personally, all these Reader and Append objects make my brain hurt, and I > hardly ever use operator overloading, except perhaps for numeric types. > Reader objects, I can just get. But "Append" objects? > > This may be useful: > > http://steve-yegge.blogspot.com.au/2006/03/execution-in-kingdom-of-nouns.html > ----> Nice one ;-)) > > and also itertools: > > > from itertools import chain > merged = chain(file1, file2, file3, file4) > for record in merged: > ? ? process(record) > ----> Very, *very* useful function, thank you! > ----> this is (incomplete) code that I created without bothering about > __add__: > with SavWriter(mergedSavFileName, varNames, varTypes) as sav_merged: > ? for savFileName in glob.glob("d:/temp/*.sav"): > ??? with SavReader(savFileName) as sav_r: > ????? header = sav_r.next() > ????? for row in sav_r: > ??????? sav_merged.writerow(row) > http://code.activestate.com/recipes/577811-python-reader-writer-for-spss-sav-files-linux-mac-/ > ---> Maybe I am making my life too difficult by trying to use __add__? > > -- Steven > _______________________________________________ > Tutor maillist? -? Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick From suryak at live.com Tue Mar 6 18:18:32 2012 From: suryak at live.com (Surya K) Date: Tue, 6 Mar 2012 22:48:32 +0530 Subject: [Tutor] New project idea!! Message-ID: Hi, I am an electronics guy, extremely interested in programming. So learned Python. Currently I know (C, Python, HTML); Learning Java, Python (still making myself flexible in OOP). So, last year I build a sudoku solver in C which was an amazing experience (though re inventing wheel is not a big deal at all), I learned a lot. Now, I would like to do a similar project using python (which should be quite acceptable to put on my resume).. Any Ideas please!! (Note: I am no computer science guy, My day-to-day affairs deal with resistors, capacitors, transistors etc. I try to learn programming myself at home.. So, I wouldn't have knowledge exactly how a computer science guys will have. But I have more than enough enthusiasm.. -------------- next part -------------- An HTML attachment was scrubbed... URL: From suryak at live.com Tue Mar 6 18:35:16 2012 From: suryak at live.com (Surya K) Date: Tue, 6 Mar 2012 23:05:16 +0530 Subject: [Tutor] New project idea!! In-Reply-To: References: , Message-ID: Subject: Re: [Tutor] New project idea!! From: laszlo at antalconsulting.com Date: Tue, 6 Mar 2012 09:24:12 -0800 CC: tutor at python.org To: suryak at live.com Hi, Since you are an electronics guy, how about a circuit simulator?You can start very simple with a power source and a light and show how the current flows.Add resistors and other bodies later. You could use pygame for the drawing and animation.I have been thinking of a simple app like that lately but I am don't have any former background in electronics and the know how, but I think it would be a great teaching tool and fun project. lzantal Well, that's not bad but I wish it should be something interesting... Actually, I have an idea to develop a multiplayer game (where friends connect across internet.. ) The problem is that, I don't know network/ socket programming. which itself takes a lot of time to learn.. : ( -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Tue Mar 6 18:35:12 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 6 Mar 2012 17:35:12 +0000 Subject: [Tutor] New project idea!! In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF47418FB46@SCACMX008.exchad.jpmchase.net> >So, last year I build a Sudoku solver in C which was an amazing experience (though re inventing wheel is not a big deal at all), I learned a lot. >Now, I would like to do a similar project using python (which should be quite acceptable to put on my resume).. Any Ideas please!! >(Note: I am no computer science guy, My day-to-day affairs deal with resistors, capacitors, transistors etc. I try to learn programming myself at home.. So, I wouldn't have knowledge exactly how a computer science guys will have. But I have more than enough enthusiasm.. Why not simply create a Sudoku solver from scratch in Python. That way you will be familiar with the logical process and learn Python? Or just use it to do something you do on a computer you find tedious. My last Python script (at home) was simply to take a bunch of Facebook emails and merge the comments so I could go back and read the comments on a deleted post. A script before that was to help me download files, but it would save where it stopped so I could go back if I stopped prematurely or if new files were added to the list. Maybe you have something you could automate at work? Some kind of calculation or circuit planning? For non-CS people, usually games are the most interesting. So if you are bored with Sudoku, pick another game. Casino games e.g. poker / blackjack / slots are common beginner games and can be done without having to learn a GUI framework...you can just print cards/slot. Hope that helps, Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From abhishek.vit at gmail.com Tue Mar 6 18:50:55 2012 From: abhishek.vit at gmail.com (Abhishek Pratap) Date: Tue, 6 Mar 2012 09:50:55 -0800 Subject: [Tutor] creating dict of dict : similar to perl hash of hash Message-ID: Hi Guys I am looking for a way to build dictionaries of dict in python. For example in perl I could do my $hash_ref = {}; $hash->{$a}->{$b}->{$c} = "value"; if (exists $hash->{$a}->{$b}->{$c} ){ print "found value"} Can I do something similar with dictionaries in Python. Thanks -Abhi -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Mar 6 19:12:46 2012 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Tue, 6 Mar 2012 18:12:46 +0000 (GMT) Subject: [Tutor] IDLE problems In-Reply-To: References: Message-ID: <1331057566.48396.YahooMailNeo@web86704.mail.ird.yahoo.com> Please use ReplyAll to include the group. > formulation of the question. Ultimately the brute question is why > can't I get IDLE to work... > I did uninstall the version that came with mac. > In a terminal I get version 2.7.2(?) OK, That's good because I think that's the same as the default install on SnowLeopard which means the things that MacOS uses Python for will probably still work... > > IDLE was working with the original install. OK, That's good too. > I run IDLE simply by opening the IDLE icon in the Python folder. OK, so from Finder. In that case can you open a Terminal window and? drag the python folder into the Terminal - that should navigate you to? the same folder. Then try running IDLE by typing python ./idle.py At the terminal prompt. > I don't believe I have wish, at least not after a spotlight search. Odd given you installed Tcl/Tk, but not a problem. >As for hard return, the cursor moves to the next line but not response >to the *hello world* string. OK, is this in the IDLE shell? In other words are you actually getting IDLE to open with a Python? prompt >> showing? If not where are you typing the command,? and what *exactly* are you typing. If you can cut 'n paste into a mail so much the better! Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From david at graniteweb.com Tue Mar 6 19:19:10 2012 From: david at graniteweb.com (David Rock) Date: Tue, 6 Mar 2012 12:19:10 -0600 Subject: [Tutor] creating dict of dict : similar to perl hash of hash In-Reply-To: References: Message-ID: <20120306181910.GC12835@wdfs.graniteweb.com> * Abhishek Pratap [2012-03-06 09:50]: > Hi Guys > > I am looking for a way to build dictionaries of dict in python. > > For example in perl I could do > > my $hash_ref = {}; > $hash->{$a}->{$b}->{$c} = "value"; > if (exists $hash->{$a}->{$b}->{$c} ){ print "found value"} > > Can I do something similar with dictionaries in Python. Absolutely. Python is very good at using nested dicts. dict = {} dict['a'] ={} dict['a']['b'] = {} dict['a']['b']['c']= "value" This is a bit brute force, but it illustrates that the intermediary keys need to exist. ie, if you try to assign directly, it won't work: Type "help", "copyright", "credits" or "license" for more information. >>> dict ={} >>> dict['a']['b']['c'] = 'value' Traceback (most recent call last): File "", line 1, in KeyError: 'a' Since the key 'a' doesn't exist, it throws an exception. Python is also more flexible than perl in nesting data because it doesn't have to be the same data type. You can nest variables, lists, dicts, etc all at the same level: dict = {} dict['mylist'] = [1,2,3] dict['mystring'] = 'string' dict['mynum'] = 4 dict['anotherdict'] = {} dict['anotherdict']['anotherstring'] = 'string2' -- David Rock david at graniteweb.com -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 190 bytes Desc: not available URL: From joel.goldstick at gmail.com Tue Mar 6 19:19:51 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 6 Mar 2012 13:19:51 -0500 Subject: [Tutor] creating dict of dict : similar to perl hash of hash In-Reply-To: References: Message-ID: On Tue, Mar 6, 2012 at 12:50 PM, Abhishek Pratap wrote: > Hi Guys > > I am looking for a way to build dictionaries of dict in python. > > For example in perl I could do > > my $hash_ref = {}; > $hash->{$a}->{$b}->{$c} = "value"; > if (exists?$hash->{$a}->{$b}->{$c} ){?print "found value"} > > Can I do something similar with dictionaries in Python. > > > Thanks > -Abhi > > Dictionaries can contain dictionaries in python: >>> sub_d = {'key1':'value1'} >>> d = {'subd1':sub_d} >>> d {'subd1': {'key1': 'value1'}} >>> d['subd1'] {'key1': 'value1'} >>> The Python site has information here: http://docs.python.org/tutorial/datastructures.html#dictionaries > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick From alan.gauld at btinternet.com Tue Mar 6 19:25:27 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 06 Mar 2012 18:25:27 +0000 Subject: [Tutor] creating dict of dict : similar to perl hash of hash In-Reply-To: References: Message-ID: On 06/03/12 17:50, Abhishek Pratap wrote: > I am looking for a way to build dictionaries of dict in python. Thats not a problem, you just nest them: d1 = {key: value,...} # a single level dictionary d2 = {key: d1, ...} # a dictionary of dictionaries... d3 = { key1: {key2: value, ...}, ...} # and on one line > For example in perl I could do > > my $hash_ref = {}; > $hash->{$a}->{$b}->{$c} = "value"; > if (exists $hash->{$a}->{$b}->{$c} ){ print "found value"} > > Can I do something similar with dictionaries in Python. No idea, I haven't done any Perl for over 10 years. What does that actually do? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From martin at linux-ip.net Tue Mar 6 19:18:43 2012 From: martin at linux-ip.net (Martin A. Brown) Date: Tue, 6 Mar 2012 13:18:43 -0500 Subject: [Tutor] creating dict of dict : similar to perl hash of hash In-Reply-To: References: Message-ID: Hello there Abhi, : I am looking for a way to build dictionaries of dict in python. : : For example in perl I could do : : my $hash_ref = {}; : $hash->{$a}->{$b}->{$c} = "value"; : if (exists $hash->{$a}->{$b}->{$c} ){ print "found value"} Autovivifying. That's what the perl-heads call that. : Can I do something similar with dictionaries in Python. I suspect you want to look into the collections module. Here's an example of how to use it to create a two-level dictionary with the same autovivifying behaviour you are accustomed to in perl. >>> import collections >>> d = collections.defaultdict(collections.defaultdict) >>> a,b,c = range(3) >>> d[a][b] = c >>> d defaultdict(, {0: defaultdict(None, {1: 2})}) Have a look at the collections module. See if that scratches your itch. Good luck, -Martin -- Martin A. Brown http://linux-ip.net/ From ps_python at yahoo.com Tue Mar 6 21:07:59 2012 From: ps_python at yahoo.com (kumar s) Date: Tue, 6 Mar 2012 12:07:59 -0800 (PST) Subject: [Tutor] count numbers only in the string Message-ID: <1331064479.53512.YahooMailNeo@web112501.mail.gq1.yahoo.com> Hi : I have some strings with both alpha-numeric strings. I want to add all the numbers in that string and leave characters and special characters.? 1A0G19 5G0C25^C52 0G2T3T91 44^C70 How can I count only the numbers in the above.? 1 A 0 G 19 ? ? ? = ? ?1+0+19 = 20 5 G 0 C 25 ^C 52 ?= ? 5+0+25+52 = 82 0 G 2 T 3 T 91 ? ?= ?0+2+3+91 = ?96 44 ^C 70 ? = ? 44+70 = ?114 ?In first string 1A0G19 ?I am only adding 1, 0, and 19. ? ?I am not splitting 19 to add 1+9 which will give totally wrong answer for me. Is there a way I can do this.? Thanks for your advise.? kumar From ramit.prasad at jpmorgan.com Tue Mar 6 21:42:43 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 6 Mar 2012 20:42:43 +0000 Subject: [Tutor] count numbers only in the string In-Reply-To: <1331064479.53512.YahooMailNeo@web112501.mail.gq1.yahoo.com> References: <1331064479.53512.YahooMailNeo@web112501.mail.gq1.yahoo.com> Message-ID: <5B80DD153D7D744689F57F4FB69AF47419226F@SCACMX008.exchad.jpmchase.net> > -----Original Message----- > From: tutor-bounces+ramit.prasad=jpmorgan.com at python.org [mailto:tutor- > bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of kumar s > Sent: Tuesday, March 06, 2012 2:08 PM > To: tutor at python.org > Subject: [Tutor] count numbers only in the string > > Hi : > > I have some strings with both alpha-numeric strings. I want to add all the > numbers in that string and leave characters and special characters. > 1A0G19 > > 5G0C25^C52 > > 0G2T3T91 > 44^C70 > > How can I count only the numbers in the above. > > 1 A 0 G 19 ? ? ? = ? ?1+0+19 = 20 > > 5 G 0 C 25 ^C 52 ?= ? 5+0+25+52 = 82 > > 0 G 2 T 3 T 91 ? ?= ?0+2+3+91 = ?96 > 44 ^C 70 ? = ? 44+70 = ?114 > > ?In first string 1A0G19 ?I am only adding 1, 0, and 19. ? ?I am not > splitting 19 to add 1+9 which will give totally wrong answer for me. > > > Is there a way I can do this. > > Thanks for your advise. > > kumar > There might be a better way, but you can use regular expressions. >>> match = re.search( '(\d+)A(\d+)G(\d+)', '1A0G19' ) >>> map(int, match.groups() ) [1, 0, 19] >>> sum( _ ) 20 Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From joel.goldstick at gmail.com Tue Mar 6 21:49:14 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 6 Mar 2012 15:49:14 -0500 Subject: [Tutor] count numbers only in the string In-Reply-To: <1331064479.53512.YahooMailNeo@web112501.mail.gq1.yahoo.com> References: <1331064479.53512.YahooMailNeo@web112501.mail.gq1.yahoo.com> Message-ID: On Tue, Mar 6, 2012 at 3:07 PM, kumar s wrote: > Hi : > > I have some strings with both alpha-numeric strings. I want to add all the numbers in that string and leave characters and special characters. > 1A0G19 > > 5G0C25^C52 > > 0G2T3T91 > 44^C70 > > How can I count only the numbers in the above. > > 1 A 0 G 19 ? ? ? = ? ?1+0+19 = 20 > > 5 G 0 C 25 ^C 52 ?= ? 5+0+25+52 = 82 > > 0 G 2 T 3 T 91 ? ?= ?0+2+3+91 = ?96 > 44 ^C 70 ? = ? 44+70 = ?114 > > ?In first string 1A0G19 ?I am only adding 1, 0, and 19. ? ?I am not splitting 19 to add 1+9 which will give totally wrong answer for me. > > > Is there a way I can do this. > > Thanks for your advise. > > kumar > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor I am pretty much a novice with regular expressions, but this seems to work to find all the numeric sequences: >>> source = 'ab123t&4533www' >>> re.findall('\d*', source) ['', '', '123', '', '', '4533', '', '', '', ''] >>> so then something like this: total = 0 my_list = re.findall('\d*', source) for my_number in my_list: if my_number != '' total += int(my_number) -- Joel Goldstick From joel.goldstick at gmail.com Tue Mar 6 21:58:51 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 6 Mar 2012 15:58:51 -0500 Subject: [Tutor] count numbers only in the string In-Reply-To: References: <1331064479.53512.YahooMailNeo@web112501.mail.gq1.yahoo.com> Message-ID: On Tue, Mar 6, 2012 at 3:49 PM, Joel Goldstick wrote: > On Tue, Mar 6, 2012 at 3:07 PM, kumar s wrote: >> Hi : >> >> I have some strings with both alpha-numeric strings. I want to add all the numbers in that string and leave characters and special characters. >> 1A0G19 >> >> 5G0C25^C52 >> >> 0G2T3T91 >> 44^C70 >> >> How can I count only the numbers in the above. >> >> 1 A 0 G 19 ? ? ? = ? ?1+0+19 = 20 >> >> 5 G 0 C 25 ^C 52 ?= ? 5+0+25+52 = 82 >> >> 0 G 2 T 3 T 91 ? ?= ?0+2+3+91 = ?96 >> 44 ^C 70 ? = ? 44+70 = ?114 >> >> ?In first string 1A0G19 ?I am only adding 1, 0, and 19. ? ?I am not splitting 19 to add 1+9 which will give totally wrong answer for me. >> >> >> Is there a way I can do this. >> >> Thanks for your advise. >> >> kumar >> >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > I am pretty much a novice with regular expressions, but this seems to > work to find all the numeric sequences: > >>>> source = 'ab123t&4533www' >>>> re.findall('\d*', source) > ['', '', '123', '', '', '4533', '', '', '', ''] >>>> > so then something like this: > > total = 0 > my_list = re.findall('\d*', source) > for my_number in my_list: > ? ?if my_number != '' > ? ? ? ?total += int(my_number) > > > > -- > Joel Goldstick Here is a shorter way: >>> source = 'ab123t&4533www' >>> my_list = re.findall('\d*', source) >>> my_list ['', '', '123', '', '', '4533', '', '', '', ''] >>> sum(int(s) for s in my_list if s != '') 4656 -- Joel Goldstick From joel.goldstick at gmail.com Tue Mar 6 22:12:44 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 6 Mar 2012 16:12:44 -0500 Subject: [Tutor] count numbers only in the string In-Reply-To: References: <1331064479.53512.YahooMailNeo@web112501.mail.gq1.yahoo.com> Message-ID: On Tue, Mar 6, 2012 at 3:58 PM, Joel Goldstick wrote: > On Tue, Mar 6, 2012 at 3:49 PM, Joel Goldstick wrote: >> On Tue, Mar 6, 2012 at 3:07 PM, kumar s wrote: >>> Hi : >>> >>> I have some strings with both alpha-numeric strings. I want to add all the numbers in that string and leave characters and special characters. >>> 1A0G19 >>> >>> 5G0C25^C52 >>> >>> 0G2T3T91 >>> 44^C70 >>> >>> How can I count only the numbers in the above. >>> >>> 1 A 0 G 19 ? ? ? = ? ?1+0+19 = 20 >>> >>> 5 G 0 C 25 ^C 52 ?= ? 5+0+25+52 = 82 >>> >>> 0 G 2 T 3 T 91 ? ?= ?0+2+3+91 = ?96 >>> 44 ^C 70 ? = ? 44+70 = ?114 >>> >>> ?In first string 1A0G19 ?I am only adding 1, 0, and 19. ? ?I am not splitting 19 to add 1+9 which will give totally wrong answer for me. >>> >>> >>> Is there a way I can do this. >>> >>> Thanks for your advise. >>> >>> kumar >>> >>> _______________________________________________ >>> Tutor maillist ?- ?Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >> >> I am pretty much a novice with regular expressions, but this seems to >> work to find all the numeric sequences: >> >>>>> source = 'ab123t&4533www' >>>>> re.findall('\d*', source) >> ['', '', '123', '', '', '4533', '', '', '', ''] >>>>> >> so then something like this: >> >> total = 0 >> my_list = re.findall('\d*', source) >> for my_number in my_list: >> ? ?if my_number != '' >> ? ? ? ?total += int(my_number) >> >> >> >> -- >> Joel Goldstick > > Here is a shorter way: > >>>> source = 'ab123t&4533www' >>>> my_list = re.findall('\d*', source) if you change above to '\d+' it will only pick up the numbers so below you can do >>>> sum(int(s) for s in my_list) which is even simpler. >>>> my_list > ['', '', '123', '', '', '4533', '', '', '', ''] >>>> sum(int(s) for s in my_list if s != '') > 4656 > Sorry for my messing up the regex in the first try > > -- > Joel Goldstick -- Joel Goldstick From hayzer at gmail.com Tue Mar 6 23:38:11 2012 From: hayzer at gmail.com (Thomas Maier) Date: Wed, 7 Mar 2012 00:38:11 +0200 Subject: [Tutor] creating dict of dict : similar to perl hash of hash In-Reply-To: <20120306181910.GC12835@wdfs.graniteweb.com> References: <20120306181910.GC12835@wdfs.graniteweb.com> Message-ID: On Tue, Mar 6, 2012 at 8:19 PM, David Rock wrote: > * Abhishek Pratap [2012-03-06 09:50]: >> Hi Guys >> >> I am looking for a way to build dictionaries of dict in python. >> >> For example in perl I could do >> >> my $hash_ref = {}; >> $hash->{$a}->{$b}->{$c} = "value"; >> if (exists $hash->{$a}->{$b}->{$c} ){ print "found value"} >> >> Can I do something similar with dictionaries in Python. > > Absolutely. ?Python is very good at using nested dicts. > > dict = {} > dict['a'] ={} > dict['a']['b'] = {} > dict['a']['b']['c']= "value" > > > This is a bit brute force, but it illustrates that the intermediary keys > need to exist. ?ie, if you try to assign directly, it won't work: > > Type "help", "copyright", "credits" or "license" for more information. >>>> dict ={} >>>> dict['a']['b']['c'] = 'value' > Traceback (most recent call last): > ?File "", line 1, in > ?KeyError: 'a' > > Since the key 'a' doesn't exist, it throws an exception. > > Python is also more flexible than perl in nesting data because it > doesn't have to be the same data type. ?You can nest variables, lists, > dicts, etc all at the same level: > > dict = {} > dict['mylist'] = [1,2,3] > dict['mystring'] = 'string' > dict['mynum'] = 4 > dict['anotherdict'] = {} > dict['anotherdict']['anotherstring'] = 'string2' > Hi David, Mixed data types in nested data structure are possible in Perl as well: %hash = (); $hash{'mylist'} = [1,2,3]; $hash{'mystring'} = 'string'; $hash{'mynum'} = 4; $hash{'anotherhash'} = {}; $hash{'anotherhash'}{'anotherstring'} = 'string2'; Thomas From alan.gauld at btinternet.com Wed Mar 7 00:21:09 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 06 Mar 2012 23:21:09 +0000 Subject: [Tutor] creating dict of dict : similar to perl hash of hash In-Reply-To: References: Message-ID: On 06/03/12 18:18, Martin A. Brown wrote: > : $hash->{$a}->{$b}->{$c} = "value"; > : if (exists $hash->{$a}->{$b}->{$c} ){ print "found value"} > > Autovivifying. That's what the perl-heads call that. Aha!, that brought it back, now I know what it does... > >>> import collections > >>> d = collections.defaultdict(collections.defaultdict) > >>> a,b,c = range(3) > >>> d[a][b] = c > >>> d > defaultdict(, {0: defaultdict(None, {1: 2})}) Unfortunately this fails at 3 levels as per the OP example. The second level dict supplies a default value of None. If you know the max number of depths you can do something like this: >>> from collections import defaultdict as dd >>> d3 = dd(lambda : dd( lambda : dd() ) ) >>> d3['a']['b']['c'] = 'value' >>> d3 defaultdict( at 0x7f3aefa4e758>, {'a': defaultdict( at 0x7f3aefa4e6e0>, {'b': defaultdict(None, {'c': 'value'})})}) >>> But it doesn't have the same dynamic depth that the Perl version has, you need to know your maximum depth. The last level will always have the default set to None. You could create a class subclassed from defaultdict that would do it though... Unless of course somebody else can think of a more elegant solution. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Mar 7 00:25:08 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 06 Mar 2012 23:25:08 +0000 Subject: [Tutor] IDLE problems In-Reply-To: <1331057566.48396.YahooMailNeo@web86704.mail.ird.yahoo.com> References: <1331057566.48396.YahooMailNeo@web86704.mail.ird.yahoo.com> Message-ID: On 06/03/12 18:12, ALAN GAULD wrote: > OK, so from Finder. In that case can you open a Terminal window and > drag the python folder into the Terminal - that should navigate you to > the same folder. Then try running IDLE by typing > > python ./idle.py > > At the terminal prompt. I meant to say that this will let you see any error messages from running IDLE. If you get any, post them here. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From david at graniteweb.com Wed Mar 7 02:02:04 2012 From: david at graniteweb.com (David Rock) Date: Tue, 6 Mar 2012 19:02:04 -0600 Subject: [Tutor] creating dict of dict : similar to perl hash of hash In-Reply-To: References: <20120306181910.GC12835@wdfs.graniteweb.com> Message-ID: <20120307010204.GF12835@wdfs.graniteweb.com> * Thomas Maier [2012-03-07 00:38]: > Hi David, > Mixed data types in nested data structure are possible in Perl as well: > %hash = (); > $hash{'mylist'} = [1,2,3]; > $hash{'mystring'} = 'string'; > $hash{'mynum'} = 4; > $hash{'anotherhash'} = {}; > $hash{'anotherhash'}{'anotherstring'} = 'string2'; > > Thomas Hah. Fair enough :-) -- David Rock david at graniteweb.com -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 190 bytes Desc: not available URL: From abhishek.vit at gmail.com Wed Mar 7 02:26:26 2012 From: abhishek.vit at gmail.com (Abhishek Pratap) Date: Tue, 6 Mar 2012 17:26:26 -0800 Subject: [Tutor] inserting new lines in long strings while printing Message-ID: I have this one big string in python which I want to print to a file inserting a new line after each 100 characters. Is there a slick way to do this without looping over the string. I am pretty sure there shud be something its just I am new to the lang. Thanks! -Abhi -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Wed Mar 7 02:36:40 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 07 Mar 2012 01:36:40 +0000 Subject: [Tutor] inserting new lines in long strings while printing In-Reply-To: References: Message-ID: On 07/03/2012 01:26, Abhishek Pratap wrote: > I have this one big string in python which I want to print to a file > inserting a new line after each 100 characters. Is there a slick way to do > this without looping over the string. I am pretty sure there shud be > something its just I am new to the lang. > > > Thanks! > -Abhi > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Simplest way I can think of (untested). onebigstring = 'nbgkasgf;sh;slfgh;asdgh;adsdhg fg...' for i in range(0, len(onebigstring), 100): # for Python3, xrange for Python 2 print onebigstring[i:i+100] -- Cheers. Mark Lawrence. From steve at pearwood.info Wed Mar 7 02:41:35 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 7 Mar 2012 12:41:35 +1100 Subject: [Tutor] inserting new lines in long strings while printing In-Reply-To: References: Message-ID: <20120307014135.GB19312@ando> On Tue, Mar 06, 2012 at 05:26:26PM -0800, Abhishek Pratap wrote: > I have this one big string in python which I want to print to a file > inserting a new line after each 100 characters. Is there a slick way to do > this without looping over the string. I am pretty sure there shud be > something its just I am new to the lang. >>> s = "a"*100 >>> print '\n'.join(s[i:i+10] for i in range(0, len(s), 10)) aaaaaaaaaa aaaaaaaaaa aaaaaaaaaa aaaaaaaaaa aaaaaaaaaa aaaaaaaaaa aaaaaaaaaa aaaaaaaaaa aaaaaaaaaa aaaaaaaaaa -- Steven From abhishek.vit at gmail.com Wed Mar 7 02:56:06 2012 From: abhishek.vit at gmail.com (Abhishek Pratap) Date: Tue, 6 Mar 2012 17:56:06 -0800 Subject: [Tutor] inserting new lines in long strings while printing In-Reply-To: <20120307014135.GB19312@ando> References: <20120307014135.GB19312@ando> Message-ID: thanks guys .. -Abhi On Tue, Mar 6, 2012 at 5:41 PM, Steven D'Aprano wrote: > On Tue, Mar 06, 2012 at 05:26:26PM -0800, Abhishek Pratap wrote: > > I have this one big string in python which I want to print to a file > > inserting a new line after each 100 characters. Is there a slick way to > do > > this without looping over the string. I am pretty sure there shud be > > something its just I am new to the lang. > > >>> s = "a"*100 > >>> print '\n'.join(s[i:i+10] for i in range(0, len(s), 10)) > aaaaaaaaaa > aaaaaaaaaa > aaaaaaaaaa > aaaaaaaaaa > aaaaaaaaaa > aaaaaaaaaa > aaaaaaaaaa > aaaaaaaaaa > aaaaaaaaaa > aaaaaaaaaa > > > -- > Steven > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ajarncolin at gmail.com Wed Mar 7 04:24:22 2012 From: ajarncolin at gmail.com (col speed) Date: Wed, 7 Mar 2012 10:24:22 +0700 Subject: [Tutor] misunderstanding "any" Message-ID: Hello again Hope you are all well. I'm trying to make a "match 3" game, where you have a square grid and have to put 3 matching shapes in a row. I need a function that tells me if the game is playable, ie. it is possible to match 3 shapes by only swapping 2 adjacent shapes. I have looked at the co-ordinates and got a list of the "offset co-ordinates" needed for the above. I have a list of coordinates and a list of "lemons" and I want to see if *any* lemon coordinate is in the list of coordinates. I tried this: if any(((x+1, y+1), (x-1, y+2),(x-2, y+1),(x-1, y-1 ))) in fruit_type: return True Thinking that if *any* of the tuples is in fruit_type(a list of tuples), then it should return True. However, it always equates to False. If I iterate through the tuples and see if any are in fruit_type, it returns True (when it should). I have tried many print statements to make sure what is happening, and also to make sure that I am comparing type. I just wondered what it is that I'm misunderstanding, or what I've done wrong. Here is the whole programme for completeness: #!usr/bin/env python import random class Gem(object): def __init__(self, x, y, fruit): self.x = x self.y = y self.fruit = fruit gems = [] x, y = 0, 0 fruits = ["lemon", "banana", "apple", "pineapple", "mango"] for gem in range(81): gems.append(Gem(x, y, random.choice(fruits))) x += 1 if x >= 9: x = 0 y += 1 def game_on(fruits): for fruit in fruits: fruit_type = [(gem.x, gem.y) for gem in gems if gem.fruit == fruit] for x, y in fruit_type: if (x-1, y+1) in fruit_type: if any(((x+1, y+1), (x-1, y+2),(x-2, y+1),(x-1, y-1 ))) in fruit_type: return True elif (x-1, y-1) in fruit_type: if any(((x+1, y-1), (x-2, y-1),(x-1, y+1),(x-1, y-2))) in fruit_type: return True elif (x+1, y+1) in fruit_type: if any(((x+2, y+1), (x+1, y-1),(x+1, y+2),(x-1, y+1))) in fruit_type: return True elif (x+1, y-1) in fruit_type: if any(((x+1, y+1), (x+1, y-2),(x+2, y-1),(x-1, y-1))) in fruit_type: return True elif (x-2, y+1) in fruit_type: if (x-1, y+1) in fruit_type: return True elif (x-2, y-1) in fruit_type: if (x-1, y-1) in fruit_type: return True elif (x-1, y-2) in fruit_type: if (x-1, y-1) in fruit_type: return True elif (x+1, y-2) in fruit_type: if (x+1, y-1) in fruit_type: return True return False print game_on(fruits) And here;s a typical printout: mango [(3, 0), (0, 1), (3, 1), (5, 1), (6, 1), (8, 1), (1, 2), (2, 2), (5, 2), (1, 4), (4, 4), (6, 4), (2, 5), (4, 5), (5, 5), (2, 6), (3, 6), (3, 8)] # fruit_type and type(fruit_type[2]) got (3, 1), and (2, 2) (4, 2), (2, 3), (1, 2), (2, 0).If any of these are in fruit type, we have a match (1, 2) It's in.# this is from iterating over the tuples and making sure they are type tuple. We have a match. ##many more matches found### False # the return from the function Thanks a lot Col From breamoreboy at yahoo.co.uk Wed Mar 7 04:45:36 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 07 Mar 2012 03:45:36 +0000 Subject: [Tutor] misunderstanding "any" In-Reply-To: References: Message-ID: On 07/03/2012 03:24, col speed wrote: > Hello again > Hope you are all well. > > I'm trying to make a "match 3" game, where you have a square grid and > have to put 3 matching shapes in a row. > I need a function that tells me if the game is playable, ie. it is > possible to match 3 shapes by only swapping 2 adjacent shapes. > I have looked at the co-ordinates and got a list of the "offset > co-ordinates" needed for the above. > > I have a list of coordinates and a list of "lemons" and I want to see > if *any* lemon coordinate is in the list of coordinates. > I tried this: > if any(((x+1, y+1), (x-1, y+2),(x-2, y+1),(x-1, y-1 ))) in fruit_type: > return True > > Thinking that if *any* of the tuples is in fruit_type(a list of > tuples), then it should return True. > However, it always equates to False. > If I iterate through the tuples and see if any are in fruit_type, it > returns True (when it should). > I have tried many print statements to make sure what is happening, and > also to make sure that I am comparing type. Here's the way to find out. >>> help(any) Help on built-in function any in module __builtin__: any(...) any(iterable) -> bool Return True if bool(x) is True for any x in the iterable. >>> help('in') Comparisons *********** [snipped] The operators ``in`` and ``not in`` test for collection membership. ``x in s`` evaluates to true if *x* is a member of the collection *s*, and false otherwise. ``x not in s`` returns the negation of ``x in s``. The collection membership test has traditionally been bound to sequences; an object is a member of a collection if the collection is a sequence and contains an element equal to that object. However, it make sense for many other object types to support membership tests without being a sequence. In particular, dictionaries (for keys) and sets support membership testing. For the list and tuple types, ``x in y`` is true if and only if there exists an index *i* such that ``x == y[i]`` is true. For the Unicode and string types, ``x in y`` is true if and only if *x* is a substring of *y*. An equivalent test is ``y.find(x) != -1``. Note, *x* and *y* need not be the same type; consequently, ``u'ab' in 'abc'`` will return ``True``. Empty strings are always considered to be a substring of any other string, so ``"" in "abc"`` will return ``True``. Changed in version 2.3: Previously, *x* was required to be a string of length ``1``. For user-defined classes which define the ``__contains__()`` method, ``x in y`` is true if and only if ``y.__contains__(x)`` is true. For user-defined classes which do not define ``__contains__()`` but do define ``__iter__()``, ``x in y`` is true if some value ``z`` with ``x == z`` is produced while iterating over ``y``. If an exception is raised during the iteration, it is as if ``in`` raised that exception. Lastly, the old-style iteration protocol is tried: if a class defines ``__getitem__()``, ``x in y`` is true if and only if there is a non- negative integer index *i* such that ``x == y[i]``, and all lower integer indices do not raise ``IndexError`` exception. (If any other exception is raised, it is as if ``in`` raised that exception). The operator ``not in`` is defined to have the inverse true value of ``in``. [snipped] -- Cheers. Mark Lawrence. From malaclypse2 at gmail.com Wed Mar 7 05:01:12 2012 From: malaclypse2 at gmail.com (Jerry Hill) Date: Tue, 6 Mar 2012 23:01:12 -0500 Subject: [Tutor] creating dict of dict : similar to perl hash of hash In-Reply-To: References: Message-ID: On Tue, Mar 6, 2012 at 6:21 PM, Alan Gauld wrote: > But it doesn't have the same dynamic depth that the Perl version has, you > need to know your maximum depth. The last level will always have the default > set to None. > > You could create a class subclassed from defaultdict that would do it > though... It's a pretty easy class to write: from collections import defaultdict class recursivedefaultdict(defaultdict): def __init__(self): self.default_factory = type(self) Given that bit of code, the OP's example looks a bit like this: a = 1 b = 2 c = 'apples' my_hash = recursivedefaultdict() my_hash[a][b][c] = "value" if my_hash[a][b][c]: print("found value") -- Jerry From ajarncolin at gmail.com Wed Mar 7 05:36:49 2012 From: ajarncolin at gmail.com (col speed) Date: Wed, 7 Mar 2012 11:36:49 +0700 Subject: [Tutor] misunderstanding "any" In-Reply-To: References: Message-ID: On 7 March 2012 10:45, Mark Lawrence wrote: > On 07/03/2012 03:24, col speed wrote: >> >> Hello again >> Hope you are all well. >> >> I'm trying to make a "match 3" game, where you have a square grid and >> have to put 3 matching shapes in a row. >> I need a function that tells me if the game is playable, ie. it is >> possible to match 3 shapes by only swapping 2 adjacent shapes. >> I have looked at the co-ordinates and got a list of the "offset >> co-ordinates" needed for the above. >> >> I have a list of coordinates and a list of "lemons" and I want to see >> if *any* lemon coordinate is in the list of coordinates. >> I tried this: >> if any(((x+1, y+1), (x-1, y+2),(x-2, y+1),(x-1, y-1 ))) in fruit_type: >> ? ? ? ? ? ? ? ? ? ? return True >> >> Thinking that if ?*any* of the tuples is in fruit_type(a list of >> tuples), then it should return True. >> However, it always equates to False. >> > > > Here's the way to find out. > >>>> help(any) > Help on built-in function any in module __builtin__: > > any(...) > ? ?any(iterable) -> bool > > ? ?Return True if bool(x) is True for any x in the iterable. > >>>> help('in') > Comparisons > *********** > > [snipped] > > > > For the list and tuple types, ``x in y`` is true if and only if there > exists an index *i* such that ``x == y[i]`` is true. > > > [snipped] > > -- > Cheers. > > Mark Lawrence. > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Thanks Mark I looked up help(any), but not help(in)! I *think* I understand: Where it says: "For the list and tuple types, ``x in y`` is true if and only if there > exists an index *i* such that ``x == y[i]`` is true." I suppose I am looking for .....an index *i* and *j* such that x[j] == y[i]. Is that right? cheers Col From breamoreboy at yahoo.co.uk Wed Mar 7 05:50:53 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 07 Mar 2012 04:50:53 +0000 Subject: [Tutor] misunderstanding "any" In-Reply-To: References: Message-ID: On 07/03/2012 04:36, col speed wrote: > On 7 March 2012 10:45, Mark Lawrence wrote: >> On 07/03/2012 03:24, col speed wrote: >>> >>> Hello again >>> Hope you are all well. >>> >>> I'm trying to make a "match 3" game, where you have a square grid and >>> have to put 3 matching shapes in a row. >>> I need a function that tells me if the game is playable, ie. it is >>> possible to match 3 shapes by only swapping 2 adjacent shapes. >>> I have looked at the co-ordinates and got a list of the "offset >>> co-ordinates" needed for the above. >>> >>> I have a list of coordinates and a list of "lemons" and I want to see >>> if *any* lemon coordinate is in the list of coordinates. >>> I tried this: >>> if any(((x+1, y+1), (x-1, y+2),(x-2, y+1),(x-1, y-1 ))) in fruit_type: >>> return True >>> >>> Thinking that if *any* of the tuples is in fruit_type(a list of >>> tuples), then it should return True. >>> However, it always equates to False. >>> >> >> >> Here's the way to find out. >> >>>>> help(any) >> Help on built-in function any in module __builtin__: >> >> any(...) >> any(iterable) -> bool >> >> Return True if bool(x) is True for any x in the iterable. >> >>>>> help('in') >> Comparisons >> *********** >> >> [snipped] >> >> >> >> For the list and tuple types, ``x in y`` is true if and only if there >> exists an index *i* such that ``x == y[i]`` is true. >> >> >> [snipped] >> >> -- >> Cheers. >> >> Mark Lawrence. >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > Thanks Mark > I looked up help(any), but not help(in)! Note as it's a keyword it has to be in quotes, help('in'). > > I *think* I understand: > Where it says: > "For the list and tuple types, ``x in y`` is true if and only if there >> exists an index *i* such that ``x == y[i]`` is true." > > I suppose I am looking for .....an index *i* and *j* such that x[j] == y[i]. > > Is that right? I reckon so although I don't believe that the interactive prompt lies. >>> a=tuple(range(10)) >>> b=tuple(reversed(a)) >>> a,b ((0, 1, 2, 3, 4, 5, 6, 7, 8, 9), (9, 8, 7, 6, 5, 4, 3, 2, 1, 0)) >>> a[3] == b[3] False >>> a[5] == b[4] True > cheers > Col > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > HTH. -- Cheers. Mark Lawrence. From ajarncolin at gmail.com Wed Mar 7 06:07:39 2012 From: ajarncolin at gmail.com (col speed) Date: Wed, 7 Mar 2012 12:07:39 +0700 Subject: [Tutor] misunderstanding "any" In-Reply-To: References: Message-ID: On 7 March 2012 11:50, Mark Lawrence wrote: > On 07/03/2012 04:36, col speed wrote: >> >> On 7 March 2012 10:45, Mark Lawrence ?wrote: >>> >>> On 07/03/2012 03:24, col speed wrote: > >> I *think* I understand: >> Where it says: >> "For the list and tuple types, ``x in y`` is true if and only if there >>> >>> exists an index *i* such that ``x == y[i]`` is true." >> >> >> I suppose I am looking for .....an index *i* and *j* such that x[j] == >> y[i]. >> >> Is that right? > > > I reckon so although I don't believe that the interactive prompt lies. > >>>> a=tuple(range(10)) >>>> b=tuple(reversed(a)) >>>> a,b > ((0, 1, 2, 3, 4, 5, 6, 7, 8, 9), (9, 8, 7, 6, 5, 4, 3, 2, 1, 0)) >>>> a[3] == b[3] > False >>>> a[5] == b[4] > True > >> cheers >> Col >> >> Then we have: >>> a = tuple(range(10)) >>> b = tuple(reversed(a)) >>> any(a) in b True >>> any(b) in a True >>> any((a,b)) in (a,b) False # I think I understand this now, but I must admit it looks confusing! Thanks again Col From __peter__ at web.de Wed Mar 7 09:58:10 2012 From: __peter__ at web.de (Peter Otten) Date: Wed, 07 Mar 2012 09:58:10 +0100 Subject: [Tutor] inserting new lines in long strings while printing References: Message-ID: Abhishek Pratap wrote: > I have this one big string in python which I want to print to a file > inserting a new line after each 100 characters. Is there a slick way to do > this without looping over the string. I am pretty sure there shud be > something its just I am new to the lang. There is also textwrap.fill(). It honours word boundaries to some extent, so there may be lines that are shorter than the specified width. >>> import textwrap >>> print textwrap.fill("dere gewizzede bizz " + "a"*100, width=10) dere gewizzede bizz aaaaa aaaaaaaaaa aaaaaaaaaa aaaaaaaaaa aaaaaaaaaa aaaaaaaaaa aaaaaaaaaa aaaaaaaaaa aaaaaaaaaa aaaaaaaaaa aaaaa From fedka2 at gmail.com Wed Mar 7 11:31:46 2012 From: fedka2 at gmail.com (Paul Douglas Grant) Date: Wed, 7 Mar 2012 11:31:46 +0100 Subject: [Tutor] IDLE problems In-Reply-To: References: <1331057566.48396.YahooMailNeo@web86704.mail.ird.yahoo.com> Message-ID: >> OK, so from Finder. In that case can you open a Terminal window and >> drag the python folder into the Terminal - that should navigate you to >> the same folder. Then try running IDLE by typing >> >> python ./idle.py >> >> At the terminal prompt. > > > I meant to say that this will let you see any error messages > from running IDLE. If you get any, post them here. Here's what I get: Last login: Wed Mar 7 11:27:19 on ttys000 MacBook-001FF3569577-4:~ fedka2$ /Applications/Python\ 3.2 -bash: /Applications/Python 3.2: is a directory MacBook-001FF3569577-4:~ fedka2$ python ./idle.py /Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python: can't open file './idle.py': [Errno 2] No such file or directory MacBook-001FF3569577-4:~ fedka2$ I don't seem to be getting a terminal prompt after dragging the folder into the shell?? Thanks again Paul From fomcl at yahoo.com Wed Mar 7 11:44:55 2012 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Wed, 7 Mar 2012 02:44:55 -0800 (PST) Subject: [Tutor] inserting new lines in long strings while printing In-Reply-To: References: <20120307014135.GB19312@ando> Message-ID: <1331117095.8992.YahooMailNeo@web110709.mail.gq1.yahoo.com> ________________________________ From: Abhishek Pratap To: Steven D'Aprano Cc: tutor at python.org Sent: Wednesday, March 7, 2012 2:56 AM Subject: Re: [Tutor] inserting new lines in long strings while printing thanks guys .. > > > > >-Abhi > > >On Tue, Mar 6, 2012 at 5:41 PM, Steven D'Aprano wrote: > >On Tue, Mar 06, 2012 at 05:26:26PM -0800, Abhishek Pratap wrote: >>> I have this one big string in python which I want to print to a file >>> inserting a new line after each 100 characters. Is there a slick way to do >>> this without looping over the string. ?I am pretty sure there shud be >>> something its just I am new to the lang. >> >>>>> s = "a"*100 >>>>> print '\n'.join(s[i:i+10] for i in range(0, len(s), 10)) >>aaaaaaaaaa >>aaaaaaaaaa >>aaaaaaaaaa >>aaaaaaaaaa >>aaaaaaaaaa >>aaaaaaaaaa >>aaaaaaaaaa >>aaaaaaaaaa >>aaaaaaaaaa >>aaaaaaaaaa >> >> >----> Hi,?using the textwrap module?is also an option: >>>> import textwrap >>>> s = "a"*100 >>>> print "\n".join(textwrap.wrap(s, 10)) >aaaaaaaaaa >aaaaaaaaaa >aaaaaaaaaa >aaaaaaaaaa >aaaaaaaaaa >aaaaaaaaaa >aaaaaaaaaa >aaaaaaaaaa >aaaaaaaaaa >aaaaaaaaaa > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Mar 7 12:30:08 2012 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Wed, 7 Mar 2012 11:30:08 +0000 (GMT) Subject: [Tutor] IDLE problems In-Reply-To: References: <1331057566.48396.YahooMailNeo@web86704.mail.ird.yahoo.com> Message-ID: <1331119808.42546.YahooMailNeo@web86704.mail.ird.yahoo.com> Sorry, I was assuming too much knowledge I suspect. ? > Last login: Wed Mar? 7 11:27:19 on ttys000 > MacBook-001FF3569577-4:~ fedka2$ /Applications/Python\ 3.2 This line is the prompt plus the folder that you dragged :- ? /Applications/Python\ 3.2 You needed to type cd first (no RETURN just cd) - I took that step for granted, sorry. then drop the folder But since we now know the folder name you could just type cd?/Applications/Python\ 3.2 That should give you a terminal prompt of: MacBook-001FF3569577-4: /Applications/Python 3.2$ If that is where idle.py is? I would expect it to be lower down than that... Then you can type python ./idle.py If, as I suspect, idle.py is lower in the folder structure you will need to? modify things by providing the path to idle.py I hope that's clearer. One of the barriers to programming on a Mac for most users is? that they pretty much have to learn how to drive the Terminal. And? that's kind of a counter-culture to Mac users. Alan G From fedka2 at gmail.com Wed Mar 7 12:45:45 2012 From: fedka2 at gmail.com (Paul Douglas Grant) Date: Wed, 7 Mar 2012 12:45:45 +0100 Subject: [Tutor] IDLE problems In-Reply-To: <1331119808.42546.YahooMailNeo@web86704.mail.ird.yahoo.com> References: <1331057566.48396.YahooMailNeo@web86704.mail.ird.yahoo.com> <1331119808.42546.YahooMailNeo@web86704.mail.ird.yahoo.com> Message-ID: Thanks again, I'm going to push my luck and ask you a final question on this subject, you've been really helpful. Should I be able to locate idle.py with a spotlight search. I can't seem to locate it... Here is what terminal gave me MacBook-001FF3569577-4:~ fedka2$ cd /Applications/Python\ 3.2 MacBook-001FF3569577-4:Python 3.2 fedka2$ python ./idle.py /Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python: can't open file './idle.py': [Errno 2] No such file or directory MacBook-001FF3569577-4:Python 3.2 fedka2$ Thanks again, and here's to the hillwalking (I'm in the French Jura, so it is no stranger to me) Paul On Wed, Mar 7, 2012 at 12:30 PM, ALAN GAULD wrote: > Sorry, I was assuming too much knowledge I suspect. > >> Last login: Wed Mar? 7 11:27:19 on ttys000 > >> MacBook-001FF3569577-4:~ fedka2$ /Applications/Python\ 3.2 > > > This line is the prompt plus the folder that you dragged :- ? /Applications/Python\ 3.2 > > You needed to type cd first (no RETURN just cd) - I took that step for granted, sorry. > then drop the folder > > But since we now know the folder name you could just type > > cd?/Applications/Python\ 3.2 > > That should give you a terminal prompt of: > > MacBook-001FF3569577-4: /Applications/Python 3.2$ > > > If that is where idle.py is? I would expect it to be lower down than that... > > Then you can type > > python ./idle.py > > If, as I suspect, idle.py is lower in the folder structure you will need to > modify things by providing the path to idle.py > > I hope that's clearer. > One of the barriers to programming on a Mac for most users is > that they pretty much have to learn how to drive the Terminal. And > that's kind of a counter-culture to Mac users. > > Alan G From marko.limbek at valicon.net Wed Mar 7 16:20:50 2012 From: marko.limbek at valicon.net (Marko Limbek) Date: Wed, 7 Mar 2012 16:20:50 +0100 Subject: [Tutor] Question about writing to Excel with slavic characters In-Reply-To: References: <4F54B58A.7020402@compuscan.co.za> <1330975245.71342.YahooMailNeo@web110714.mail.gq1.yahoo.com> Message-ID: Hi, I have been trying to use that programme but without success. In Eclipse you usually create new project in two steps, first you create new Pydev project, then inside you create new Pydev module. I have created new project and new module 'crosstabs', where I want to read spss file. My programme is the module. Now I have put this ReaderWriter programme into the same Pydev project as a another new module called 'rw' and then imported it into my module 'crosstabs' with import rw from rw import SavReader I don't even know, if I did that correctly. Actually I don't even know how to implement that programme. I put the recommended code savFileName = "C:/dropbox/Exc_MarkoL_Zenel/Valicon/crosstabs/Tabela/ipk108_kosovo_data_finale_c1-1.sav" with SavReader(savFileName) as sav: header = sav.next() for line in sav: process(line) but I am get errors I have however managed to compile the programme in the module, I just had to comment more than 20 lines (because of that problem with "employee data.sav" ). I also don't know, if it was right to comment all those lines. Without commenting them I can't even compile the module. Maybe someone can tell me, how to actually implement that programme? Where to put it in my Eclipse? Is this programm ethe best way to read spss with Python? Thank you so much, Marko On Tue, Mar 6, 2012 at 4:53 PM, Marko Limbek wrote: > Hi Albert > > Two notes > first I have used the promising looking package memics and the result > is the same as foreign package. Reading in R is fine, but reading in > rpy on Python27 unfortunatelly I get funny characters again like > PRI?TINA > > second I have to run your programme and I get the following errors, > that I send in attachment as printscreen. There is a file "employee > data.sav" that I don't have and if I define my own file, I am asked in > the next step about the variable "id" that I also don't have. So I > would like to ask for your advise. > > Thanks, > Marko > > > > On Mon, Mar 5, 2012 at 8:20 PM, Albert-Jan Roskam wrote: >> Hi, >> >> The R package foreign, in particular the read.spss function has some known >> problems reading spss system files. The memisc package also has a function >> to read .sav files. The big advantage of that function is that you can >> select rows and columns prior to actually reading the data into memory. >> >> If you're just using R and Rpy to read .sav files, you could also consider >> using a Python program that I wrote a while ago: >> http://code.activestate.com/recipes/577811-python-reader-writer-for-spss-sav-files-linux-mac-/ >> It runs on Windows, Mac and Linux and requires no installation of spss. I'd >> be interested to hear your experiences. >> >> Regards, >> Albert-Jan >> >> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ >> All right, but apart from the sanitation, the medicine, education, wine, >> public order, irrigation, roads, a >> fresh water system, and public health, what have the Romans ever done for >> us? >> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ >> >> ________________________________ >> From: Marko Limbek >> To: cwitts at compuscan.co.za >> Cc: tutor at python.org >> Sent: Monday, March 5, 2012 2:05 PM >> Subject: Re: [Tutor] Question about writing to Excel with slavic characters >> >> Thank you! >> >> That was easy. Now I have another problem. >> I use RPy and read the spss database with method read.spss inside a >> nested R code in Python, that looks like that: >> >> >> import rpy >> >> r(""" >> >> library(foreign) >> >> baza <- read.spss(""" + analysis[0] + """) >> >> print(baza$demo_izob0) >> >> """) >> >> Now when my text data labels in spss have slavic characters, they are >> not recognised and output is something like that: >> >> stiriletna srednja ?ola >> nedokon?ana osnovna ?ola >> >> >> What should I do here? >> >> >> Thanks a lot, >> >> >> Marko >> >> >> >> >> On Mon, Mar 5, 2012 at 1:46 PM, Christian Witts >> wrote: >>> On 2012/03/05 02:37 PM, Marko Limbek wrote: >>> >>> Hi everyone. >>> >>> >>> I am new to list and few months old to Python. I am writing some text >>> to Excel and I open the new book and try to write to the book and the >>> save it using >>> >>> book.save >>> >>> Now when I write slavic characters in the text to Excel (?, ?, ?, for >>> instance 0xc5), I get an error, I can't save it. >>> I have declared appropriate encoding >>> >>> # -*- coding: utf-8 -*- >>> # coding= >>> #!/E:/Python >>> >>> and those characters appear normally in the code, but there seems to >>> be the problem with the function book.save. >>> Does anyone have any ideas, what would be the problem and how to solve >>> it? Some additional encoding or some changes or parameters to the >>> book.save method? >>> >>> Is that the right forum for my question? >>> >>> >>> Thank you, >>> >>> Marko >>> _______________________________________________ >>> Tutor maillist? -? Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> What package are you using to create your Excel workbook ? >>> If it's xlwt you can set your encoding type when you create your workbook >>> book = xlwt.Workbook(encoding="utf-8") >>> -- >>> >>> Christian Witts >>> Python Developer >> _______________________________________________ >> Tutor maillist? -? Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> From ramit.prasad at jpmorgan.com Wed Mar 7 17:24:47 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Wed, 7 Mar 2012 16:24:47 +0000 Subject: [Tutor] misunderstanding "any" In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF474194452@SCACMX008.exchad.jpmchase.net> > >>> a = tuple(range(10)) > >>> b = tuple(reversed(a)) > > >>> any(a) in b > True > > >>> any(b) in a > True > > >>> any((a,b)) in (a,b) > False # I think I understand this now, but I must admit it looks > confusing! I just want to clarify some things. 'any(a) in b' evaluates any(a) before it evaluates 'x in b'. So in essence 'any(a) in b' is equivalent to 'True in b'. The reason why you get True in the first two cases is because of Python's history where there were no bool types (I could be wrong on this). At the very least bool types inherit from integer in a common practice from older languages like C. Hopefully some of my samples will help explain my point. >>> a = range(10) >>> b = tuple( reversed( a ) ) >>> any(a) # Any non-zero value equates to true True >>> any(a) in b # True == 1 True >>> True in b # True == 1 True >>> any(b) # Any non-zero value equates to true True >>> True in a # True == 1 True >>> True == 1 # Proof that True == 1 True >>> False == 0 # Proof that False == 0 True >>> any( (a,b) ) # many non-zero values True >>> a = range( 10,20 ) # create a list without 1 >>> b = tuple( reversed( a ) ) >>> any( a ) # still contains non-zero values True >>> any( a ) in b # b is missing the value 1 and therefore missing True False >>> any( b ) # still contains non-zero values True >>> any (b ) in a # a is missing the value 1 and therefore missing True False >>> any( (a,b) ) # still contains non-zero values True >>> any ( (a,b) ) in ( a,b ) # a and b is missing the value 1 False >>> any ( (a,b) ) in ( a,b, 1 ) # 1 == True True > Thinking that if *any* of the tuples is in fruit_type(a list of tuples), then it should return True. What you want is not any, but probably filter or any + map. >>> c = zip( a, b ) >>> c [(10, 19), (11, 18), (12, 17), (13, 16), (14, 15), (15, 14), (16, 13), (17, 12), (18, 11), (19, 10)] >>> d = ( 11, 18 ) >>> filter( lambda x: d == x, c ) [(11, 18)] >>> >>> if filter( lambda x: d == x, c ): ... print 'True' ... True >>> map( lambda x: x==d, c ) [False, True, False, False, False, False, False, False, False, False] >>> any( map( lambda x: x==d, c ) ) True If you are comparing a list of tuples against a list of tuples merely change the above '==' to 'in' and d to be the second list of tuples and it should have similar results Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From d at davea.name Wed Mar 7 19:11:39 2012 From: d at davea.name (Dave Angel) Date: Wed, 07 Mar 2012 13:11:39 -0500 Subject: [Tutor] misunderstanding "any" In-Reply-To: References: Message-ID: <4F57A4DB.4090603@davea.name> On 03/07/2012 12:07 AM, col speed wrote: > > Then we have: > > >>>> a = tuple(range(10)) >>>> b = tuple(reversed(a)) >>>> any(a) in b > True > >>>> any(b) in a > True > >>>> any((a,b)) in (a,b) > False # I think I understand this now, but I must admit it looks confusing! > > Thanks again > Col None of those last three does anything usefully similar to your original request. Just because an English phrase makes sense, you can't expect the equivalent set of keywords to do anything remotely related. If you insist on using the any function in solving your problem, you'll have to preprocess your two arrays into a single iterator. And at that point, you might as well solve the problem in that loop. (untested): def test(a, b): for val1 in a: for val2 in b: if val1 == val2: return True return False print test(a,b) Rather than: def findinter(a, b): res = [] for val1 in a: for val2 in b: res.append(val1 == val2) return res print any(findinter(a,b)) -- DaveA From fedka2 at gmail.com Wed Mar 7 20:37:06 2012 From: fedka2 at gmail.com (Paul Douglas Grant) Date: Wed, 7 Mar 2012 20:37:06 +0100 Subject: [Tutor] IDLE problems FIXED Message-ID: Thanks Alan, It seems like it was a keybinding issue. When I dragged IDLE into a terminal window I got a laundry list of errors having to do with correct keys. I switched to a built in key set "classic mac", and I'm running. I really appreciated your help with this. Paul On Wed, Mar 7, 2012 at 12:25 AM, Alan Gauld wrote: > On 06/03/12 18:12, ALAN GAULD wrote: > >> OK, so from Finder. In that case can you open a Terminal window and >> drag the python folder into the Terminal - that should navigate you to >> the same folder. Then try running IDLE by typing >> >> python ./idle.py >> >> At the terminal prompt. > > > I meant to say that this will let you see any error messages > from running IDLE. If you get any, post them here. > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From steve at pearwood.info Wed Mar 7 23:36:47 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 08 Mar 2012 09:36:47 +1100 Subject: [Tutor] Question about writing to Excel with slavic characters In-Reply-To: References: <4F54B58A.7020402@compuscan.co.za> <1330975245.71342.YahooMailNeo@web110714.mail.gq1.yahoo.com> Message-ID: <4F57E2FF.1020000@pearwood.info> Marko Limbek wrote: > I put the recommended code > > savFileName = "C:/dropbox/Exc_MarkoL_Zenel/Valicon/crosstabs/Tabela/ipk108_kosovo_data_finale_c1-1.sav" > with SavReader(savFileName) as sav: > header = sav.next() > for line in sav: > process(line) > > > but I am get errors Will you tell us what errors, or should we just guess? Since I love guessing games, let me try... my guess is that you get AttributeError: 'SavReader' object has no attribute 'next' Am I close? If so, try using next(sav) instead of sav.next(). > I have however managed to compile the programme in the module, I just > had to comment more than 20 lines (because of that problem with > "employee data.sav" ). > I also don't know, if it was right to comment all those lines. Without > commenting them I can't even compile the module. Marko, it seems that you don't know how to program Python. Perhaps you should do a Python tutorial or two so you can fix the code instead of just commenting out lines. Perhaps start here: http://docs.python.org/tutorial/ -- Steven From ajarncolin at gmail.com Thu Mar 8 00:53:05 2012 From: ajarncolin at gmail.com (col speed) Date: Thu, 8 Mar 2012 06:53:05 +0700 Subject: [Tutor] misunderstanding "any" In-Reply-To: <4F57A4DB.4090603@davea.name> References: <4F57A4DB.4090603@davea.name> Message-ID: On 8 March 2012 01:11, Dave Angel wrote: > On 03/07/2012 12:07 AM, col speed wrote: >> >> >> >> Then we have: >> >> >>>>> a = tuple(range(10)) >>>>> b = tuple(reversed(a)) >>>>> any(a) in b >> >> True >> >>>>> any(b) in a >> >> True >> >>>>> any((a,b)) in (a,b) >> >> False ?# I think I understand this now, but I must admit it looks >> confusing! >> >> Thanks again >> Col > > > None of those last three does anything usefully similar to your original > request. ?Just because an English phrase makes sense, you can't expect the > equivalent set of keywords to do anything remotely related. > > If you insist on using the any function in solving your problem, you'll have > to preprocess your two arrays into a single iterator. ?And at that point, > you might as well solve the problem in that loop. > > (untested): > > def test(a, b): > ? ?for val1 in a: > ? ? ? ?for val2 in b: > ? ? ? ? ? ?if val1 == val2: ?return True > ? ?return False > print test(a,b) > > Rather than: > > def ?findinter(a, b): > ? ?res = [] > ? ?for val1 in a: > ? ? ? ? for val2 in b: > ? ? ? ? ? ? ?res.append(val1 == val2) > ? ?return res > > print any(findinter(a,b)) > > > > -- > > DaveA > Thanks again to everybody for your very clear explanations. I have done away with any and have defined a function that iterates through one list and returns True if *i* in the next . It seems to work every time and also looks a little clearer. Cheers Col From sudipb at sudipb.com Thu Mar 8 12:11:57 2012 From: sudipb at sudipb.com (Sudip Bhattacharya) Date: Thu, 8 Mar 2012 16:41:57 +0530 Subject: [Tutor] Tuple - Immutable ? Message-ID: >>> s=(1,2,3) >>> s=s+(4,5,6) >>>s (1,2,3,4,5,6) The tuple has changed. I thought I read that tuples are sequences (like lists), but they are immutable - They can't be changed once created. Could someone explain please ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Thu Mar 8 12:21:50 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 08 Mar 2012 22:21:50 +1100 Subject: [Tutor] Tuple - Immutable ? In-Reply-To: References: Message-ID: <4F58964E.2060906@pearwood.info> Sudip Bhattacharya wrote: >>>> s=(1,2,3) >>>> s=s+(4,5,6) >>>> s > (1,2,3,4,5,6) > > The tuple has changed. No it hasn't. You have created a *new* tuple, and assigned it to the same name. Consider: py> s = (1, 2, 3) py> id(s) 3083421332 py> t = s py> id(t) 3083421332 This shows that both s and t are names for the same tuple, with ID 3083421332. Now watch when we use += on s: py> s += (4, 5) py> id(s) 3083534812 py> id(t) 3083421332 py> t (1, 2, 3) The ID of s has changed, but t stays the same. So the original tuple remains untouched, and a new tuple is created. If you do the same thing with lists, you will see that because lists are mutable, it does *not* create a new list, but changes the original in place: py> a = [1, 2, 3] py> b = a py> a += [4, 5] py> b [1, 2, 3, 4, 5] -- Steven From wprins at gmail.com Thu Mar 8 12:23:37 2012 From: wprins at gmail.com (Walter Prins) Date: Thu, 8 Mar 2012 11:23:37 +0000 Subject: [Tutor] Tuple - Immutable ? In-Reply-To: References: Message-ID: On 8 March 2012 11:11, Sudip Bhattacharya wrote: >>>> s=(1,2,3) >>>> s=s+(4,5,6) >>>>s > (1,2,3,4,5,6) > > The tuple has changed. No, the tuple hasn't changed. That's a *new* tuple. Consider: Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on win32 Type "copyright", "credits" or "license()" for more information. >>> s=(1,2,3) >>> id(s) 44137280L >>> s=s+(4,5,6) >>> id(s) 34277416L >>> l=[1,2,3] >>> id(l) 44152072L >>> l.extend([4,5,6]) >>> id(l) 44152072L >>> l [1, 2, 3, 4, 5, 6] >>> l=l+[7,8,9] >>> id(l) 44150856L >>> l [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> So, as you can see, in the case of the tuple, the addition actually creates a *new* tuple (different id) that consists of the members of the 2 input tuples, whereas in the case of the list, since the list is mutable, the same list (same id) is *changed* when you add another list to it. Walter From ajarncolin at gmail.com Thu Mar 8 12:23:50 2012 From: ajarncolin at gmail.com (col speed) Date: Thu, 8 Mar 2012 18:23:50 +0700 Subject: [Tutor] Tuple - Immutable ? In-Reply-To: References: Message-ID: On 8 March 2012 18:11, Sudip Bhattacharya wrote: >>>> s=(1,2,3) >>>> s=s+(4,5,6) >>>>s > (1,2,3,4,5,6) > > The tuple has changed. > > I thought I read that tuples are sequences (like lists), but they are > immutable - They can't be changed once created. Could someone explain please > ? I'm just a noob, but as nobody else has replied yet...... As far as I *think* I know: s=s+(4,5,6) creates a new tuple, it doesn't change it. Tuples are immutable as in you can't add or append and stuff. Also: >>> s[0] = 8 Traceback (most recent call last): File "", line 1, in TypeError: 'tuple' object does not support item assignment Nor does it have attribute "reverse" or anything like that. HTH Col From wprins at gmail.com Thu Mar 8 12:27:05 2012 From: wprins at gmail.com (Walter Prins) Date: Thu, 8 Mar 2012 11:27:05 +0000 Subject: [Tutor] Tuple - Immutable ? In-Reply-To: References: Message-ID: Just to add, notice that even for lists, l = l + [7,8,9] produces a new list, while l += [7,8,9] does not. From ajarncolin at gmail.com Thu Mar 8 12:33:17 2012 From: ajarncolin at gmail.com (col speed) Date: Thu, 8 Mar 2012 18:33:17 +0700 Subject: [Tutor] Tuple - Immutable ? In-Reply-To: References: Message-ID: On 8 March 2012 18:27, Walter Prins wrote: > Just to add, notice that even for lists, > > l = l + [7,8,9] > > produces a new list, while > > l += [7,8,9] > > does not. > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor I was just thinking about the immutability of things and tried this (which -at least I- find interesting: >>> id(1) 154579120 >>> a = 1 >>> id(a) 154579120 >>> a += 2 >>> id(a) 154579096 >>> id(3) 154579096 >>> a is 3 True >>> Although there is probably no other logical way of doing it - I learnt something new again! From sudipb at sudipb.com Thu Mar 8 12:41:28 2012 From: sudipb at sudipb.com (Sudip Bhattacharya) Date: Thu, 8 Mar 2012 17:11:28 +0530 Subject: [Tutor] Tuple - Immutable ? In-Reply-To: References: Message-ID: That makes perfect sense. What happened was that the old tuple got replaced with a new tuple (old + new items) and NOT changed cause tuple is immutable. Thanks HTH. On Thu, Mar 8, 2012 at 4:53 PM, col speed wrote: > On 8 March 2012 18:11, Sudip Bhattacharya wrote: > >>>> s=(1,2,3) > >>>> s=s+(4,5,6) > >>>>s > > (1,2,3,4,5,6) > > > > The tuple has changed. > > > > I thought I read that tuples are sequences (like lists), but they are > > immutable - They can't be changed once created. Could someone explain > please > > ? > > I'm just a noob, but as nobody else has replied yet...... > As far as I *think* I know: > s=s+(4,5,6) creates a new tuple, it doesn't change it. > Tuples are immutable as in you can't add or append and stuff. > Also: > > >>> s[0] = 8 > Traceback (most recent call last): > File "", line 1, in > TypeError: 'tuple' object does not support item assignment > Nor does it have attribute "reverse" or anything like that. > > HTH > Col > -- Thanks and regards, Sudip Bhattacharya Mobile: +91 9999 100 706 Home Land line: +91 11 22237561 Office Land line: +91 0124 4321078 eMail ID: sudipb at sudipb.com; sudipb at gmail.com Please visit my website at: www.sudipb.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Thu Mar 8 12:51:33 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 08 Mar 2012 22:51:33 +1100 Subject: [Tutor] Tuple - Immutable ? In-Reply-To: References: Message-ID: <4F589D45.7050306@pearwood.info> col speed wrote: > I was just thinking about the immutability of things and tried this > (which -at least I- find interesting: > >>>> id(1) > 154579120 >>>> a = 1 >>>> id(a) > 154579120 >>>> a += 2 >>>> id(a) > 154579096 >>>> id(3) > 154579096 >>>> a is 3 > True > Although there is probably no other logical way of doing it - I learnt > something new again! Prepare to have your mind boggled: py> a = 99 py> b = 99 py> a is b True py> a = 9912345 py> b = 9912345 py> a is b False Well, okay, so it's not *much* of a boggle. Perhaps a bogglet. What happens is that Python caches the small integers, like -1, 0, 1, up to some limit, and re-uses them when and as needed. That limit various from version to version, so you can't rely on it. But larger integers are not cached, and so you get a fresh one each time. This makes sense, and is easy to understand. Now for the real boggle: py> a = 9912346; b = 9912346 py> a is b True Can you guess what is going on here? (Answer will follow later.) -- Steven From ajarncolin at gmail.com Thu Mar 8 12:57:14 2012 From: ajarncolin at gmail.com (col speed) Date: Thu, 8 Mar 2012 18:57:14 +0700 Subject: [Tutor] Tuple - Immutable ? In-Reply-To: <4F589D45.7050306@pearwood.info> References: <4F589D45.7050306@pearwood.info> Message-ID: On 8 March 2012 18:51, Steven D'Aprano wrote: > col speed wrote: > >> I was just thinking about the immutability of things and tried this >> (which -at least I- find interesting: >> >>>>> id(1) >> >> 154579120 >>>>> >>>>> a = 1 >>>>> id(a) >> >> 154579120 >>>>> >>>>> a += 2 >>>>> id(a) >> >> 154579096 >>>>> >>>>> id(3) >> >> 154579096 >>>>> >>>>> a is 3 >> >> True >> Although there is probably no other logical way of doing it - I learnt >> something new again! > > > Prepare to have your mind boggled: > > py> a = 99 > py> b = 99 > py> a is b > True > py> a = 9912345 > py> b = 9912345 > py> a is b > False > > > Well, okay, so it's not *much* of a boggle. Perhaps a bogglet. > > What happens is that Python caches the small integers, like -1, 0, 1, up to > some limit, and re-uses them when and as needed. That limit various from > version to version, so you can't rely on it. But larger integers are not > cached, and so you get a fresh one each time. > > This makes sense, and is easy to understand. Now for the real boggle: > > py> a = 9912346; b = 9912346 > py> a is b > True > > Can you guess what is going on here? > > (Answer will follow later.) > > > > -- > Steven Because it's on the same line and there are 2 variables with the same int, it gets cached??? Otherwise I'm truly boggled(a normal state of mind for me). From jensenjohn59 at yahoo.com Thu Mar 8 13:18:51 2012 From: jensenjohn59 at yahoo.com (John Jensen) Date: Thu, 8 Mar 2012 04:18:51 -0800 (PST) Subject: [Tutor] Tuple - Immutable ? In-Reply-To: <4F589D45.7050306@pearwood.info> References: <4F589D45.7050306@pearwood.info> Message-ID: <1331209131.7203.YahooMailNeo@web125604.mail.ne1.yahoo.com> ________________________________ From: Steven D'Aprano To: tutor at python.org Sent: Thursday, March 8, 2012 7:51:33 AM Subject: Re: [Tutor] Tuple - Immutable ? col speed wrote: > I was just thinking about the immutability of things and tried this > (which -at least I- find interesting: > >>>> id(1) > 154579120 >>>> a = 1 >>>> id(a) > 154579120 >>>> a += 2 >>>> id(a) > 154579096 >>>> id(3) > 154579096 >>>> a is 3 > True > Although there is probably no other logical way of doing it - I learnt > something new again! Prepare to have your mind boggled: py> a = 99 py> b = 99 py> a is b True py> a = 9912345 py> b = 9912345 py> a is b False Well, okay, so it's not *much* of a boggle. Perhaps a bogglet. What happens is that Python caches the small integers, like -1, 0, 1, up to some limit, and re-uses them when and as needed. That limit various from version to version, so you can't rely on it. But larger integers are not cached, and so you get a fresh one each time. This makes sense, and is easy to understand. Now for the real boggle: py> a = 9912346; b = 9912346 py> a is b True Can you guess what is going on here? (Answer will follow later.) I'll preface my answer by stating that I'm a noob and haven't checked the documentation for my answer, but I would guess that Python is saving the variables as integer values and that the larger values would require them being saved as doubles. -- Steven _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From ajarncolin at gmail.com Thu Mar 8 13:45:48 2012 From: ajarncolin at gmail.com (col speed) Date: Thu, 8 Mar 2012 19:45:48 +0700 Subject: [Tutor] Tuple - Immutable ? In-Reply-To: <1331209131.7203.YahooMailNeo@web125604.mail.ne1.yahoo.com> References: <4F589D45.7050306@pearwood.info> <1331209131.7203.YahooMailNeo@web125604.mail.ne1.yahoo.com> Message-ID: On 8 March 2012 19:18, John Jensen wrote: > ________________________________ > From: Steven D'Aprano > To: tutor at python.org > Sent: Thursday, March 8, 2012 7:51:33 AM > Subject: Re: [Tutor] Tuple - Immutable ? > > col speed wrote: > >> I was just thinking about the immutability of things and tried this >> (which -at least I- find interesting: >> >>>>> id(1) >> 154579120 >>>>> a = 1 >>>>> id(a) >> 154579120 >>>>> a += 2 >>>>> id(a) >> 154579096 >>>>> id(3) >> 154579096 >>>>> a is 3 >> True >> Although there is probably no other logical way of doing it - I learnt >> something new again! > > Prepare to have your mind boggled: > > py> a = 99 > py> b = 99 > py> a is b > True > py> a = 9912345 > py> b = 9912345 > py> a is b > False > > > Well, okay, so it's not *much* of a boggle. Perhaps a bogglet. > > What happens is that Python caches the small integers, like -1, 0, 1, up to > some limit, and re-uses them when and as needed. That limit various from > version to version, so you can't rely on it. But larger integers are not > cached, and so you get a fresh one each time. > > This makes sense, and is easy to understand. Now for the real boggle: > > py> a = 9912346; b = 9912346 > py> a is b > True > > Can you guess what is going on here? > > (Answer will follow later.) > > I'll preface my answer by stating that I'm a noob and haven't checked the > documentation for my answer, but I would guess that Python is saving the > variables as integer values and that the larger values would require them > being saved as doubles. > > > -- Steven > > _______________________________________________ > Tutor maillist? -? Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Thanks From ejjyrex at gmail.com Thu Mar 8 14:13:05 2012 From: ejjyrex at gmail.com (Ejaj Hassan) Date: Thu, 8 Mar 2012 18:43:05 +0530 Subject: [Tutor] Refactoring Message-ID: Hi, I have been hearing this refactoring of code. Well does it have any thing like this in Python and if it is then what is it all about. Thanks. Regards, Ejaj From Steve.Flynn at capita.co.uk Thu Mar 8 13:01:54 2012 From: Steve.Flynn at capita.co.uk (Flynn, Stephen (L & P - IT)) Date: Thu, 8 Mar 2012 12:01:54 -0000 Subject: [Tutor] Python 3.2 - difference between out of dir() and help() Message-ID: Pythonistas, Tinkering around this morning and noticed the following when I created a tuple and asked for a dir() on it and some help() on it. >>> x=('rod','jane','freddy') >>> dir(x) ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index'] >>> help(x) Help on tuple object: class tuple(object) | tuple() -> empty tuple [etc... snipped for brevity] All pretty standard stuff. I did however notice that the dir(x) told me about __class__, __reduce__ and __reduce_ex__ where the help(x) made no mention of them. Why is this difference? I presume the two commands using different means of getting at and displaying the methods for an object? Is help() giving me all of the useful methods an object has which I'm encouraged to make use of, whereas dir gives me a complete list of everything that object can 'do' including those methods which aren't really meant for public consumption? P.S. Posting from work, so I've configured this mail software to post to this address in plain text. I'm hoping this email is going to get converted to plain text when I hit send, as it looks decidedly html/rich text as I type... Steve Flynn | Technical Architect | Life & Pensions Services | Capita | The Grange, Bishops Cleeve, GL52 8XX | 01242-670864 Part of Capita plc www.capita.co.uk Capita Life & Pensions Services Limited is registered in England No 4359665 Capita Life & Pensions Regulated Services Limited is registered in England No 2424853 Registered office: 71 Victoria Street, Westminster, London SW1H 0XA Capita Life & Pensions Regulated Services Limited is authorised and regulated by the Financial Services Authority. This email and any attachment to it are confidential. Unless you are the intended recipient, you may not use, copy or disclose either the message or any information contained in the message. If you are not the intended recipient, you should delete this email and notify the sender immediately. Any views or opinions expressed in this email are those of the sender only, unless otherwise stated. All copyright in any Capita material in this email is reserved. All emails, incoming and outgoing, may be recorded by Capita and monitored for legitimate business purposes. Capita exclude all liability for any loss or damage arising or resulting from the receipt, use or transmission of this email to the fullest extent permitted by law. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Thu Mar 8 14:31:15 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 09 Mar 2012 00:31:15 +1100 Subject: [Tutor] Tuple - Immutable ? In-Reply-To: References: <4F589D45.7050306@pearwood.info> Message-ID: <4F58B4A3.4060607@pearwood.info> col speed wrote: > On 8 March 2012 18:51, Steven D'Aprano wrote: >> This makes sense, and is easy to understand. Now for the real boggle: >> >> py> a = 9912346; b = 9912346 >> py> a is b >> True >> >> Can you guess what is going on here? >> >> (Answer will follow later.) > Because it's on the same line and there are 2 variables with the same > int, it gets cached??? Almost correct, but well done. Yes, the trick is that they are on the same line. But you're *almost* correct, because the value doesn't actually gets cached. It only gets re-used in the context of that one line. If you then follow with a second line using the same 9912346, it gets a different ID. All of these details are implementation tricks. They are subject to change without notice, and the exact rules are not documented anywhere (except perhaps in the source code) so there is no language promise that they will apply. But they are interesting little tricks nevertheless. -- Steven From cwitts at compuscan.co.za Thu Mar 8 14:37:06 2012 From: cwitts at compuscan.co.za (Christian Witts) Date: Thu, 08 Mar 2012 15:37:06 +0200 Subject: [Tutor] Refactoring In-Reply-To: References: Message-ID: <4F58B602.7070709@compuscan.co.za> On 2012/03/08 03:13 PM, Ejaj Hassan wrote: > Hi, > I have been hearing this refactoring of code. Well does it have > any thing like this in Python and if it is then what is it all about. > Thanks. > Regards, > Ejaj > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > /"Refactoring is the process of changing a software system in such a way that it does not alter the external behavior of the code yet improves its internal structure."/ -- Martin Fowler in Refactoring: Improving The Design Of Existing Code [1] As for Python IDEs that have built-in refactoring tools, I know of PyCharm [2] which handles it. [1] http://martinfowler.com/refactoring/ [2] http://www.jetbrains.com/pycharm/features/ -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.sjoblom at gmail.com Thu Mar 8 14:41:17 2012 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Thu, 8 Mar 2012 14:41:17 +0100 Subject: [Tutor] Refactoring In-Reply-To: References: Message-ID: > Hi, > ? I have been hearing this refactoring of code. Well does it ?have > any thing like this in Python and if it is then what is it all about. > Thanks. > Regards, > Ejaj Refactoring is just a way of restructuring code. It can be breaking code apart to more logical pieces -- moving parts of a class to a new class for instance or renaming methods to better say what they're about, subclassing or superclassing things and such. -- best regards, Robert S. From bozra at simbanet.co.tz Thu Mar 8 14:54:08 2012 From: bozra at simbanet.co.tz (Bozra Moses) Date: Thu, 8 Mar 2012 16:54:08 +0300 Subject: [Tutor] Begginner References: Message-ID: <021501ccfd32$eefde2f0$ccf9a8d0$@co.tz> Hi all, I have just finished installing python on a centos machine but I don't know where to begin learning this language. Please help on how to go about after installation, any useful materials will help. Thanks & regards, Bozra Moses. From steve at pearwood.info Thu Mar 8 15:06:23 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 09 Mar 2012 01:06:23 +1100 Subject: [Tutor] Refactoring In-Reply-To: References: Message-ID: <4F58BCDF.8040702@pearwood.info> Ejaj Hassan wrote: > Hi, > I have been hearing this refactoring of code. Well does it have > any thing like this in Python and if it is then what is it all about. "Refactoring" is a general technique that applies to any language, not just Python. Refactoring means to take a program which is written in a complicated way, not easy to understand, and gradually simplify it so that it becomes easier to understand and maintain without starting from scratch or changing the behaviour. The trick with refactoring is to find parts of the program that have common, related code. Here is a toy example -- suppose I had code that looks like this: # Ask the user for a number between one and ten. print "Please enter a number between 1 and 10" while True: a = int(raw_input("My number is: ")) if 1 <= a <= 10: break print "I'm sorry, your number was not between 1 and 10" print "please try again" # Ask the user for a number between ten and twenty. print "Please enter a number between 10 and 20" while True: b = int(raw_input("My number is: ")) if 10 <= a <= 20: break print "I'm sorry, your number was not between 10 and 20" print "please try again" # And one more between twenty and 100. print "Please enter a number between 20 and 100" while True: c = int(raw_input("My number is: ")) if 20 <= c <= 100: break print "I'm sorry, your number was not between 1 and 10" print "please try again" print a+b+c Look at all that duplicated code! And if you look carefully, you'll see a silly bug in it as well. You might re-factor that code like so: def get_number(low, high): # Ask the user for a number between low and high. print "Please enter a number between", low, "and", high while True: n = int(raw_input("My number is: ")) if low <= n <= high: break print "I'm sorry, your number was not between", low, "and", high print "please try again" return n a = get_number(1, 10) b = get_number(10, 20) c = get_number(20, 100) print a+b+c Notice that in refactoring, the aim should be to end up with code that is easier to maintain in the future. In this example, all the repeated code is now in one place, so instead of having to make changes to it in three different places, we can make it in one place. -- Steven From steve at pearwood.info Thu Mar 8 15:16:05 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 09 Mar 2012 01:16:05 +1100 Subject: [Tutor] Begginner In-Reply-To: <021501ccfd32$eefde2f0$ccf9a8d0$@co.tz> References: <021501ccfd32$eefde2f0$ccf9a8d0$@co.tz> Message-ID: <4F58BF25.6050406@pearwood.info> Bozra Moses wrote: > Hi all, > > I have just finished installing python on a centos machine but I don't know > where to begin learning this language. Do you know how to search the internet? You should always try searching the Internet first for an answer. https://duckduckgo.com/html/?q=python%20tutorial Here are some tutorials you might try: http://docs.python.org/tutorial/ http://www.alan-g.me.uk/tutor/index.htm http://www.learnpython.org/ http://coolnamehere.com/geekery/python/pythontut.html and many, many others. Good luck, and welcome! -- Steven From marko.limbek at valicon.net Thu Mar 8 15:59:31 2012 From: marko.limbek at valicon.net (Marko Limbek) Date: Thu, 8 Mar 2012 15:59:31 +0100 Subject: [Tutor] Question about writing to Excel with slavic characters In-Reply-To: <4F57E2FF.1020000@pearwood.info> References: <4F54B58A.7020402@compuscan.co.za> <1330975245.71342.YahooMailNeo@web110714.mail.gq1.yahoo.com> <4F57E2FF.1020000@pearwood.info> Message-ID: On Wed, Mar 7, 2012 at 11:36 PM, Steven D'Aprano wrote: > Marko Limbek wrote: > >> I put the recommended code >> >> savFileName = >> "C:/dropbox/Exc_MarkoL_Zenel/Valicon/crosstabs/Tabela/ipk108_kosovo_data_finale_c1-1.sav" >> with SavReader(savFileName) as sav: >> ? ?header = sav.next() >> ? ?for line in sav: >> ? ? ? ?process(line) >> >> >> but I am get errors > > > > Will you tell us what errors, or should we just guess? > > Since I love guessing games, let me try... my guess is that you get > > AttributeError: 'SavReader' object has no attribute 'next' > > Am I close? If so, try using next(sav) instead of sav.next(). I overcame commenting. I managed to read my own file and print it. Now I am trying to use method getNumberofVariables() but unsuccesfully. First way SavReader(savFileName).getNumberofVariables() gives me this error Traceback (most recent call last): File "C:\Dropbox\Exc_MarkoL_Zenel\Python\crosstabs\src\src\rw.py", line 660, in SavReader(savFileName).getNumberofVariables() TypeError: getNumberofVariables() takes exactly 3 arguments (1 given) Second way getNumberofVariables(savFileName, fh, spssio) gives me this error Traceback (most recent call last): File "C:\Dropbox\Exc_MarkoL_Zenel\Python\crosstabs\src\src\rw.py", line 660, in getNumberofVariables(savFileName, fh, spssio) NameError: name 'getNumberofVariables' is not defined Why there needs to be fh and spssio? I would like to be able to know how to use all the methods to run and test them and see, if any of them can give me labels from the file instead of just pure numbers, before I start asking questions if there is any method that can read labels. I am really sorry but I tried to find answers to that in the tutorial. I would like to read labels with such characters like ??? and not just read pure numbers. > > >> I have however managed to compile the programme in the module, I just >> had to comment more than 20 lines (because of that problem with >> "employee data.sav" ). >> I also don't know, if it was right to comment all those lines. Without >> commenting them I can't even compile the module. > > > > Marko, it seems that you don't know how to program Python. Perhaps you > should do a Python tutorial or two so you can fix the code instead of just > commenting out lines. > > Perhaps start here: http://docs.python.org/tutorial/ > I have been using Python for a few months now and I am a mathematician, so I have done some programming. It is true however that I am not trained programmer. So please excuse dumb questions. But I have fixed the code so far that I can read and print. Marko From steve at pearwood.info Thu Mar 8 15:59:39 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 09 Mar 2012 01:59:39 +1100 Subject: [Tutor] Python 3.2 - difference between out of dir() and help() In-Reply-To: References: Message-ID: <4F58C95B.2070505@pearwood.info> Flynn, Stephen (L & P - IT) wrote: > All pretty standard stuff. I did however notice that the > dir(x) told me about __class__, __reduce__ and __reduce_ex__ where the > help(x) made no mention of them. Why is this difference? I presume the > two commands using different means of getting at and displaying the > methods for an object? Yes. Both help() and dir() attempt to give an "interesting" list of attributes, and both have different ideas of what counts as "interesting". There is no hard rules as to what they will give, consequently they may change from version to version. Any differences are unlikely to be deliberate, but merely side-effects of the specific implementation of each. By the way, help() is a complete interactive environment. Just call help() with no arguments and follow the prompts. > Is help() giving me all of the useful methods an object > has which I'm encouraged to make use of, whereas dir gives me a complete > list of everything that object can 'do' including those methods which > aren't really meant for public consumption? Nothing so specific. See the documentation for both: http://docs.python.org/library/functions.html#dir http://docs.python.org/library/functions.html#help -- Steven From wprins at gmail.com Thu Mar 8 17:18:27 2012 From: wprins at gmail.com (Walter Prins) Date: Thu, 8 Mar 2012 16:18:27 +0000 Subject: [Tutor] Question about writing to Excel with slavic characters In-Reply-To: References: <4F54B58A.7020402@compuscan.co.za> <1330975245.71342.YahooMailNeo@web110714.mail.gq1.yahoo.com> <4F57E2FF.1020000@pearwood.info> Message-ID: Hi Marko, I'm going out on a limb here as I know next to nothing about either SPSS or Albert-Jan's wrapper module, and so with that caveat, some comments/observations: On 8 March 2012 14:59, Marko Limbek wrote: > I overcame commenting. I managed to read my own file and print it. Now > I am trying to use method getNumberofVariables() ?but unsuccesfully. > First way > > SavReader(savFileName).getNumberofVariables() > > gives me this error > > Traceback (most recent call last): > ?File "C:\Dropbox\Exc_MarkoL_Zenel\Python\crosstabs\src\src\rw.py", > line 660, in > ? ?SavReader(savFileName).getNumberofVariables() > TypeError: getNumberofVariables() takes exactly 3 arguments (1 given) > > > > Second way > > getNumberofVariables(savFileName, fh, spssio) > > gives me this error > > Traceback (most recent call last): > ?File "C:\Dropbox\Exc_MarkoL_Zenel\Python\crosstabs\src\src\rw.py", > line 660, in > ? ?getNumberofVariables(savFileName, fh, spssio) > NameError: name 'getNumberofVariables' is not defined The short answer: ============== Don't use getNumberofVariables, use the script as demonstrated at the bottom of the script in the "if __name__ == "__main__" section. I suppose something like this should do (I've modified it slightly to make it a bit more obvious what's happening): ## ----- Get some basic file info savFileName = r"C:\Program Files\IBM\SPSS\Statistics\19\Samples\English\Employee data.sav" mySavReaderObj = SavReader(savFileName) numVars, nCases, varNames, varTypes, printTypesFile, printTypeLabels, varWids = \ mySavReaderObj.getSavFileInfo() #Now the number of variables is presumably in numVars... The longer answer: ============== Firstly, getNumberofVariables() is defined as a class instance method. This means you can only ever call it on an object instance of that class. It is not a standalone function that can be called freestanding as you tried to do in your latter attempt. That is why you got the "not defined" error -- There is no freestanding function by that name (even if there happens to be a /method/ by that name inside the SavReader class.) so Python complained as such. Your prior attempt, which as you noticed requires to have parameters fh and spssio supplied appears to me to be effectively somewhat of an internal/private/helper method that is written in the style of a function, so consequently the method has no external dependencies on any state in the object/class and hence has to have the spssio and fh supplied when it's called. You can see elsewhere in the class when this method is called, the object itself keeps track of the fh and the sspsio and so passes these into the method as required. >From this you can infer that you'd be able to do the same and thus successfully call getNumberofVariables() by retrieving the fh and sspsio from your SavReader object (e.g. what I called mySavReaderObj above), by passing in mySavReaderObj.fh and mySavREaderObj.spssio when calling mySavReaderObj.getNumberofVariables(). But, as per the short answer, you probably don't want to do that. As an aside it also then follows it would be possible to rewrite/refactor the getNumberofVariables() method (and indeed several others) to remove the fh and sspsio parameters, by having them picked up directly from the object instance when required. Debateably, it might be an improvement that makes the code a bit more object oriented and less surprising to use. HTH, Walter From ejjyrex at gmail.com Fri Mar 9 00:49:44 2012 From: ejjyrex at gmail.com (Ejaj Hassan) Date: Fri, 9 Mar 2012 05:19:44 +0530 Subject: [Tutor] disutils Message-ID: Hi, I was just going through a book on python and came across this 'disutils'. Can somebody explained to me about this. Regards, Ejaj From alan.gauld at btinternet.com Fri Mar 9 01:21:12 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 09 Mar 2012 00:21:12 +0000 Subject: [Tutor] disutils In-Reply-To: References: Message-ID: On 08/03/12 23:49, Ejaj Hassan wrote: > I was just going through a book on python and came across this > 'disutils'. Can somebody explained to me about this. I assume you mean distutils? If so here is the official help description: ---------------- DESCRIPTION The main package for the Python Module Distribution Utilities. Normally used from a setup script as from distutils.core import setup setup (...) ------------------- So it's a set of tools for distributing your finished code modules so that other people can easily install them on their computer. Now, what else do you need to know? The more specific the question the more specific the answer... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From d at davea.name Fri Mar 9 02:58:44 2012 From: d at davea.name (Dave Angel) Date: Thu, 08 Mar 2012 20:58:44 -0500 Subject: [Tutor] disutils In-Reply-To: References: Message-ID: <4F5963D4.5040907@davea.name> On 03/08/2012 06:49 PM, Ejaj Hassan wrote: > Hi, > I was just going through a book on python and came across this > 'disutils'. Can somebody explained to me about this. > Regards, > Ejaj Without mentioning the book, how are we supposed to guess what disutils is? Or perhaps you meant distutils? If so, check out this link: http://www.python.org/community/sigs/current/distutils-sig/ and start a new thread there, or here, with the correct spelling. -- DaveA From bbbgggwww at gmail.com Fri Mar 9 03:07:46 2012 From: bbbgggwww at gmail.com (brandon w) Date: Thu, 8 Mar 2012 21:07:46 -0500 Subject: [Tutor] Python using RXVT vs Konsole? Message-ID: I have noticed the difference in terminals when using the Python interpreter. I am able to up-arrow to get the last typed command using rxvt but when I use konsole and I press the up-arrow I get the symbols: ^[[A Why is that? Is this the right place to ask this question? I want to be able to use the up-arrow in all terminals so I don't have to type as much. Python os: 2.6.6 OS: Slackware 13.37 Brandon -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Fri Mar 9 03:58:27 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 9 Mar 2012 13:58:27 +1100 Subject: [Tutor] Python using RXVT vs Konsole? In-Reply-To: References: Message-ID: <20120309025826.GA30395@ando> On Thu, Mar 08, 2012 at 09:07:46PM -0500, brandon w wrote: > I have noticed the difference in terminals when using the Python > interpreter. > I am able to up-arrow to get the last typed command using rxvt but when I > use konsole and I press the up-arrow I get the symbols: ^[[A > Why is that? Is this the right place to ask this question? I want to be > able to > use the up-arrow in all terminals so I don't have to type as much. Assuming you are using the same Python executable in both terminals, then it isn't a problem with Python, but with the settings for Konsole. Which surprises me, since I've used Konsole and it just works fine. (Although if you're using KDE 4, nothing would surprise me...) Try this, in both terminals: Start the Python interactive interpreter Enter import readline If they both succeed, then the problem is that Konsole is (somehow!) not using readline when it should be. You may need to ask for help in a KDE forum. If you are using two different Python executables, then possibly one of them is not built using the readline library, in which case you should install the GNU readline utils package on that machine and re-build Python. If none of these things help, you may need to ask the question on the main Python list, python-list at python.org or comp.lang.python. -- Steven From bbbgggwww at gmail.com Fri Mar 9 05:24:55 2012 From: bbbgggwww at gmail.com (brandon w) Date: Thu, 8 Mar 2012 23:24:55 -0500 Subject: [Tutor] Python using RXVT vs Konsole? In-Reply-To: <20120309025826.GA30395@ando> References: <20120309025826.GA30395@ando> Message-ID: I am using fluxbox an a window manager not KDE. That may have something to do with it. I will ask in another forum. Running: >>> import readline in both terminals succeded. Thank you for your help. Brandon On Thu, Mar 8, 2012 at 9:58 PM, Steven D'Aprano wrote: > On Thu, Mar 08, 2012 at 09:07:46PM -0500, brandon w wrote: > > I have noticed the difference in terminals when using the Python > > interpreter. > > I am able to up-arrow to get the last typed command using rxvt but when I > > use konsole and I press the up-arrow I get the symbols: ^[[A > > Why is that? Is this the right place to ask this question? I want to be > > able to > > use the up-arrow in all terminals so I don't have to type as much. > > Assuming you are using the same Python executable in both terminals, > then it isn't a problem with Python, but with the settings for Konsole. > Which surprises me, since I've used Konsole and it just works fine. > (Although if you're using KDE 4, nothing would surprise me...) > > Try this, in both terminals: > > Start the Python interactive interpreter > Enter import readline > > If they both succeed, then the problem is that Konsole is (somehow!) not > using readline when it should be. You may need to ask for help in a KDE > forum. > > If you are using two different Python executables, then possibly one of > them is not built using the readline library, in which case you should > install the GNU readline utils package on that machine and re-build > Python. > > If none of these things help, you may need to ask the question on the > main Python list, python-list at python.org or comp.lang.python. > > > > -- > Steven > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From marko.limbek at valicon.net Fri Mar 9 09:34:44 2012 From: marko.limbek at valicon.net (Marko Limbek) Date: Fri, 9 Mar 2012 09:34:44 +0100 Subject: [Tutor] Question about writing to Excel with slavic characters In-Reply-To: References: <4F54B58A.7020402@compuscan.co.za> <1330975245.71342.YahooMailNeo@web110714.mail.gq1.yahoo.com> <4F57E2FF.1020000@pearwood.info> Message-ID: Hi Walter I understand, thank you. Maybe I am trying to do what is not meant to be done. I tried as you suggested mySavReaderObject = SavReader(savFileName) mySavReaderObject.getNumberofVariables(savFileName, mySavReaderObject.fh, mySavReaderObject.spssio) but it won't work File "C:\Dropbox\Exc_MarkoL_Zenel\Python\crosstabs\src\src\rw.py", line 715, in mySavReaderObject.getNumberofVariables(savFileName, mySavReaderObject.fh, mySavReaderObject.spssio) AttributeError: 'SavReader' object has no attribute 'spssio' So the methods must really be somewhat internal. The information that I get in numVars, nCases, varNames, varTypes, printTypesFile, printTypeLabels, varWids is not sufficient to me. What I need from this programme are the labels that are in the column 'Values' in SPSS 'Variable view'. What is the most important is that unicode characters like '?', '?', '?', in the labels can be read. This is the only reason why I am touching this programme. I will forward the question to Albert. Thank you, Marko On Thu, Mar 8, 2012 at 5:18 PM, Walter Prins wrote: > Hi Marko, > > I'm going out on a limb here as I know next to nothing about either > SPSS or Albert-Jan's wrapper module, and so with that caveat, some > comments/observations: > > On 8 March 2012 14:59, Marko Limbek wrote: >> I overcame commenting. I managed to read my own file and print it. Now >> I am trying to use method getNumberofVariables() ?but unsuccesfully. >> First way >> >> SavReader(savFileName).getNumberofVariables() >> >> gives me this error >> >> Traceback (most recent call last): >> ?File "C:\Dropbox\Exc_MarkoL_Zenel\Python\crosstabs\src\src\rw.py", >> line 660, in >> ? ?SavReader(savFileName).getNumberofVariables() >> TypeError: getNumberofVariables() takes exactly 3 arguments (1 given) >> >> >> >> Second way >> >> getNumberofVariables(savFileName, fh, spssio) >> >> gives me this error >> >> Traceback (most recent call last): >> ?File "C:\Dropbox\Exc_MarkoL_Zenel\Python\crosstabs\src\src\rw.py", >> line 660, in >> ? ?getNumberofVariables(savFileName, fh, spssio) >> NameError: name 'getNumberofVariables' is not defined > > The short answer: > ============== > Don't use getNumberofVariables, use the script as demonstrated at the > bottom of the script in the "if __name__ == "__main__" section. ?I > suppose something like this should do (I've modified it slightly to > make it a bit more obvious what's happening): > > ## ----- Get some basic file info > savFileName = r"C:\Program > Files\IBM\SPSS\Statistics\19\Samples\English\Employee data.sav" > mySavReaderObj = SavReader(savFileName) > numVars, nCases, varNames, varTypes, printTypesFile, printTypeLabels, > varWids = \ > ? ?mySavReaderObj.getSavFileInfo() > #Now the number of variables is presumably in numVars... > > > The longer answer: > ============== > Firstly, getNumberofVariables() is defined as a class instance method. > ?This means you can only ever call it on an object instance of that > class. It is not a standalone function that can be called freestanding > as you tried to do in your latter attempt. ?That is why you got the > "not defined" error -- There is no freestanding function by that name > (even if there happens to be a /method/ by that name inside the > SavReader class.) so Python complained as such. > > Your prior attempt, which as you noticed requires to have parameters > fh and spssio supplied appears to me to be effectively somewhat of an > internal/private/helper method that is written in the style of a > function, so consequently the method has no external dependencies on > any state in the object/class and hence has to have the spssio and fh > supplied when it's called. ?You can see elsewhere in the class when > this method is called, the object itself keeps track of the fh and the > sspsio and so passes these into the method as required. > > >From this you can infer that you'd be able to do the same and thus > successfully call getNumberofVariables() by retrieving the fh and > sspsio from your SavReader object (e.g. what I called mySavReaderObj > above), by passing in mySavReaderObj.fh and mySavREaderObj.spssio when > calling mySavReaderObj.getNumberofVariables(). ?But, as per the short > answer, you probably don't want to do that. > > As an aside it also then follows it would be possible to > rewrite/refactor the getNumberofVariables() method (and indeed several > others) to remove the fh and sspsio parameters, by having them picked > up directly from the object instance when required. ? Debateably, it > might be an improvement that makes the code a bit more object oriented > and less surprising to use. > > HTH, > > Walter > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Fri Mar 9 09:49:48 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 09 Mar 2012 08:49:48 +0000 Subject: [Tutor] Python using RXVT vs Konsole? In-Reply-To: References: Message-ID: On 09/03/12 02:07, brandon w wrote: > I am able to up-arrow to get the last typed command using rxvt but when I > use konsole and I press the up-arrow I get the symbols: ^[[A > Why is that? Your terminal settings look like they are messed up. Does up arrow work in any other applications? emacs or vim for example? If not you will need to configure your termcap/terminfo or stty settings I suspect. If it does work in other apps then I don't know what's happening! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From wprins at gmail.com Fri Mar 9 11:49:35 2012 From: wprins at gmail.com (Walter Prins) Date: Fri, 9 Mar 2012 10:49:35 +0000 Subject: [Tutor] Question about writing to Excel with slavic characters In-Reply-To: References: <4F54B58A.7020402@compuscan.co.za> <1330975245.71342.YahooMailNeo@web110714.mail.gq1.yahoo.com> <4F57E2FF.1020000@pearwood.info> Message-ID: Hi Marko, On 9 March 2012 08:34, Marko Limbek wrote: > ?File "C:\Dropbox\Exc_MarkoL_Zenel\Python\crosstabs\src\src\rw.py", > line 715, in > ? ?mySavReaderObject.getNumberofVariables(savFileName, > mySavReaderObject.fh, mySavReaderObject.spssio) > AttributeError: 'SavReader' object has no attribute 'spssio' > > So the methods must really be somewhat internal. Python doesn't enforce access levels like some other languages do which means effectively, any member of any object can in principle be accessed. By "gentlemans agreement", members with a name starting with a single underscore are supposed to be considered private (although you can still ignore this agreement and access them anyway) while members with double underscores get some behind the scenes assistance to ensure privateness and name uniqueness via "name mangling". (There's a couple of other minor behavioural differences, but the point stands -- there's no preventing you as programmer from accessing "private" members of a class if you insist to do so. But then it's doubly your problem if that gets you into trouble ;) ) Anyway, the message then really means what it says -- The SavReader object instance you're using really does not have an spssio member (there should be no problem accessing it if it was there so I must interpret that message to mean what it says.) I'm not sure why this would be the case -- perhaps we're not looking/using the same version of the reader class and the member name has changed? (I previously guessed/assumed that you were using the following version, or something close enough to it, given here: http://code.activestate.com/recipes/577650-python-reader-for-spss-sav-files/ Looking back I see you're actually using a slightly newer version from here: http://code.activestate.com/recipes/577811-python-reader-writer-for-spss-sav-files-linux-mac-/ But, everything I've said appears to still hold true about the updated version, so can you clarify which version you're currently using?) Regardless, the error simple enough to troubleshoot -- have a look at *your* version of the SavReader class, and find out what the member name should in fact be. There are calls to e.g. getNumberofVariables() in the class itself, from which you can determine what the object data/field/variable member is that holds the value to pass to the spssio parameter of getNumberofVariables(). But, I have to repeat: The value that you get from getNumberofVariables() is the exact same value that you get inside of the numVars variable after calling: numVars, nCases, varNames, varTypes, printTypesFile, printTypeLabels, varWids = mySavReaderObj.getSavFileInfo() You can see this will be the case if you read the code: 1) The __init__ method assigns self.numVars_ from the result of calling self._readBasicSavFileInfo(). 2) This in turn calls on self.getNumberofVariables() as follows: numVars = self.getNumberofVariables(self.fh, self.spssio)[1] ... and that local variable numVars is what is returned and ends up in the object member self.numVars_. 3) Then, looking at getSavFileInfo() you can see that it in turn simply returns self.numVars_, 4) In other words it returns the same value that it previously retrieved using self.getNumberofVariables(). So, the 2 ways are functionally identical w.r.t. the retrieval of the "NumberofVariables". The only differences are that a) with the latter call you get a bunch of other stuff besides the number of variables, and b) With the latter call you don't have to worry about spssio or fh parameters (because they're absent/not required when calling getSavFileInfo() and c) with the latter call the actual retrieval of the number of variables happened slightly earlier on when the SavReader object was created, while with the direct call to getNumberofVariables() it is presumably read again directly from the file. So, I think you need to stop fixating on the getNumberofVariables() method as it's not, I suspect, the solution to your real problem like you seem to think, and it is also introducing a distraction (the parameters issue) since it's not really the intended way for you to use this class. (Not that you absolutely cannot use it if you're determined to do so, as I've already tried to explain, but it's just probably just easier to go with the intended means of use for now given that there's functionally no difference in the result up to this point, at least that I can see.) Walter From marko.limbek at valicon.net Fri Mar 9 13:36:24 2012 From: marko.limbek at valicon.net (Marko Limbek) Date: Fri, 9 Mar 2012 13:36:24 +0100 Subject: [Tutor] Question about writing to Excel with slavic characters In-Reply-To: References: <4F54B58A.7020402@compuscan.co.za> <1330975245.71342.YahooMailNeo@web110714.mail.gq1.yahoo.com> <4F57E2FF.1020000@pearwood.info> Message-ID: Hi Walter It is as you say. Thanks for long explanation. I am using the newer version. Now I also understand difference between single underscore and double underscore. I would still have problems if I would want to programme them for instance. Well I always try to be independent and I want to answer the questions by myself. Learning the tutorial by heart is also not my way. Maybe I need just to understand it better and understand better the whole philosophy of private and public methods. And what is __init__ method and __enter__ method and so on. I was just asking of that getNumberofVariables() method, because I wanted to run the methods my self and see if I get the labels I wanted by myself. I wouldn't want to ask the author directly does this programme does this or that because that might be silly questions because the answer would be, 'well of course it does, run this and this method' and you will see. I don't want to consume too much time of the people. So I wanted to check first. As an amateur as I am. Nobody really trained me how to programme except for in the first years at the faculty some 10 years ago, but at that time I was not that interested in programming. Now we are resolving the issue directly with Albert. Have a nice day, Marko On Fri, Mar 9, 2012 at 11:49 AM, Walter Prins wrote: > Hi Marko, > > On 9 March 2012 08:34, Marko Limbek wrote: >> ?File "C:\Dropbox\Exc_MarkoL_Zenel\Python\crosstabs\src\src\rw.py", >> line 715, in >> ? ?mySavReaderObject.getNumberofVariables(savFileName, >> mySavReaderObject.fh, mySavReaderObject.spssio) >> AttributeError: 'SavReader' object has no attribute 'spssio' >> >> So the methods must really be somewhat internal. > > Python doesn't enforce access levels like some other languages do > which means effectively, any member of any object can in principle be > accessed. ?By "gentlemans agreement", members with a name starting > with a single underscore are supposed to be considered private > (although you can still ignore this agreement and access them anyway) > while members with double underscores get some behind the scenes > assistance to ensure privateness and name uniqueness via "name > mangling". ?(There's a couple of other minor behavioural differences, > but the point stands -- there's no preventing you as programmer from > accessing "private" members of a class if you insist to do so. ?But > then it's doubly your problem if that gets you into trouble ;) ) > > Anyway, the message then really means what it says -- The SavReader > object instance you're using really does not have an spssio member > (there should be no problem accessing it if it was there so I must > interpret that message to mean what it says.) ? I'm not sure why this > would be the case -- perhaps we're not looking/using the same version > of the reader class and the member name has changed? ?(I previously > guessed/assumed ?that you were using the following version, or > something close enough to it, given here: > http://code.activestate.com/recipes/577650-python-reader-for-spss-sav-files/ > ?Looking back I see you're actually using a slightly newer version > from here: http://code.activestate.com/recipes/577811-python-reader-writer-for-spss-sav-files-linux-mac-/ > But, everything I've said appears to still hold true about the updated > version, so can you clarify which version you're currently using?) > > Regardless, the error simple enough to troubleshoot -- have a look at > *your* version of the SavReader class, and find out what the member > name should in fact be. ?There are calls to e.g. > getNumberofVariables() in the class itself, from which you can > determine what the object data/field/variable member is that holds the > value to pass to the spssio parameter of getNumberofVariables(). > > But, I have to repeat: The value that you get from > getNumberofVariables() is the exact same value that you get inside of > the numVars variable after calling: > > ?numVars, nCases, varNames, varTypes, printTypesFile, > printTypeLabels, varWids = mySavReaderObj.getSavFileInfo() > > You can see this will be the case if you read the code: > 1) The __init__ method assigns self.numVars_ from the result of > calling self._readBasicSavFileInfo(). > 2) This in turn calls on self.getNumberofVariables() as follows: > ?numVars = self.getNumberofVariables(self.fh, self.spssio)[1] > ... and that local variable numVars is what is returned and ends up in > the object member self.numVars_. > 3) Then, looking at getSavFileInfo() you can see that it in turn > simply returns self.numVars_, > 4) In other words it returns the same value that it previously > retrieved using self.getNumberofVariables(). > > So, the 2 ways are functionally identical w.r.t. the retrieval of the > "NumberofVariables". ?The only differences are that a) with the latter > call you get a bunch of other stuff besides the number of variables, > and b) With the latter call you don't have to worry about spssio or fh > parameters (because they're absent/not required when calling > getSavFileInfo() and c) with the latter call the actual retrieval of > the number of variables happened slightly earlier on when the > SavReader object was created, while with the direct call to > getNumberofVariables() it is presumably read again directly from the > file. > > So, I think you need to stop fixating on the getNumberofVariables() > method as it's not, I suspect, the solution to your real problem like > you seem to think, and it is also introducing a distraction (the > parameters issue) since it's not really the intended way for you to > use this class. ?(Not that you absolutely cannot use it if you're > determined to do so, as I've already tried to explain, but it's just > probably just easier to go with the intended means of use for now > given that there's functionally no difference in the result up to this > point, at least that I can see.) > > Walter > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From sulinet at postafiok.hu Fri Mar 9 14:09:23 2012 From: sulinet at postafiok.hu (=?ISO-8859-1?Q?V=E1las_P=E9ter?=) Date: Fri, 9 Mar 2012 14:09:23 +0100 Subject: [Tutor] Floating point error in tkinter Message-ID: Hi, I use a tkinter-based editor that ran properly earlier on English Windows XP. Now I use Hungarian Windows 7 with Python 2.7.2. You must know that in Hungary decimal fractions are marked with a decimal comma, not a dot (e.g. pi=3,1415...). I suspect it somehow gets a Hungarian decimal from Windows and can't understand it. So when I page up and down with PgUp/PgDn buttons, it works well. When I use the wheel on mouse, it's OK, too. But when I try to use the vertical scrollbar of the window with mouse, error messages flood my screen and it won't work. Dou you think this is a Python bug? Shall I make a bugreport or just some config setting is missing? Exception in Tkinter callback Traceback (most recent call last): File "c:\python27\lib\lib-tk\Tkinter.py", line 1410, in __call__ return self.func(*args) File "c:\python27\lib\lib-tk\Tkinter.py", line 1444, in yview res = self.tk.call(self._w, 'yview', *args) TclError: expected floating-point number but got "0,0016" Exception in Tkinter callback Traceback (most recent call last): File "c:\python27\lib\lib-tk\Tkinter.py", line 1410, in __call__ return self.func(*args) File "c:\python27\lib\lib-tk\Tkinter.py", line 1444, in yview res = self.tk.call(self._w, 'yview', *args) TclError: expected floating-point number but got "0,0033" Exception in Tkinter callback Traceback (most recent call last): File "c:\python27\lib\lib-tk\Tkinter.py", line 1410, in __call__ return self.func(*args) File "c:\python27\lib\lib-tk\Tkinter.py", line 1444, in yview res = self.tk.call(self._w, 'yview', *args) TclError: expected floating-point number but got "0,0049" Exception in Tkinter callback Traceback (most recent call last): File "c:\python27\lib\lib-tk\Tkinter.py", line 1410, in __call__ return self.func(*args) File "c:\python27\lib\lib-tk\Tkinter.py", line 1444, in yview res = self.tk.call(self._w, 'yview', *args) TclError: expected floating-point number but got "0,0066" Exception in Tkinter callback Traceback (most recent call last): File "c:\python27\lib\lib-tk\Tkinter.py", line 1410, in __call__ return self.func(*args) File "c:\python27\lib\lib-tk\Tkinter.py", line 1444, in yview res = self.tk.call(self._w, 'yview', *args) TclError: expected floating-point number but got "0,0082" Exception in Tkinter callback Traceback (most recent call last): File "c:\python27\lib\lib-tk\Tkinter.py", line 1410, in __call__ return self.func(*args) File "c:\python27\lib\lib-tk\Tkinter.py", line 1444, in yview res = self.tk.call(self._w, 'yview', *args) TclError: expected floating-point number but got "0,0098" Exception in Tkinter callback Traceback (most recent call last): File "c:\python27\lib\lib-tk\Tkinter.py", line 1410, in __call__ return self.func(*args) File "c:\python27\lib\lib-tk\Tkinter.py", line 1444, in yview res = self.tk.call(self._w, 'yview', *args) TclError: expected floating-point number but got "0,0098" -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Fri Mar 9 15:40:06 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 10 Mar 2012 01:40:06 +1100 Subject: [Tutor] Floating point error in tkinter In-Reply-To: References: Message-ID: <20120309143940.GC30395@ando> On Fri, Mar 09, 2012 at 02:09:23PM +0100, V?las P?ter wrote: > Hi, > > I use a tkinter-based editor that ran properly earlier on English Windows > XP. Now I use Hungarian Windows 7 with Python 2.7.2. You must know that in > Hungary decimal fractions are marked with a decimal comma, not a dot (e.g. > pi=3,1415...). > > I suspect it somehow gets a Hungarian decimal from Windows and can't > understand it. So when I page up and down with PgUp/PgDn buttons, it works > well. When I use the wheel on mouse, it's OK, too. But when I try to use > the vertical scrollbar of the window with mouse, error messages flood my > screen and it won't work. Dou you think this is a Python bug? What makes you think it is a Python bug? Is there something that makes you expect that Tkinter should accept strings with commas instead of floats? The error message is pretty clear: tkinter is expecting a float, but receiving a string instead. TclError: expected floating-point number but got "0,0016" Unless there is documentation that says that it will accept strings with commas, this is not a Python bug. It may be a bug in the editor, but not in the Python language. By the way, it seems that a lot of other code has this same problem. You might find that running this: import locale locale.setlocale(locale.LC_ALL, 'english_us') just before the editor starts up might help: http://forums.arcgis.com/threads/27427-arcpy-and-easygui-eventloop-conflict -- Steven From alan.gauld at btinternet.com Fri Mar 9 20:28:03 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 09 Mar 2012 19:28:03 +0000 Subject: [Tutor] Floating point error in tkinter In-Reply-To: References: Message-ID: On 09/03/12 13:09, V?las P?ter wrote: > flood my screen and it won't work. Dou you think this is a Python bug? It's probably not a Python bug but a Tcl/Tk bug. It would be worth asking about it on a Tcl/Tk forum - or maybe even the Tkinter list. > File "c:\python27\lib\lib-tk\Tkinter.py", line 1444, in yview > res = self.tk.call(self._w, 'yview', *args) > TclError: expected floating-point number but got "0,0033" Note that this error comes from Tcl not Python. Tcl/Tk often evaluates strings as a float but may well be expecting a decimal period rather than a comma in the string. (It really just uses the float as an encoding for two integers!) Can you hard code the period in your code? Or trap the string and do a replace() to convert it before it calls the Tkinter code? On the other hand it could just be that it expects a literal float and not a string representation of the same... With no sight of the original Python code it's hard to say. But Tk uses string floats often enough that I suspect that it is a Tcl/Tk issue. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From mjolewis at gmail.com Sat Mar 10 08:20:40 2012 From: mjolewis at gmail.com (mjolewis at gmail.com) Date: Fri, 9 Mar 2012 23:20:40 -0800 Subject: [Tutor] getattr help Message-ID: What is the purpose of getattr? Why not just use help or am I completely misunderstanding this? From what I read, getattr allows you to get a reference to a function without knowing its name until runtime. However, the example provided is: li = ['larry', 'curly] getattr(li, 'pop') It seems to me that I need to know the name of the function to use getattr? Please help. Sent from my iPhone From __peter__ at web.de Sat Mar 10 10:05:36 2012 From: __peter__ at web.de (Peter Otten) Date: Sat, 10 Mar 2012 10:05:36 +0100 Subject: [Tutor] getattr help References: Message-ID: mjolewis at gmail.com wrote: > What is the purpose of getattr? Why not just use help or am I completely > misunderstanding this? > >>From what I read, getattr allows you to get a reference to a function >>without knowing its name until runtime. > > However, the example provided is: > > li = ['larry', 'curly] > getattr(li, 'pop') > > It seems to me that I need to know the name of the function to use > getattr? The name need not be known *until* *runtime*. You can pass it as a variable which makes the program more flexible. Here is an example: $ cat getattrdemo.py class Joe: def run(self): print("running") def jump(self): print("jumping") def say_hello(self): print("Hello, I am Joe") class Sue: def say_hello(elf): print("Hello, I am Sue") def swim(self): print("swimming") for person in [Joe(), Sue()]: person.say_hello() actions = [action for action in dir(person) if not action.startswith("_")] print("I can", ", ".join(actions)) while True: action = input("What do you want me to do? ") if action == "": print("bye") break if action in actions: getattr(person, action)() else: print("I'm afraid I can't", action) The code in the for loop does not "know" what joe or sue can do, it detects it at runtime. Therefore you don't have to change it when you add another person (as long as it can .say_hello()). And here's what you may see when you run the script: $ python3 getattrdemo.py Hello, I am Joe I can jump, run, say_hello What do you want me to do? jump jumping What do you want me to do? run running What do you want me to do? swim I'm afraid I can't swim What do you want me to do? bye Hello, I am Sue I can say_hello, swim What do you want me to do? say_hello Hello, I am Sue What do you want me to do? talk I'm afraid I can't talk What do you want me to do? swim swimming What do you want me to do? bye $ If you want to see a more advanced example of the technique, have a look at cmd.py in Python's standard library. From bbbgggwww at gmail.com Sat Mar 10 16:22:01 2012 From: bbbgggwww at gmail.com (brandon w) Date: Sat, 10 Mar 2012 10:22:01 -0500 Subject: [Tutor] Python using RXVT vs Konsole? In-Reply-To: References: Message-ID: Up arrow does work in other applications. The only application that it does not work in is konsole. I actually do not care for konsole that much. I think I will just use some other terminal. I found this on the Internet: The interpreter's line-editing features usually aren't very sophisticated. On Unix, whoever installed the interpreter may have enabled support for the GNU readline library, which adds more elaborate interactive editing and history features. Perhaps the quickest check to see whether command line editing is supported is typing *Control-P*, or the *up-arrow* to the first Python prompt you get. If it beeps, you have command line editing; see Appendix A for an introduction to the keys. If nothing appears to happen, or if P is echoed, command line editing isn't available; you'll only be able to use backspace to remove characters from the current line. http://pytut.infogami.com/node4.html konsole somehow disabled command line editing. On Fri, Mar 9, 2012 at 3:49 AM, Alan Gauld wrote: > On 09/03/12 02:07, brandon w wrote: > > I am able to up-arrow to get the last typed command using rxvt but when I >> use konsole and I press the up-arrow I get the symbols: ^[[A >> Why is that? >> > > Your terminal settings look like they are messed up. > Does up arrow work in any other applications? > emacs or vim for example? > > If not you will need to configure your termcap/terminfo or stty settings I > suspect. > > If it does work in other apps then I don't know what's happening! > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sulinet at postafiok.hu Sat Mar 10 20:40:54 2012 From: sulinet at postafiok.hu (=?ISO-8859-1?Q?V=E1las_P=E9ter?=) Date: Sat, 10 Mar 2012 20:40:54 +0100 Subject: [Tutor] Floating point error in tkinter In-Reply-To: References: <20120309143940.GC30395@ando> Message-ID: Sorry for sending it in private first, Steven drew my attention to it. This list has a strange setting, I got used to lists that send replies automatically to list, and did not notice the error. 2012. m?rcius 9. 18:53 V?las P?ter ?rta, : > 2012/3/9 Steven D'Aprano > >> >> What makes you think it is a Python bug? Is there something that makes >> you expect that Tkinter should accept strings with commas instead of >> floats? >> > Better to say: I think it is a Tkinter bug (unless we expect Windows to > adapt itself to Python), and Tkinter is part of the Python dstribution > AFAIK. As you may see, Tkinter is the only module to appear in the error > message. We may say it is a Windows bug, but this is the case of the > elephant and the mouse. :-) > > >> The error message is pretty clear: tkinter is expecting a float, but >> receiving a string instead. >> > No; it receives a float formatted by Hungarian standards as set in control > panel of Windows, and does not recognize it as a float. > > >> >> import locale >> locale.setlocale(locale.LC_ALL, 'english_us') >> > That's what I definitely wouldn't like to do, because I *do need*Hungarian locale very much for everything else. Too big a price. > > VP > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.sjoblom at gmail.com Sun Mar 11 00:38:04 2012 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Sun, 11 Mar 2012 00:38:04 +0100 Subject: [Tutor] UnicodeEncodeError: 'cp932' codec can't encode character '\xe9' in position Message-ID: Okay, so here's a fun one. Since I'm on a japanese locale my native encoding is cp932. I was thinking of writing a parser for a bunch of text files, but I stumbled on even printing the contents due to ... something. I don't know what encoding the text file uses, which isn't helping my case either (I have asked, but I've yet to get an answer). Okay, so: address = "C:/Path/to/file/file.ext" with open(address, encoding="cp1252") as alpha: text = alpha.readlines() for line in text: print(line) It starts to print until it hits the wonderful character ? or '\xe9', where it gives me this happy traceback: Traceback (most recent call last): File "C:\Users\Azaz\Desktop\CK2 Map Painter\Parser\test parser.py", line 8, in print(line) UnicodeEncodeError: 'cp932' codec can't encode character '\xe9' in position 13: illegal multibyte sequence I can open the document and view it in UltraEdit -- and it displays correct characters there -- but UE can't give me what encoding it uses. Any chance of solving this without having to switch from my japanese locale? Also, the cp1252 is just an educated guess, but it doesn't really matter because it always comes back to the cp932 error. -- best regards, Robert S. From alan.gauld at btinternet.com Sun Mar 11 01:52:04 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 11 Mar 2012 00:52:04 +0000 Subject: [Tutor] Python using RXVT vs Konsole? In-Reply-To: References: Message-ID: On 10/03/12 15:22, brandon w wrote: > Up arrow does work in other applications. The only application that it > does not work in is konsole. Konsole is a shell, you run applications inside Konsole. Python is one such application. What I was asking was do the arrow keys work in other Konsole applications - like vim. (or emacs started with the -nw option) or pico... > I actually do not care for konsole that much. I think I will just use > some other terminal. That might be the simplest option! :-). -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sun Mar 11 01:58:18 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 11 Mar 2012 00:58:18 +0000 Subject: [Tutor] Floating point error in tkinter In-Reply-To: References: <20120309143940.GC30395@ando> Message-ID: On 10/03/12 19:40, V?las P?ter wrote: > Better to say: I think it is a Tkinter bug (unless we expect Windows > to adapt itself to Python), and Tkinter is part of the Python But it's really a Tcl bug because Tkinter is built on top of Tcl/Tk and (mostly) cannot fix bugs that exist in the underlying framework. > The error message is pretty clear: tkinter is expecting a float, but > receiving a string instead. > > No; it receives a float formatted by Hungarian standards as set in > control panel of Windows, and does not recognize it as a float. No, it is receiving a string - note the quotation marks. But Tcl is a strange language that interprets many variables as strings and, especially in Tk, it is common to pass numerical values as strings. (In early Tcl versions all variables were strings interpreted by Tcl at runtime, one of the most common complaints and a reason for its early lethargy. Nowadays Tcl uses native types like most other languages and is no longer sloth like... But some artifacts remain) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From d at davea.name Sun Mar 11 02:03:18 2012 From: d at davea.name (Dave Angel) Date: Sat, 10 Mar 2012 20:03:18 -0500 Subject: [Tutor] UnicodeEncodeError: 'cp932' codec can't encode character '\xe9' in position In-Reply-To: References: Message-ID: <4F5BF9D6.2050105@davea.name> On 03/10/2012 06:38 PM, Robert Sjoblom wrote: > Okay, so here's a fun one. Since I'm on a japanese locale my native > encoding is cp932. I was thinking of writing a parser for a bunch of > text files, but I stumbled on even printing the contents due to ... > something. I don't know what encoding the text file uses, which isn't > helping my case either (I have asked, but I've yet to get an answer). > > Okay, so: > > address = "C:/Path/to/file/file.ext" > with open(address, encoding="cp1252") as alpha: > text = alpha.readlines() > for line in text: > print(line) > > It starts to print until it hits the wonderful character ? or '\xe9', > where it gives me this happy traceback: > Traceback (most recent call last): > File "C:\Users\Azaz\Desktop\CK2 Map Painter\Parser\test parser.py", > line 8, in > print(line) > UnicodeEncodeError: 'cp932' codec can't encode character '\xe9' in > position 13: illegal multibyte sequence > > I can open the document and view it in UltraEdit -- and it displays > correct characters there -- but UE can't give me what encoding it > uses. Any chance of solving this without having to switch from my > japanese locale? Also, the cp1252 is just an educated guess, but it > doesn't really matter because it always comes back to the cp932 error. > There are just 256 possible characters in cp1252, and 256 in cp932. So you should expect to see this error if your input file is unconstrained. And since you don't know what encoding it's in, you might as well consider it unconstrained. In other words, there are possible characters in the cp1252 that just won't display in cp932. You can "solve" the problem by pretending the input file is also cp932 when you open it. That way you'll get the wrong characters, but no errors. Or you can solve it by encoding the output explicitly, telling it to ignore errors. I don't know how to do that in Python 3.x. Finally, you can change your console to be utf-8, and find a font that includes both sets of characters. -- DaveA From robert.sjoblom at gmail.com Sun Mar 11 02:31:56 2012 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Sun, 11 Mar 2012 02:31:56 +0100 Subject: [Tutor] UnicodeEncodeError: 'cp932' codec can't encode character '\xe9' in position In-Reply-To: <4F5BF9D6.2050105@davea.name> References: <4F5BF9D6.2050105@davea.name> Message-ID: > You can "solve" the problem by pretending the input file is also cp932 when > you open it. That way you'll get the wrong characters, but no errors. So I tried that: Traceback (most recent call last): File "C:\Users\Azaz\Desktop\CK2 Map Painter\Parser\test parser.py", line 6, in text = alpha.readlines() UnicodeDecodeError: 'cp932' codec can't decode bytes in position 1374-1375: illegal multibyte sequence >?Or > you can solve it by encoding the output explicitly, telling it to ignore > errors. ?I don't know how to do that in Python 3.x. Me neither. I will research this tomorrow. >?Finally, you can change > your console to be utf-8, and find a font that includes both sets of > characters. While that might be a tempting solution, it would be best if this worked without having to do any changes to the environment itself; it would be best if it could run on any platform, but I'll take a Windows machine with no changes to command line if I have to. -- best regards, Robert S. From steve at pearwood.info Sun Mar 11 10:38:09 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 11 Mar 2012 20:38:09 +1100 Subject: [Tutor] UnicodeEncodeError: 'cp932' codec can't encode character '\xe9' in position In-Reply-To: <4F5BF9D6.2050105@davea.name> References: <4F5BF9D6.2050105@davea.name> Message-ID: <20120311093808.GA27971@ando> On Sat, Mar 10, 2012 at 08:03:18PM -0500, Dave Angel wrote: > There are just 256 possible characters in cp1252, and 256 in cp932. CP932 is also known as MS-KANJI or SHIFT-JIS (actually, one of many variants of SHIFT-JS). It is a multi-byte encoding, which means it has far more than 256 characters. http://www.rikai.com/library/kanjitables/kanji_codes.sjis.shtml http://en.wikipedia.org/wiki/Shift_JIS The actual problem the OP has got is that the *multi-byte* sequence he is trying to print is illegal when interpreted as CP932. Personally I think that's a bug in the terminal, or possibly even print, since he's not printing bytes but characters, but I haven't given that a lot of thought so I might be way out of line. The quick and dirty fix is to change the encoding of his terminal, so that it no longer tries to interpret the characters printed using CP932. That will also mean he'll no longer see valid Japanese characters. But since he appears to be using Windows, I don't know if this is possible, or easy. [...] > You can "solve" the problem by pretending the input file is also cp932 > when you open it. That way you'll get the wrong characters, but no > errors. Not so -- there are multi-byte sequences that can't be read in CP932. >>> b"\xe9x".decode("cp932") # this one works '?' >>> b"\xe9!".decode("cp932") # this one doesn't Traceback (most recent call last): File "", line 1, in UnicodeDecodeError: 'cp932' codec can't decode bytes in position 0-1: illegal multibyte sequence In any case, the error doesn't occur when he reads the data, but when he prints it. Once the data is read, it is already Unicode text, so he should be able to print any character. At worst, it will print as a missing character (a square box or space) rather than the expected glyph. He shouldn't get a UnicodeDecodeError when printing. I smell a bug since print shouldn't be decoding anything. (At worst, it needs to *encode*.) -- Steven From __peter__ at web.de Sun Mar 11 11:21:37 2012 From: __peter__ at web.de (Peter Otten) Date: Sun, 11 Mar 2012 11:21:37 +0100 Subject: [Tutor] UnicodeEncodeError: 'cp932' codec can't encode character '\xe9' in position References: Message-ID: Robert Sjoblom wrote: > Okay, so here's a fun one. Since I'm on a japanese locale my native > encoding is cp932. I was thinking of writing a parser for a bunch of > text files, but I stumbled on even printing the contents due to ... > something. I don't know what encoding the text file uses, which isn't > helping my case either (I have asked, but I've yet to get an answer). > > Okay, so: > > address = "C:/Path/to/file/file.ext" > with open(address, encoding="cp1252") as alpha: Superfluous readlines() alert: > text = alpha.readlines() > for line in text: > print(line) You can iterate over the file directly with #python3 for line in alpha: print(line, end="") or even sys.stdout.writelines(alpha) > It starts to print until it hits the wonderful character ? or '\xe9', > where it gives me this happy traceback: > Traceback (most recent call last): > File "C:\Users\Azaz\Desktop\CK2 Map Painter\Parser\test parser.py", > line 8, in > print(line) > UnicodeEncodeError: 'cp932' codec can't encode character '\xe9' in > position 13: illegal multibyte sequence > > I can open the document and view it in UltraEdit -- and it displays > correct characters there -- but UE can't give me what encoding it > uses. Any chance of solving this without having to switch from my > japanese locale? Also, the cp1252 is just an educated guess, but it > doesn't really matter because it always comes back to the cp932 error. # python3 output_encoding = sys.stdout.encoding or "UTF-8" error_handling = "replace" Writer = codecs.getwriter(output_encoding) outstream = Writer(sys.stdout.buffer, error_handling) with open(filename, "r", encoding="cp1252") as instream: for line in instream: print(line, end="", file=outstream) error_handling = "replace" prints "?" for characters that cannot be displayed in the target encoding. From __peter__ at web.de Sun Mar 11 11:37:04 2012 From: __peter__ at web.de (Peter Otten) Date: Sun, 11 Mar 2012 11:37:04 +0100 Subject: [Tutor] UnicodeEncodeError: 'cp932' codec can't encode character '\xe9' in position References: <4F5BF9D6.2050105@davea.name> <20120311093808.GA27971@ando> Message-ID: Steven D'Aprano wrote: > glyph. He shouldn't get a UnicodeDecodeError when printing. I smell a > bug since print shouldn't be decoding anything. (At worst, it needs to > *encode*.) You have correctly derived the actual traceback ;) [Robert] > It starts to print until it hits the wonderful character ? or '\xe9', > where it gives me this happy traceback: > Traceback (most recent call last): > File "C:\Users\Azaz\Desktop\CK2 Map Painter\Parser\test parser.py", > line 8, in > print(line) > UnicodeEncodeError: 'cp932' codec can't encode character '\xe9' in > position 13: illegal multibyte sequence In nuce: $ PYTHONIOENCODING=cp932 python3 -c 'print("\xe9")' Traceback (most recent call last): File "", line 1, in UnicodeEncodeError: 'cp932' codec can't encode character '\xe9' in position 0: illegal multibyte sequence (I have to lie about the encoding; my terminal speaks UTF-8) From robert.sjoblom at gmail.com Mon Mar 12 02:56:36 2012 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Mon, 12 Mar 2012 02:56:36 +0100 Subject: [Tutor] Finding a specific line in a body of text Message-ID: I'm sorry if the subject is vague, but I can't really explain it very well. I've been away from programming for a while now (I got a daughter and a year after that a son, so I've been busy with family matters). As such, my skills are definitely rusty. In the file I'm parsing, I'm looking for specific lines. I don't know the content of these lines but I do know the content that appears two lines before. As such I thought that maybe I'd flag for a found line and then flag the next two lines as well, like so: if keyword in line: flag = 1 continue if flag == 1 or flag == 2: if flag == 1: flag = 2 continue if flag == 2: list.append(line) This, however, turned out to be unacceptably slow; this file is 1.1M lines, and it takes roughly a minute to go through. I have 450 of these files; I don't have the luxury to let it run for 8 hours. So I thought that maybe I could use enumerate() somehow, get the index when I hit keyword and just append the line at index+2; but I realize I don't know how to do that. File objects doesn't have an index function. For those curious, the data I'm looking for looks like this: 5 72 88 77 90 92 18 80 75 98 84 90 81 12 58 76 77 94 96 There are other parts of the file that contains similar strings of digits, so I can't just grab any digits I come across either; the only thing I have to go on is the keyword. It's obvious that my initial idea was horribly bad (and I knew that as well, but I wanted to first make sure that I could find what I was after properly). The structure looks like this (I opted to use \t instead of relying on the tabs to getting formatted properly in the email): \t\tkeyword= \t\t{ 5 72 88 77 90 92 \t\t} -- best regards, Robert S. From mjolewis at gmail.com Mon Mar 12 03:02:11 2012 From: mjolewis at gmail.com (Michael Lewis) Date: Sun, 11 Mar 2012 19:02:11 -0700 Subject: [Tutor] question on self Message-ID: Why do I have to use "self.example" when calling a method inside a class? For example: def Play(self): '''find scores, reports winners''' self.scores = [] for player in range(self.players): print print 'Player', player + 1 self.scores.append(self.TakeTurns()) I have another method called take turns (not shown for brevity purposes). When I want to call it, why can't I just call it like a function and use TakeTurns() instead of self.TakeTurns()? -- Michael J. Lewis -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Mon Mar 12 04:03:55 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 12 Mar 2012 14:03:55 +1100 Subject: [Tutor] question on self In-Reply-To: References: Message-ID: <20120312030354.GC27971@ando> On Sun, Mar 11, 2012 at 07:02:11PM -0700, Michael Lewis wrote: > Why do I have to use "self.example" when calling a method inside a class? > > For example: > > def Play(self): > '''find scores, reports winners''' > self.scores = [] > for player in range(self.players): > print > print 'Player', player + 1 > self.scores.append(self.TakeTurns()) > > I have another method called take turns (not shown for brevity purposes). > When I want to call it, why can't I just call it like a function and use > TakeTurns() instead of self.TakeTurns()? When you call range() inside a method, as you do above, do you expect to get the global range() function, or the self.range() method (which likely doesn't exist)? Same for len(), or any other built-in or global. Similarly, how do you expect Python to distinguish between a persistent attribute, like self.scores, and a local variable, like player? Since Python can't read your mind, one way or another you have to explicitly tell the compiler which of the two name resolution orders to use: (1) The normal function scope rules: - local variables have priority over: - non-locals, which have priority over: - globals, which have priority over: - built-ins; (2) or the attribute search rules, which is quite compilicated but a simplified version is: - instance attributes or methods - class attributes or methods - superclass attributes or method - computed attributes or methods using __getattr__ Python refuses to guess which one you want, since any guess is likely to be wrong 50% of the time. Instead, Python's design is to always use function scope rules, and if you want attributes or methods, you have to explicitly ask for them. This makes MUCH more sense than having to explicitly flag local variables! Other languages made other choices. For instance, you might demand that the programmer declare all their variables up-front, and all their instance attributes. Then the compiler can tell at compile-time that range is a built-in, that player is a local variable, and that TakeTurns is an instance attribute. That's a legitimate choice, and some languages do it that way. But having programmed in some of these other languages, give me Python's lack of declarations anytime! Since all names (variables and attributes) in Python are generated at runtime, the compiler normally cannot tell what the scope of a name is until runtime (with a few exceptions). -- Steven From steve at pearwood.info Mon Mar 12 04:28:07 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 12 Mar 2012 14:28:07 +1100 Subject: [Tutor] Finding a specific line in a body of text In-Reply-To: References: Message-ID: <20120312032807.GD27971@ando> On Mon, Mar 12, 2012 at 02:56:36AM +0100, Robert Sjoblom wrote: > In the file I'm parsing, I'm looking for specific lines. I don't know > the content of these lines but I do know the content that appears two > lines before. As such I thought that maybe I'd flag for a found line > and then flag the next two lines as well, like so: > > if keyword in line: > flag = 1 > continue > if flag == 1 or flag == 2: > if flag == 1: > flag = 2 > continue > if flag == 2: > list.append(line) You haven't shown us the critical part: how are you getting the lines in the first place? (Also, you shouldn't shadow built-ins like list as you do above, unless you know what you are doing. If you have to ask "what's shadowing?", you don't :) > This, however, turned out to be unacceptably slow; this file is 1.1M > lines, and it takes roughly a minute to go through. I have 450 of > these files; I don't have the luxury to let it run for 8 hours. Really? And how many hours have you spent trying to speed this up? Two? Three? Seven? And if it takes people two or three hours to answer your question, and you another two or three hours to read it, it would have been faster to just run the code as given :) I'm just saying. Since you don't show the actual critical part of the code, I'm going to make some simple suggestions that you may or may not have already tried. - don't read files off USB or CD or over the network, because it will likely be slow; if you can copy the files onto the local hard drive, performance may be better; - but if you include the copying time, it might not make that much difference; - can you use a dedicated tool for this, like Unix grep or even perl, which is optimised for high-speed file manipulations? - if you need to stick with Python, try this: # untested results = [] fp = open('filename') for line in fp: if key in line: # Found key, skip the next line and save the following. _ = next(fp, '') results.append(next(fp, '')) By the way, the above assumes you are running Python 2.6 or better. In Python 2.5, you can define this function: def next(iterator, default): try: return iterator.next() except StopIteration: return default but it will likely be a little slower. Another approach may be to read the whole file into memory in one big chunk. 1.1 million lines, by (say) 50 characters per line comes to about 53 MB per file, which should be small enough to read into memory and process it in one chunk. Something like this: # again untested text = open('filename').read() results = [] i = 0 while i < len(text): offset = text.find(key, i) if i == -1: break i += len(key) # skip the rest of the key # read ahead to the next newline, twice i = text.find('\n', i) i = text.find('\n', i) # now find the following newline, and save everything up to that p = text.find('\n', i) if p == -1: p = len(text) results.append(text[i:p]) i = p # skip ahead This will likely break if the key is found without two more lines following it. -- Steven From steve at alchemy.com Mon Mar 12 04:14:37 2012 From: steve at alchemy.com (Steve Willoughby) Date: Sun, 11 Mar 2012 20:14:37 -0700 Subject: [Tutor] question on self In-Reply-To: <20120312030354.GC27971@ando> References: <20120312030354.GC27971@ando> Message-ID: <4F5D6A1D.3010305@alchemy.com> On 11-Mar-12 20:03, Steven D'Aprano wrote: > On Sun, Mar 11, 2012 at 07:02:11PM -0700, Michael Lewis wrote: >> Why do I have to use "self.example" when calling a method inside a class? >> >> For example: >> >> def Play(self): >> '''find scores, reports winners''' >> self.scores = [] >> for player in range(self.players): >> print >> print 'Player', player + 1 >> self.scores.append(self.TakeTurns()) >> >> I have another method called take turns (not shown for brevity purposes). >> When I want to call it, why can't I just call it like a function and use >> TakeTurns() instead of self.TakeTurns()? Steven's notes about scoping rules are one reason. Another is the matter of object instance binding. When you call a method, you're not just calling a regular function. You're calling a function bound to a particular object, so by saying self.TakeTurns(), Python knows that the object "self" is invoking that method, not some other instance of the Play class. That method then can access all of that specific object's attributes as necessary. -- Steve Willoughby / steve at alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C From robert.sjoblom at gmail.com Mon Mar 12 05:46:39 2012 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Mon, 12 Mar 2012 05:46:39 +0100 Subject: [Tutor] Finding a specific line in a body of text In-Reply-To: <20120312032807.GD27971@ando> References: <20120312032807.GD27971@ando> Message-ID: > You haven't shown us the critical part: how are you getting the lines in > the first place? Ah, yes -- with open(address, "r", encoding="cp1252") as instream: for line in instream: > (Also, you shouldn't shadow built-ins like list as you do above, unless > you know what you are doing. If you have to ask "what's shadowing?", you > don't :) Maybe I should have said list_name.append() instead; sorry for that. >> This, however, turned out to be unacceptably slow; this file is 1.1M >> lines, and it takes roughly a minute to go through. I have 450 of >> these files; I don't have the luxury to let it run for 8 hours. > > Really? And how many hours have you spent trying to speed this up? Two? > Three? Seven? And if it takes people two or three hours to answer your > question, and you another two or three hours to read it, it would have > been faster to just run the code as given :) Yes, for one set of files. Since I don't know how many sets of ~450 files I'll have to run this over, I think that asking for help was a rather acceptable loss of time. I work on other parts while waiting anyway, or try and find out on my own as well. > - if you need to stick with Python, try this: > > # untested > results = [] > fp = open('filename') > for line in fp: > ? ?if key in line: > ? ? ? ?# Found key, skip the next line and save the following. > ? ? ? ?_ = next(fp, '') > ? ? ? ?results.append(next(fp, '')) Well that's certainly faster, but not fast enough. Oh well, I'll continue looking for a solution -- because even with the speedup it's unacceptable. I'm hoping against hope that I only have to run it against the last file of each batch of files, but if it turns out that I don't, I'm in for some exciting days of finding stuff out. Thanks for all the help though, it's much appreciated! How do you approach something like this, when someone tells you "we need you to parse these files. We can't tell you how they're structured so you'll have to figure that out yourself."? It's just so much text that's it's hard to get a grasp on the structure, and there's so much information contained in there as well; this is just the first part of what I'm afraid will be many. I'll try not to bother this list too much though. -- best regards, Robert S. From ian.douglas at iandouglas.com Mon Mar 12 06:07:19 2012 From: ian.douglas at iandouglas.com (ian douglas) Date: Sun, 11 Mar 2012 22:07:19 -0700 Subject: [Tutor] Finding a specific line in a body of text In-Reply-To: References: <20120312032807.GD27971@ando> Message-ID: Erik Rise gave a good talk today at PyCon about a parsing library he's working on called Parsimonious. You could maybe look into what he's doing there, and see if that helps you any... Follow him on Twitter at @erikrose to see when his session's video is up. His session was named "Parsing Horrible Things in Python" On Mar 11, 2012 9:48 PM, "Robert Sjoblom" wrote: > > You haven't shown us the critical part: how are you getting the lines in > > the first place? > > Ah, yes -- > with open(address, "r", encoding="cp1252") as instream: > for line in instream: > > > (Also, you shouldn't shadow built-ins like list as you do above, unless > > you know what you are doing. If you have to ask "what's shadowing?", you > > don't :) > Maybe I should have said list_name.append() instead; sorry for that. > > >> This, however, turned out to be unacceptably slow; this file is 1.1M > >> lines, and it takes roughly a minute to go through. I have 450 of > >> these files; I don't have the luxury to let it run for 8 hours. > > > > Really? And how many hours have you spent trying to speed this up? Two? > > Three? Seven? And if it takes people two or three hours to answer your > > question, and you another two or three hours to read it, it would have > > been faster to just run the code as given :) > Yes, for one set of files. Since I don't know how many sets of ~450 > files I'll have to run this over, I think that asking for help was a > rather acceptable loss of time. I work on other parts while waiting > anyway, or try and find out on my own as well. > > > - if you need to stick with Python, try this: > > > > # untested > > results = [] > > fp = open('filename') > > for line in fp: > > if key in line: > > # Found key, skip the next line and save the following. > > _ = next(fp, '') > > results.append(next(fp, '')) > > Well that's certainly faster, but not fast enough. > Oh well, I'll continue looking for a solution -- because even with the > speedup it's unacceptable. I'm hoping against hope that I only have to > run it against the last file of each batch of files, but if it turns > out that I don't, I'm in for some exciting days of finding stuff out. > Thanks for all the help though, it's much appreciated! > > How do you approach something like this, when someone tells you "we > need you to parse these files. We can't tell you how they're > structured so you'll have to figure that out yourself."? It's just so > much text that's it's hard to get a grasp on the structure, and > there's so much information contained in there as well; this is just > the first part of what I'm afraid will be many. I'll try not to bother > this list too much though. > -- > best regards, > Robert S. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Mon Mar 12 06:10:25 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 12 Mar 2012 16:10:25 +1100 Subject: [Tutor] Finding a specific line in a body of text In-Reply-To: References: <20120312032807.GD27971@ando> Message-ID: <20120312051025.GE27971@ando> On Mon, Mar 12, 2012 at 05:46:39AM +0100, Robert Sjoblom wrote: > > You haven't shown us the critical part: how are you getting the lines in > > the first place? > > Ah, yes -- > with open(address, "r", encoding="cp1252") as instream: > for line in instream: Seems reasonable. > > (Also, you shouldn't shadow built-ins like list as you do above, unless > > you know what you are doing. If you have to ask "what's shadowing?", you > > don't :) > Maybe I should have said list_name.append() instead; sorry for that. No problems :) Shadowing builtins is fine if you know what you're doing, but it's the people who do it without realising that end up causing themselves trouble. > >> This, however, turned out to be unacceptably slow; this file is 1.1M > >> lines, and it takes roughly a minute to go through. I have 450 of > >> these files; I don't have the luxury to let it run for 8 hours. > > > > Really? And how many hours have you spent trying to speed this up? Two? > > Three? Seven? And if it takes people two or three hours to answer your > > question, and you another two or three hours to read it, it would have > > been faster to just run the code as given :) > Yes, for one set of files. Since I don't know how many sets of ~450 > files I'll have to run this over, I think that asking for help was a > rather acceptable loss of time. I work on other parts while waiting > anyway, or try and find out on my own as well. All very reasonable. So long as you have considered the alternatives. > > - if you need to stick with Python, try this: > > > > # untested > > results = [] > > fp = open('filename') > > for line in fp: > > ? ?if key in line: > > ? ? ? ?# Found key, skip the next line and save the following. > > ? ? ? ?_ = next(fp, '') > > ? ? ? ?results.append(next(fp, '')) > > Well that's certainly faster, but not fast enough. You may have to consider that your bottleneck is not the speed of your Python code, but the speed of getting data off the disk into memory. In which case, you may be stuck. I suggest you time how long it takes to process a file using the above, then compare it to how long just reading the file takes: from time import clock t = clock() for line in open('filename', encoding='cp1252'): pass print(clock() - t) Run both timings a couple of times and pick the smallest number, to minimise caching effects and other extraneous influences. Then do the same using a system tool. You're using Windows, right? I can't tell you how to do it in Windows, but on Linux I'd say: time cat 'filename' > /dev/null which should give me a rough-and-ready estimate of the raw speed of reading data off the disk. If this speed is not *significantly* better than you are getting in Python, then there simply isn't any feasible way to speed the code up appreciably. (Except maybe get faster hard drives or smaller files .) [...] > How do you approach something like this, when someone tells you "we > need you to parse these files. We can't tell you how they're > structured so you'll have to figure that out yourself."? Bitch and moan quietly to myself, and then smile when I realise I'm being paid by the hour. Reverse-engineering a file structure without any documentation is rarely simple or fast. -- Steven From alan.gauld at btinternet.com Mon Mar 12 09:49:58 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 12 Mar 2012 08:49:58 +0000 Subject: [Tutor] Finding a specific line in a body of text In-Reply-To: <20120312032807.GD27971@ando> References: <20120312032807.GD27971@ando> Message-ID: On 12/03/12 03:28, Steven D'Aprano wrote: > Another approach may be to read the whole file into memory in one big > chunk. 1.1 million lines, by (say) 50 characters per line comes to about > 53 MB per file, which should be small enough to read into memory and > process it in one chunk. Something like this: > > # again untested > text = open('filename').read() > results = [] > i = 0 > while i< len(text): > offset = text.find(key, i) > if i == -1: break > i += len(key) # skip the rest of the key > # read ahead to the next newline, twice > i = text.find('\n', i) > i = text.find('\n', i) > # now find the following newline, and save everything up to that > p = text.find('\n', i) > if p == -1: p = len(text) > results.append(text[i:p]) > i = p # skip ahead Or using readlines: index = 0 text = open('filename').readlines() while True: try: index = text.index(key,index) + 2 results.append(text[index]) except ValueError: break readlines will take slightly more memory. But I suspect a tool like grep will be faster. grep can be downloaded for windows. To use grep explore the -A option. Even using grep as a pre-filter to pipe into your program might work. But you may also have to accept that processing 450 large files will take some time! You can help by parallel processing up to the number of cores (less 1) in your PC, But other than that you may just need a faster computer! Either more RAM or a SSD drive will help greatly. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Mar 12 09:56:16 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 12 Mar 2012 08:56:16 +0000 Subject: [Tutor] question on self In-Reply-To: References: Message-ID: On 12/03/12 02:02, Michael Lewis wrote: > I have another method called take turns (not shown for brevity > purposes). When I want to call it, why can't I just call it like a > function and use TakeTurns() instead of self.TakeTurns()? The Steve's have given technical answers, its also stylistically better because it removed ambiguity for the reader as well as for Python. Many corporate style guides advocate using this same style when using C++ or Java to make it explicit when you are using a class attribute rather than a local or global value/function. It improves code clarity and therefore reduces potential bugs and speeds up maintenance for a tiny loss in initial coding productivity. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From emile at fenx.com Mon Mar 12 14:22:43 2012 From: emile at fenx.com (Emile van Sebille) Date: Mon, 12 Mar 2012 06:22:43 -0700 Subject: [Tutor] Finding a specific line in a body of text In-Reply-To: References: Message-ID: On 3/11/2012 6:56 PM Robert Sjoblom said... > I'm sorry if the subject is vague, but I can't really explain it very > well. I've been away from programming for a while now (I got a > daughter and a year after that a son, so I've been busy with family > matters). As such, my skills are definitely rusty. > > In the file I'm parsing, I'm looking for specific lines. I don't know > the content of these lines but I do know the content that appears two > lines before. As such I thought that maybe I'd flag for a found line > and then flag the next two lines as well, like so: > If, as others suggest, the files do fit in memory, you might try: content = open(thisfile).read() for fragment in content.split(keyword)[1:]: myresults.append(fragment.split('\n')[1] Emile From emeraldoffice at hotmail.com Tue Mar 13 00:25:32 2012 From: emeraldoffice at hotmail.com (Tamar Osher) Date: Mon, 12 Mar 2012 18:25:32 -0500 Subject: [Tutor] import pygame Message-ID: Hello. I cannot successfully import third party modules. I have tried various things and searched online. Pygame is installed on my Windows 7 computer at C:\python32\pygame. Can someone please help me?>>>import pygameTraceback (most recent call last): File "", line 1, in import pygameImportError: No module named pygame -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Tue Mar 13 01:13:24 2012 From: d at davea.name (Dave Angel) Date: Mon, 12 Mar 2012 20:13:24 -0400 Subject: [Tutor] import pygame In-Reply-To: References: Message-ID: <4F5E9124.1080703@davea.name> On 03/12/2012 07:25 PM, Tamar Osher wrote: > Hello. I cannot successfully import third party modules. I have tried various things and searched online. Pygame is installed on my Windows 7 computer at C:\python32\pygame. Can someone please help me?>>>import pygameTraceback (most recent call last): > File "", line 1, in import pygameImportError: No module named pygame > > There are a number of places to install packages, but that's not one of them. Normally, you'd install them one level down, in dst-packages. Anyway, you can see the search path of Python, interactively. Start python, import sys, and print out sys.path that's the search path that Python uses to find imports. There are various ways to modify that, but I don't know what pygame uses. -- DaveA From wallenpb at gmail.com Tue Mar 13 11:51:08 2012 From: wallenpb at gmail.com (Bill Allen) Date: Tue, 13 Mar 2012 05:51:08 -0500 Subject: [Tutor] question on self In-Reply-To: References: Message-ID: This little thread on the usage of self references when calling class instance methods and attributes was excellent, one of the best I have seen. Thanks, Bill Allen Sent from my iPhone On Mar 12, 2012, at 3:56, Alan Gauld wrote: > On 12/03/12 02:02, Michael Lewis wrote: > >> I have another method called take turns (not shown for brevity >> purposes). When I want to call it, why can't I just call it like a >> function and use TakeTurns() instead of self.TakeTurns()? > > The Steve's have given technical answers, its also stylistically > better because it removed ambiguity for the reader as well as > for Python. > > Many corporate style guides advocate using this same style > when using C++ or Java to make it explicit when you are using > a class attribute rather than a local or global value/function. > > It improves code clarity and therefore reduces potential bugs > and speeds up maintenance for a tiny loss in initial coding > productivity. > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From wescpy at gmail.com Tue Mar 13 17:07:15 2012 From: wescpy at gmail.com (wesley chun) Date: Tue, 13 Mar 2012 09:07:15 -0700 Subject: [Tutor] question on self In-Reply-To: References: Message-ID: i want to expand specifically on steve's response and note the big distinction that needs to be made for everyone is that this is primary the difference between calling a *function* and calling a *method* (which is a function that belongs to/defined for a class). with that instance (self), that method is considered "bound," and Python automagically passes it in as the first argument to that method (self). if you wish to call an *unbound* method, you need to pass an instance on your own *and* reference it via its class, i.e., YourClass.TakeTurns(self) -- readability takes a blow there. btw, if you want to make just a function call *and* that function doesn't have much to do with the class, then just define it as a function. a seldomly-used alternative is to make it a static method (using the @staticmethod decorator) -- this lets you define a method within a class but pretend it's like a function (where you don't need to use the instance [self]). cheers, --wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.chun : wescpy-gmail.com : @wescpy/+wescpy python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From gollumgreg407366 at gmail.com Tue Mar 13 18:00:45 2012 From: gollumgreg407366 at gmail.com (Greg Nielsen) Date: Tue, 13 Mar 2012 13:00:45 -0400 Subject: [Tutor] Position issue with Pygame Message-ID: Hey everyone, Still working on that racing game project. I have come quite a far way and will hopefully release something soon, but I wrote some bad code and can't seem to fix it. Im most likely just missing something really silly because I wrote this code at 2am yesterday. Here it is def __init__(self): pygame.sprite.Sprite.__init__(self) """Set the image, convert the image, and set the rect""" self.image = pygame.image.load("NoCondition.bmp") self.image = self.image.convert() self.rect = self.image.get_rect() """Set the position of the sprite on screen""" self.center = (100, 100) self.rect.center = self.center For whatever reason, the sprite is placed at the very top of the screen as if assigned "self.rect.topleft = (0, 0)" reguardless of what I assign as the position. Please put me out of my misery and point out what little thing I coded wrong. Thank you all for the help. Greg -------------- next part -------------- An HTML attachment was scrubbed... URL: From hugo.yoshi at gmail.com Tue Mar 13 18:55:38 2012 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Tue, 13 Mar 2012 18:55:38 +0100 Subject: [Tutor] Position issue with Pygame In-Reply-To: References: Message-ID: On Tue, Mar 13, 2012 at 6:00 PM, Greg Nielsen wrote: > Hey everyone, > > ???? Still working on that racing game project. I have come quite a far way > and will hopefully release something soon, but I wrote some bad code and > can't seem to fix it. Im most likely just missing something really silly > because I wrote this code at 2am yesterday. Here it is > > ??? def __init__(self): > ??????? pygame.sprite.Sprite.__init__(self) > > ??????? """Set the image, convert the image, and set the rect""" > ??????? self.image = pygame.image.load("NoCondition.bmp") > ??????? self.image = self.image.convert() > ??????? self.rect = self.image.get_rect() > > ??????? """Set the position of the sprite on screen""" > ??????? self.center = (100, 100) > ??????? self.rect.center = self.center > > ???? For whatever reason, the sprite is placed at the very top of the screen > as if assigned "self.rect.topleft = (0, 0)" reguardless of what I assign as > the position. Please put me out of my misery and point out what little thing > I coded wrong. Thank you all for the help. > > Greg > The mistake isn't in this piece of code. It's probably in the piece of code that does the drawing, I'm guessing in the call to blit(). Make sure you're using self.rect as the destination of the blit, and the screen as the surface. HTH, Hugo From emile at fenx.com Tue Mar 13 22:09:22 2012 From: emile at fenx.com (Emile van Sebille) Date: Tue, 13 Mar 2012 14:09:22 -0700 Subject: [Tutor] number of mismatches in a string In-Reply-To: <1330715490.17262.YahooMailNeo@web111210.mail.gq1.yahoo.com> References: <1330715490.17262.YahooMailNeo@web111210.mail.gq1.yahoo.com> Message-ID: On 3/2/2012 11:11 AM Hs Hs said... > Hi: > I have the following table and I am interested in calculating mismatch > ratio. I am not completely clear how to do this and any help is deeply > appreciated. > ...and then there's always the standard library: Help on class SequenceMatcher in module difflib: class SequenceMatcher | SequenceMatcher is a flexible class for comparing pairs of sequences of | any type, so long as the sequence elements are hashable. Emile From emeraldoffice at hotmail.com Wed Mar 14 01:52:57 2012 From: emeraldoffice at hotmail.com (Tamar Osher) Date: Tue, 13 Mar 2012 19:52:57 -0500 Subject: [Tutor] Cannot run python programs on my windows7 computer Message-ID: Hello. Is there someone who can tutor me about how to "run" Python files on my windows7 computer? I have IDLE (the white box, the Python shell). I have the command prompt (the black box). And I also have Notepad++ on my computer. I have a total of 3 ways of trying to run my Python programs. I have tried and tried. The books and the online tutorials don't mention or discuss the problems that I am having; I cannot run Python programs. The computer itself it fabulously great, but I cannot get my Python files to easily run on it. If I am sometimes able to get a program to run, it is just seems to happen by chance, and I am not able to do it again next time. I feel frustrated with this situation, and need help. I hope to hear from someone, please. -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Wed Mar 14 02:25:12 2012 From: d at davea.name (Dave Angel) Date: Tue, 13 Mar 2012 21:25:12 -0400 Subject: [Tutor] import pygame In-Reply-To: References: , <4F5E9124.1080703@davea.name> Message-ID: <4F5FF378.9090807@davea.name> Three points of order, then a response, all at the proper place, after the portion of your message I'm quoting. On 03/13/2012 05:48 PM, Tamar Osher wrote: > > Dear Dave: Hi. Pygame is located in my computer at c:\Python32\Lib\site-packages\pygame. I am having difficulty importing and using pygame. Can someone help, please? >>>> import sys>>> print (sys.path)['C:\\Python32\\Lib\\idlelib', 'C:\\windows\\system32\\python32.zip', 'C:\\Python32\\DLLs', 'C:\\Python32\\lib', 'C:\\Python32', 'C:\\Python32\\lib\\site-packages']>>> import pygameTraceback (most recent call last): File "", line 1, in import pygameImportError: No module named pygame>>> > 1) please don't top-post. In this forum, as in most mailing lists, your response should go after the portion of whatever message you're quoting. 2) please use text mode email. By posting in an html format, you cause the lines of the message to run together. No harm done in this case, but it's a bad habit to get into. 3) please use reply-all, or use other means to make sure you include tutor at python.org as a recipient. You sent this message to me only, and I don't reply to private emails. As for your error, you're apparently not running this from a cmd prompt, but from pyshell. So you've introduced other variables into the equation, and somebody else will have to help. Put those lines in a text file, and run them as: c:\ >> python3 myfile.py and see what error you get then. At that point, you know what Python will do. If your shell gives worse results, then you have to figure out the shell. -- DaveA From emeraldoffice at hotmail.com Wed Mar 14 02:50:28 2012 From: emeraldoffice at hotmail.com (Tamar Osher) Date: Tue, 13 Mar 2012 20:50:28 -0500 Subject: [Tutor] top-posting and text mode email Message-ID: Hi!Could someone please explain what top-posting is? Specifically how does someone not "top-post"? What is text mode email? How does someone get and use text mode email? How can I recognize that I am sending an email message in text mode? I have a hotmail email account. What is the best way to get text mode email? -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Wed Mar 14 03:28:38 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 14 Mar 2012 02:28:38 +0000 Subject: [Tutor] top-posting and text mode email In-Reply-To: References: Message-ID: This is top posted. On 14/03/2012 01:50, Tamar Osher wrote: > > Hi!Could someone please explain what top-posting is? Specifically how does someone not "top-post"? > What is text mode email? How does someone get and use text mode email? How can I recognize that I am sending an email message in text mode? I have a hotmail email account. What is the best way to get text mode email? > Text mode email is an email sent in plain text, i.e. it doesn't have any html embedded. Your hotmail account should have an option that allows you to toggle between plain text and html. If not get a different email account :) > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor This is bottom posted. -- Cheers. Mark Lawrence. From breamoreboy at yahoo.co.uk Wed Mar 14 03:40:08 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 14 Mar 2012 02:40:08 +0000 Subject: [Tutor] Cannot run python programs on my windows7 computer In-Reply-To: References: Message-ID: On 14/03/2012 00:52, Tamar Osher wrote: > > Hello. Is there someone who can tutor me about how to "run" Python files on my windows7 computer? I have IDLE (the white box, the Python shell). I have the command prompt (the black box). And I also have Notepad++ on my computer. I have a total of 3 ways of trying to run my Python programs. I have tried and tried. The books and the online tutorials don't mention or discuss the problems that I am having; I cannot run Python programs. The computer itself it fabulously great, but I cannot get my Python files to easily run on it. If I am sometimes able to get a program to run, it is just seems to happen by chance, and I am not able to do it again next time. I feel frustrated with this situation, and need help. I hope to hear from someone, please. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Stating "I cannot run Python programs" doesn't give us much to go on. Read this first http://www.imladris.com/Scripts/PythonForWindows.html If you still have problems tell us exactly what you are doing and what the error messages are by cutting and pasting into email, don't try to type stuff yourself. -- Cheers. Mark Lawrence. From brian.van.den.broek at gmail.com Wed Mar 14 11:42:53 2012 From: brian.van.den.broek at gmail.com (Brian van den Broek) Date: Wed, 14 Mar 2012 12:42:53 +0200 Subject: [Tutor] Cannot run python programs on my windows7 computer In-Reply-To: References: Message-ID: On 14 Mar 2012 02:56, "Tamar Osher" wrote: > > Hello. Is there someone who can tutor me about how to "run" Python files on my windows7 computer? I have IDLE (the white box, the Python shell). I have the command prompt (the black box). And I also have Notepad++ on my computer. I have a total of 3 ways of trying to run my Python programs. I have tried and tried. The books Hi Tamar, I remember that I found it a bit non-obvious to get this working when I started with python, too. Unfortunately, that is nearing a decade ago and I don't recall what the bump was. If you can get idle going, you can run programs. On the File menu, New opens a new editor window where you can type a program and Open opens an extant file. It also provide a different menu with Run. If that doesn't run your program, something is messed up with your install. Idle isn't always the best choice; you'll want to be able to run from a command shell (the "black box"), too. What happens when you type 'python' there? If you get a python prompt, save a file mytest.py that has the sole line raw_input(42) somewhere and try 'python full\path\to\mytest.py'. If you don't get a python prompt on typing 'python' type 'path' and report your result. I don't have a windows box, so I am going on memory and might have got things wrong. As for top posting: notice how my text follows yours? This means a reader of this email hits the context before my content. If you are on a number of lists and watching a number of threads, top posted emails are annoying as you have to scroll down to read the context then up to read the content. Whether that makes sense to you or not, the community from which you seek help strongly prefers you not top post, so don't. Best, Brian vdB -------------- next part -------------- An HTML attachment was scrubbed... URL: From emeraldoffice at hotmail.com Wed Mar 14 17:12:51 2012 From: emeraldoffice at hotmail.com (Tamar Osher) Date: Wed, 14 Mar 2012 11:12:51 -0500 Subject: [Tutor] seeing the results of a python program in windows7 Message-ID: Hi. I ask for help. Thanks very much for your time. I can run a python program in Notepad++, but what happens is that the black box flashes and disappears immediately, so that I never see the results. How can I style it so that the results of the program stay on the computer screen, for me to see? Using IDLE, the Python Shell, I can click File/New Window, to get a new window that allows me to RUN a program. But the RUN option does not allow me to choose which program I want to run. How can I style it so that I can choose which program to run, and how can I see the results of that program? -------------- next part -------------- An HTML attachment was scrubbed... URL: From hugo.yoshi at gmail.com Wed Mar 14 17:57:33 2012 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Wed, 14 Mar 2012 17:57:33 +0100 Subject: [Tutor] seeing the results of a python program in windows7 In-Reply-To: References: Message-ID: On Wed, Mar 14, 2012 at 5:12 PM, Tamar Osher wrote: > Hi. ?I ask for help. ?Thanks very much for your time. > > I can run a python program in Notepad++, but what happens is that the black > box flashes and disappears immediately, so that I never see the results. > ?How can I style it so that the results of the program stay on the computer > screen, for me to see? > The black box disappears when the program exits. To stop your program from exiting immediately, you can wait for user input at the end of your program. In python 3, this is the input() function. In python 2 you should use raw_input(). Alternatively, you could add the lines import os os.system("pause") at the end of the program, which asks you to press any key and then exits. > Using IDLE, the Python Shell, I can click File/New Window, to get a new > window that allows me to RUN a program. ?But the RUN option does not allow > me to choose which program I want to run. ?How can I style it so that I can > choose which program to run, and how can I see the results of that program? > If you want to use IDLE it's possible as well, and you don't need to change your program for it. Just open the file you want to run in IDLE (in the IDLE menu click File -> Open, or right click the file in explorer and choose "Edit with IDLE") Then, either press F5 or click Run -> Run Module. HTH, Hugo From breamoreboy at yahoo.co.uk Wed Mar 14 18:07:48 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 14 Mar 2012 17:07:48 +0000 Subject: [Tutor] seeing the results of a python program in windows7 In-Reply-To: References: Message-ID: On 14/03/2012 16:12, Tamar Osher wrote: > > Hi. I ask for help. Thanks very much for your time. > I can run a python program in Notepad++, but what happens is that the black box flashes and disappears immediately, so that I never see the results. How can I style it so that the results of the program stay on the computer screen, for me to see? > Using IDLE, the Python Shell, I can click File/New Window, to get a new window that allows me to RUN a program. But the RUN option does not allow me to choose which program I want to run. How can I style it so that I can choose which program to run, and how can I see the results of that program? > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Now that you can actually run a program, would you please be kind enough to tell everybody for the record how you overcame the problem "I cannot run Python programs" as asked in the thread entitled "Cannot run python programs on my windows7 computer". -- Cheers. Mark Lawrence. From bgailer at gmail.com Thu Mar 15 03:09:05 2012 From: bgailer at gmail.com (bob gailer) Date: Wed, 14 Mar 2012 22:09:05 -0400 Subject: [Tutor] seeing the results of a python program in windows7 In-Reply-To: References: Message-ID: <4F614F41.5020307@gmail.com> On 3/14/2012 12:12 PM, Tamar Osher wrote: > Hi. I ask for help. Thanks very much for your time. > > I can run a python program in Notepad++, but what happens is that the > black box flashes and disappears immediately, so that I never see the > results. If you expected anything else you don't understand how windows runs programs. > How can I style it so that the results of the program stay on the > computer screen, for me to see? Do this: try: # your program goes here finally: raw_input("Press any key") # if you are running Python 3 replace raw_input with input Adding the try-finally construct ensures that any exception in your code will be visible. -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From brian.van.den.broek at gmail.com Thu Mar 15 07:45:58 2012 From: brian.van.den.broek at gmail.com (Brian van den Broek) Date: Thu, 15 Mar 2012 08:45:58 +0200 Subject: [Tutor] seeing the results of a python program in windows7 In-Reply-To: <4F614F41.5020307@gmail.com> References: <4F614F41.5020307@gmail.com> Message-ID: On 15 Mar 2012 04:14, "bob gailer" wrote: > > On 3/14/2012 12:12 PM, Tamar Osher wrote: >> I can run a python program in Notepad++, but what happens is that the black box flashes and disappears immediately, so that I never see the results. >> >> How can I style it so that the results of the program stay on the computer screen, for me to see? > > Do this: > > try: > # your program goes here > finally: > raw_input("Press any key") > # if you are running Python 3 replace raw_input with input > > Adding the try-finally construct ensures that any exception in your code will be visible. > Alternatively, invoke python to run your program at the prompt with the interactive switch: python -i myscript.py Best, Brian vdB -------------- next part -------------- An HTML attachment was scrubbed... URL: From hadi.is at hotmail.com Thu Mar 15 08:53:40 2012 From: hadi.is at hotmail.com (Hadi ismail) Date: Thu, 15 Mar 2012 03:53:40 -0400 Subject: [Tutor] minecraft and python Message-ID: Hello, im new to python i've decided to learn python so i can make plugins in games like css and minecraft i have a question about minecraft, there is a plugin that loads plugins made in python. http://forums.bukkit.org/threads/dev-pythonloader-v0-3-1-load-plugins-written-in-python-1597.30389/page-2 This sounds really nice because i dont have to learn java but i dont know how to start how would make a program that works in minecraft for example this program Roll the dice numbers 1-10 if the player picks the right number he gets a reward you can only do it once in a while the rewards could be items or something i know how to do this in python but i dont know how to do it in way that it works in minecraft seems like its impossible for me and there are no tutorials on it because the python loader plugin doesnt tell you how to do this stuff and i couldnt find anything online about it please help thank you -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Mar 15 09:15:58 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 15 Mar 2012 08:15:58 +0000 Subject: [Tutor] minecraft and python In-Reply-To: References: Message-ID: On 15/03/12 07:53, Hadi ismail wrote: > i know how to do this in python but i dont know how to do it in way that > it works in minecraft seems like its impossible for me and there are no > tutorials on it There are probably tutorials on how to do it in Java and you will need to translate how Java does it to Python. Also you may be able to find plugins written in Python by other people and you can study their code to see how they did similar things. Unfortunately you will be very lucky if you find anyone on this list to answer your questions. You would really need to ask on a minecraft forum or mailing list. Even if you did find someone it's not really relevant to this list since it is about learning to program in python, not learning to interface with product xyz... good luck, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From kellyadrian at hotmail.com Thu Mar 15 15:19:16 2012 From: kellyadrian at hotmail.com (ADRIAN KELLY) Date: Thu, 15 Mar 2012 14:19:16 +0000 Subject: [Tutor] null inputs Message-ID: Hi guys, how do i prevent a user from leaving a blank when inputting? e.g. age=int(input("what age are you? ")).................. i want to stop the user pressing enter!!!! if age==""????? Adrian Kelly 1 Bramble Close Baylough Athlone County Westmeath 0879495663 -------------- next part -------------- An HTML attachment was scrubbed... URL: From kellyadrian at hotmail.com Thu Mar 15 15:32:20 2012 From: kellyadrian at hotmail.com (ADRIAN KELLY) Date: Thu, 15 Mar 2012 14:32:20 +0000 Subject: [Tutor] FW: null inputs In-Reply-To: References: Message-ID: Adrian Kelly 1 Bramble Close Baylough Athlone County Westmeath 0879495663 From: kellyadrian at hotmail.com To: tutor at python.org Subject: null inputs Date: Thu, 15 Mar 2012 14:19:16 +0000 Hi guys, how do i prevent a user from leaving a blank when inputting? e.g. age=int(input("what age are you? ")).................. i want to stop the user pressing enter!!!! if age==""????? ************************************ age=raw_input("what age are you? ") if age=="": age=int(age) print "please enter your age" else: print "your age is ",age ************************************* i have tried this but still no luck, if anyone can help i would apprecitate it Adrian Kelly 1 Bramble Close Baylough Athlone County Westmeath 0879495663 -------------- next part -------------- An HTML attachment was scrubbed... URL: From eire1130 at gmail.com Thu Mar 15 15:56:48 2012 From: eire1130 at gmail.com (James Reynolds) Date: Thu, 15 Mar 2012 10:56:48 -0400 Subject: [Tutor] FW: null inputs In-Reply-To: References: Message-ID: On Thu, Mar 15, 2012 at 10:32 AM, ADRIAN KELLY wrote: > > > Adrian Kelly > 1 Bramble Close > Baylough > Athlone > County Westmeath > > 0879495663 > > > ------------------------------ > From: kellyadrian at hotmail.com > To: tutor at python.org > Subject: null inputs > Date: Thu, 15 Mar 2012 14:19:16 +0000 > > Hi guys, > how do i prevent a user from leaving a blank when inputting? > > e.g. > age=int(input("what age are you? ")).................. i want to stop the > user pressing enter!!!! > > if age==""????? > > > ************************************ > age=raw_input("what age are you? ") > if age=="": > age=int(age) > print "please enter your age" > else: > print "your age is ",age > ************************************* > i have tried this but still no luck, if anyone can help i would > apprecitate it > > > > Adrian Kelly > 1 Bramble Close > Baylough > Athlone > County Westmeath > > 0879495663 > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > You can't prevent users from entering whatever they feel like it, but you can prevent your program from processing that input and force them to try again. The typical way this is done is through a while loop: age = '' while age != '' age=raw_input("what age are you? ") this will continue to loop until you give it something other than ''. Of course, you can build on this, you know, something like: checker = False while checker: age=raw_input("what age are you? ") try: age = int(age) checker = True except TypeError: print "you didn't enter an integer for an age!" print "try again!!! -------------- next part -------------- An HTML attachment was scrubbed... URL: From hugo.yoshi at gmail.com Thu Mar 15 16:03:12 2012 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Thu, 15 Mar 2012 16:03:12 +0100 Subject: [Tutor] FW: null inputs In-Reply-To: References: Message-ID: On Thu, Mar 15, 2012 at 3:56 PM, James Reynolds wrote: > > > You can't prevent users from entering whatever they feel like it, but you > can prevent your program from processing that input and force them to try > again. > > The typical way this is done is through a while loop: > > age = '' > > while age != '' > ? ??age=raw_input("what age are you? ") > > this will continue to loop until you give it something other than ''. > > Of course, you can build on this, you know, something like: > > checker = False > > while checker: > ? ??age=raw_input("what age are you? ") > ? ? try: > ? ? ? ? age = int(age) > ? ? ? ? checker = True > ? ? except TypeError: > ? ? ? print "you didn't enter an integer for an age!" > ? ? ? print "try again!!! > > Small correction: the exception you're looking for in this case is a ValueError (after all, the argument provided has the correct type, but its value can not be converted to an integer). int will throw TypeError, but only if you supply an argument that is not a string or number. Hugo From kellyadrian at hotmail.com Thu Mar 15 16:08:56 2012 From: kellyadrian at hotmail.com (ADRIAN KELLY) Date: Thu, 15 Mar 2012 15:08:56 +0000 Subject: [Tutor] FW: null inputs In-Reply-To: References: , , Message-ID: thanks very much i get it now............... > From: hugo.yoshi at gmail.com > Date: Thu, 15 Mar 2012 16:03:12 +0100 > Subject: Re: [Tutor] FW: null inputs > To: eire1130 at gmail.com > CC: kellyadrian at hotmail.com; tutor at python.org > > On Thu, Mar 15, 2012 at 3:56 PM, James Reynolds wrote: > > > > > > You can't prevent users from entering whatever they feel like it, but you > > can prevent your program from processing that input and force them to try > > again. > > > > The typical way this is done is through a while loop: > > > > age = '' > > > > while age != '' > > age=raw_input("what age are you? ") > > > > this will continue to loop until you give it something other than ''. > > > > Of course, you can build on this, you know, something like: > > > > checker = False > > > > while checker: > > age=raw_input("what age are you? ") > > try: > > age = int(age) > > checker = True > > except TypeError: > > print "you didn't enter an integer for an age!" > > print "try again!!! > > > > > > Small correction: the exception you're looking for in this case is a > ValueError (after all, the argument provided has the correct type, but > its value can not be converted to an integer). int will throw > TypeError, but only if you supply an argument that is not a string or > number. > > Hugo -------------- next part -------------- An HTML attachment was scrubbed... URL: From emeraldoffice at hotmail.com Thu Mar 15 18:59:14 2012 From: emeraldoffice at hotmail.com (Tamar Osher) Date: Thu, 15 Mar 2012 12:59:14 -0500 Subject: [Tutor] How do I get user input when running a python program? Message-ID: Hi. I am reading Python for the Absolute Beginner, finished chapter 4, and am trying to duplicate the author's games. In order to know if I have properly created my new games, I need to get user input and see what happens. How do I set things up on my computer so that I can get user input when my new program is being run? I have Python 3.2.2 and a Windows7 64-bit computer. I hope to hear from someone; thank you very much for helping me. I am very appreciative! -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Thu Mar 15 19:15:08 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 15 Mar 2012 18:15:08 +0000 Subject: [Tutor] How do I get user input when running a python program? In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF474026B93A3@SCACMX008.exchad.jpmchase.net> >Hi. ?I am reading Python for the Absolute Beginner, finished chapter 4, and am trying to duplicate the author's games. ?In order to know if I have properly created my new games, I need to get user input and see what happens. ?How do I set things up on my computer so that I can get user input when my new program is being run? ?I have Python 3.2.2 and a Windows7 64-bit computer. ?I hope to hear from someone; thank you very much for helping me. ?I am very appreciative! How is the author doing it? What code do you have? What problems are you facing? What errors are you getting (please copy/paste the full error message including stack trace)? Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From kellyadrian at hotmail.com Thu Mar 15 22:24:21 2012 From: kellyadrian at hotmail.com (ADRIAN KELLY) Date: Thu, 15 Mar 2012 21:24:21 +0000 Subject: [Tutor] stuck on null values Message-ID: Please can anyone tell me how to solve the problem i am having here, i am trying to loop if the value is left blank by the user but how can i then use the value and multiply it. e.g. while number_child==""............ i want to multiply the input i get.........??? def main(): print """________________________________________________________ Welcome to the Travel Kiosk________________________________________________________""" adult=15 child=5 firstname=raw_input("Please enter your firstname: ") lastname=raw_input ("Please enter your lastname: ") number_child=raw_input("Enter the number of kids: ") number_adults=raw_input("Enter the number of adults: ") while number_child=="": number_child=raw_input("Enter the number of kids: ") price=child*number_child print """_______________________________________________________ Thank you, the Price will be: """,price print"""_______________________________________________________""" main() Adrian Kelly 1 Bramble Close Baylough Athlone County Westmeath 0879495663 -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Thu Mar 15 22:38:52 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 15 Mar 2012 17:38:52 -0400 Subject: [Tutor] stuck on null values In-Reply-To: References: Message-ID: On Thu, Mar 15, 2012 at 5:24 PM, ADRIAN KELLY wrote: > Please can anyone tell me how to solve the problem i am having here, i am > trying to loop if the value is left blank by the user > but how can i then use the value and multiply it. ?e.g. while > number_child==""............ i want to multiply the input i get.........??? > > def main(): > ? ? print """ > ________________________________________________________ > > ? ? ? ? ? ? ? ? Welcome to the Travel Kiosk > ________________________________________________________ > """ > > ? ? adult=15 > ? ? child=5 > ? ? firstname=raw_input("Please enter your firstname: ") > ? ? lastname=raw_input ("Please enter your lastname: ") > ? ? number_child=raw_input("Enter the number of kids: ") > ? ? number_adults=raw_input("Enter the number of adults: ") > ? ? while number_child=="": > ? ? ? ? number_child=raw_input("Enter the number of kids: ") > ? ? price=child*number_child > > > ? ? print """ > _______________________________________________________ > > Thank you, the Price will be: """,price > ? ? print""" > _______________________________________________________ > """ > > main() > > > > > > > Adrian Kelly > 1 Bramble Close > Baylough > Athlone > County Westmeath > > 0879495663 > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > raw_input returns the values the user types as a string. In python if you have 3 * 'bob' the result will be "bobbobbob" So you need to turn the number_child into a number like so: int(number_child) You will need to do the same thing for the number of adults. That will get you started, but if your user types in something that isn't a number, your program will fail. See if you can get it to work for good data and then come back with what happens when you type in other than integers. Also, when your program fails, it prints out what is called a traceback. When you get this situation, be sure to post the traceback with your problem. It helps figure out what went wrong -- Joel Goldstick From wprins at gmail.com Thu Mar 15 23:11:40 2012 From: wprins at gmail.com (Walter Prins) Date: Thu, 15 Mar 2012 22:11:40 +0000 Subject: [Tutor] How do I get user input when running a python program? In-Reply-To: References: Message-ID: Hi Tamar, On 15 March 2012 17:59, Tamar Osher wrote: > Hi. ?I am reading Python for the Absolute Beginner, finished chapter 4, and > am trying to duplicate the author's games. ?In order to know if I have > properly created my new games, I need to get user input and see what > happens. ?How do I set things up on my computer so that I can get user input > when my new program is being run? ?I have Python 3.2.2 and a Windows7 64-bit > computer. ?I hope to hear from someone; thank you very much for helping me. > ?I am very appreciative! Firstly, what version of the book are you using? (Or more specifically, what version of Python is the book using?) You're just setting yourself up for trouble if your book is using a substantially different version of Python than you are. (The first version of the book, for example, came out in 2003 and uses Python 2.2...) The second edition came out around 2006 so probably also uses Python 2.x so even if you're using that, I'd suggest you perhaps consider uninstalling Python 3 and (for now at least) installing something closer to what the book is using. (Sorry if this causes you trouble, but IMHO it's probably better for you to not introduce more unnecessary variables that make your learning more complicated that it needs to be and using Python 3.x when your book is 2.x will make things more complicated than it needs to be.) Secondly, have you actually read the first 3 chapters? I ask, because by your question it appears you may not have, or may not have properly absorbed the content. For example, in the first chapter of the book (at the least, the first version), your question is partially answered. I quote: "*Waiting for the user* ================ The last line of the program: raw_input("\n\nPress the Enter key to exit.") displays the prompt "Press the Enter key to exit." and waits for the user to press the Enter key. Once the user presses the key, the program ends. This is a nice trick to keep a console window open until the user is done with an application." Similarly, there's a section entitled "Getting user input" in chapter 2. So, to echo Ramit, are you having trouble understanding how the author does it in Chapter 1 & 2? If not, what are you stuck on? Regards, Walter From emeraldoffice at hotmail.com Thu Mar 15 23:12:37 2012 From: emeraldoffice at hotmail.com (Tamar Osher) Date: Thu, 15 Mar 2012 17:12:37 -0500 Subject: [Tutor] how I overcame the problem "I cannot run Python programs" Message-ID: I realized that my computer was running the programs. The black box was flashing off and disappearing immediately, so that I never saw the programs. Also, I am using Notepad++, in addition to IDLE. I am now able to see my programs and provide user input, when I use Notepad++. Also, I still have not fully overcome, I am slowly on my way to success. I am working vigorously on Python, but only 10% of my time is learning Python. The rest of my time is learning everything related to Python, to get my programs to work. I greatly appreciate everyone's help! I cannot thank each of you enough. Thanks for being there when I need someone! Have a wonderful day! -------------- next part -------------- An HTML attachment was scrubbed... URL: From eire1130 at gmail.com Thu Mar 15 23:30:47 2012 From: eire1130 at gmail.com (eire1130 at gmail.com) Date: Thu, 15 Mar 2012 22:30:47 +0000 Subject: [Tutor] how I overcame the problem "I cannot run Python programs" In-Reply-To: References: Message-ID: <1795078761-1331850648-cardhu_decombobulator_blackberry.rim.net-1415149165-@b11.c28.bise6.blackberry> That's the nature of things I'm afraid. I do about half of my development on windows. My recomendation, download eclipse and install pydev. IDE choice is always a touchy subject but for windows, this should be your choice. I have notepad++ as well. Its great. But eclipse is better, especially for learning. I can't describe how much it helped me. Sent from my Verizon Wireless BlackBerry -----Original Message----- From: Tamar Osher Sender: tutor-bounces+eire1130=gmail.com at python.org Date: Thu, 15 Mar 2012 17:12:37 To: Tutor at Python.org Subject: [Tutor] how I overcame the problem "I cannot run Python programs" _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From emeraldoffice at hotmail.com Thu Mar 15 23:39:53 2012 From: emeraldoffice at hotmail.com (Tamar Osher) Date: Thu, 15 Mar 2012 17:39:53 -0500 Subject: [Tutor] more about how I overcame not being able to run my programs Message-ID: I am very appreciative for the many valuable individuals who graciously take their precious time to help others in need. Special thanks to: Brian van den Broek,Bob Gailer,and Hugo Arts. I followed all the instructions of Hugo, Bob, and Brian. This is specifically what I am now doing so that I can see the programs that I run, and also be able to provide user input: try: import os # my programfinally: input ('\n\t\t\tPress the enter key to continue.') os.system ('pause') -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Mar 16 00:51:47 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 15 Mar 2012 23:51:47 +0000 Subject: [Tutor] more about how I overcame not being able to run my programs In-Reply-To: References: Message-ID: On 15/03/12 22:39, Tamar Osher wrote: > try: > import os > # my program > finally: > input ('\n\t\t\tPress the enter key to continue.') > os.system ('pause') It's more conventional to put the import at the very top, before the try: line. But otherwise what you have should be fine. There are other ways of doing it and eventually you may write programs that don't require the press enter... line and you can then miss out all of the code above. But for learning that's fine. Or just run your programs inside IDLE or, as someone else suggested, Eclipse and PyDev (although personally that seems like overkill!) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From breamoreboy at yahoo.co.uk Fri Mar 16 01:29:37 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 16 Mar 2012 00:29:37 +0000 Subject: [Tutor] how I overcame the problem "I cannot run Python programs" In-Reply-To: <1795078761-1331850648-cardhu_decombobulator_blackberry.rim.net-1415149165-@b11.c28.bise6.blackberry> References: <1795078761-1331850648-cardhu_decombobulator_blackberry.rim.net-1415149165-@b11.c28.bise6.blackberry> Message-ID: On 15/03/2012 22:30, eire1130 at gmail.com wrote: > > That's the nature of things I'm afraid. > > I do about half of my development on windows. My recomendation, download eclipse and install pydev. IDE choice is always a touchy subject but for windows, this should be your choice. > > I have notepad++ as well. Its great. But eclipse is better, especially for learning. I can't describe how much it helped me. > I believe that eclipse is crap. I tried it 10 years ago and gave up because it was so slow. I tried it a couple of months ago for two weeks and again gave up for the same reasons. Why not stick with pythonwin, it's perfectly adequate for my needs? -- Cheers. Mark Lawrence. From steve at pearwood.info Fri Mar 16 01:35:35 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 16 Mar 2012 11:35:35 +1100 Subject: [Tutor] more about how I overcame not being able to run my programs In-Reply-To: References: Message-ID: <4F628AD7.6090303@pearwood.info> Alan Gauld wrote: > On 15/03/12 22:39, Tamar Osher wrote: > >> try: >> import os >> # my program >> finally: >> input ('\n\t\t\tPress the enter key to continue.') >> os.system ('pause') > > It's more conventional to put the import at the very top, before the > try: line. True, but in this case, if there is an import error, the message will flash by without being read. Wrapping the *entire* program, imports and all, ensures that the program will pause regardless of what happens. -- Steven From alan.gauld at btinternet.com Fri Mar 16 02:10:39 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 16 Mar 2012 01:10:39 +0000 Subject: [Tutor] how I overcame the problem "I cannot run Python programs" In-Reply-To: References: <1795078761-1331850648-cardhu_decombobulator_blackberry.rim.net-1415149165-@b11.c28.bise6.blackberry> Message-ID: On 16/03/12 00:29, Mark Lawrence wrote: >> I have notepad++ as well. Its great. But eclipse is better, especially >> for learning. I can't describe how much it helped me. > > I believe that eclipse is crap. No, it's not crap, it's one of the most powerful and extensible development tools available and used by thousands (millions?) of professional programmers worldwide. But... > I tried it 10 years ago and gave up because it was so slow. It's written in Java and 10 years ago few PCs had the horsepower to run Java well, and the Java compilers/VM were less efficient too. > I tried it a couple of months ago for two weeks and again gave up > for the same reasons. Unless you are still using the same 10 year old PC it shouldn't have been that bad! I certainly don't find it any slower than most large apps these days. > Why not stick with pythonwin, it's perfectly adequate for my needs? For a beginner to python I tend to agree with you. Not because Eclipse is slow but because it's way over powered for the simple programs beginners write. If you want to develop a large application with dozens/hundreds of files and packages on Windows then Eclipse (or Netbeans etc) is a useful tool to have. And if you need to develop code in many different languages again, Eclipse will provide consistency. And if you need to build design models in UML you get a choice of top-end tools. But, for single-file programs Pythonwin and even IDLE are perfectly adequate. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From cyclicflux at yahoo.com Fri Mar 16 08:26:59 2012 From: cyclicflux at yahoo.com (cyclicflux at yahoo.com) Date: Fri, 16 Mar 2012 03:26:59 -0400 Subject: [Tutor] How I overcame my problems executing python programs. In-Reply-To: References: Message-ID: I've just received this e-mail on my android and believe that the above advice is good(as always), this list is great for beginners as there are a never-ending amt. Of talented/knowledgable ppl. Available. Additionally, I love Eclipse's Pydev(Comes incl. 'd) already in AptanaStudio(Eclipse-derivative for web-development and best of all python. Its very new, and although there is a commercial version, they provide full features to the free Aptana version. If you go this route, there is one less step, and me starting python a year or so ago, it was a life-saver. The other life-saver was the pydoc feature that comes with the std. Python Windows installation. Its amazing and if my memory serves correctly in Windows IDLE launched from the help menu. Thats great for quickly referencing things. But good luck!! Sent from my Verizon Wireless Phone -----Original message----- From: tutor-request at python.org To: tutor at python.org Sent: Fri, Mar 16, 2012 01:12:28 GMT+00:00 Subject: Tutor Digest, Vol 97, Issue 41 Send Tutor mailing list submissions to tutor at python.org To subscribe or unsubscribe via the World Wide Web, visit http://mail.python.org/mailman/listinfo/tutor or, via email, send a message with subject or body 'help' to tutor-request at python.org You can reach the person managing the list at tutor-owner at python.org When replying, please edit your Subject line so it is more specific than "Re: Contents of Tutor digest..." Today's Topics: 1. how I overcame the problem "I cannot run Python programs" (Tamar Osher) 2. Re: how I overcame the problem "I cannot run Python programs" (eire1130 at gmail.com) 3. more about how I overcame not being able to run my programs (Tamar Osher) 4. Re: more about how I overcame not being able to run my programs (Alan Gauld) 5. Re: how I overcame the problem "I cannot run Python programs" (Mark Lawrence) 6. Re: more about how I overcame not being able to run my programs (Steven D'Aprano) 7. Re: how I overcame the problem "I cannot run Python programs" (Alan Gauld) ---------------------------------------------------------------------- Message: 1 Date: Thu, 15 Mar 2012 17:12:37 -0500 From: Tamar Osher To: "Tutor at Python.org" Subject: [Tutor] how I overcame the problem "I cannot run Python programs" Message-ID: Content-Type: text/plain; charset="iso-8859-1" I realized that my computer was running the programs. The black box was flashing off and disappearing immediately, so that I never saw the programs. Also, I am using Notepad++, in addition to IDLE. I am now able to see my programs and provide user input, when I use Notepad++. Also, I still have not fully overcome, I am slowly on my way to success. I am working vigorously on Python, but only 10% of my time is learning Python. The rest of my time is learning everything related to Python, to get my programs to work. I greatly appreciate everyone's help! I cannot thank each of you enough. Thanks for being there when I need someone! Have a wonderful day! -------------- next part -------------- An HTML attachment was scrubbed... URL: ------------------------------ Message: 2 Date: Thu, 15 Mar 2012 22:30:47 +0000 From: eire1130 at gmail.com To: "Tamar Osher" , tutor-bounces+eire1130=gmail.com at python.org, "Tutor at Python.org" Subject: Re: [Tutor] how I overcame the problem "I cannot run Python programs" Message-ID: <1795078761-1331850648-cardhu_decombobulator_blackberry.rim.net-1415149165- at b 11.c28.bise6.blackberry> Content-Type: text/plain That's the nature of things I'm afraid. I do about half of my development on windows. My recomendation, download eclipse and install pydev. IDE choice is always a touchy subject but for windows, this should be your choice. I have notepad++ as well. Its great. But eclipse is better, especially for learning. I can't describe how much it helped me. Sent from my Verizon Wireless BlackBerry -----Original Message----- From: Tamar Osher Sender: tutor-bounces+eire1130=gmail.com at python.org Date: Thu, 15 Mar 2012 17:12:37 To: Tutor at Python.org Subject: [Tutor] how I overcame the problem "I cannot run Python programs" _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ------------------------------ Message: 3 Date: Thu, 15 Mar 2012 17:39:53 -0500 From: Tamar Osher To: "Tutor at Python.org" Subject: [Tutor] more about how I overcame not being able to run my programs Message-ID: Content-Type: text/plain; charset="iso-8859-1" I am very appreciative for the many valuable individuals who graciously take their precious time to help others in need. Special thanks to: Brian van den Broek,Bob Gailer,and Hugo Arts. I followed all the instructions of Hugo, Bob, and Brian. This is specifically what I am now doing so that I can see the programs that I run, and also be able to provide user input: try: import os # my programfinally: input ('\n\t\t\tPress the enter key to continue.') os.system ('pause') -------------- next part -------------- An HTML attachment was scrubbed... URL: ------------------------------ Message: 4 Date: Thu, 15 Mar 2012 23:51:47 +0000 From: Alan Gauld To: tutor at python.org Subject: Re: [Tutor] more about how I overcame not being able to run my programs Message-ID: Content-Type: text/plain; charset=ISO-8859-1; format=flowed On 15/03/12 22:39, Tamar Osher wrote: > try: > import os > # my program > finally: > input ('\n\t\t\tPress the enter key to continue.') > os.system ('pause') It's more conventional to put the import at the very top, before the try: line. But otherwise what you have should be fine. There are other ways of doing it and eventually you may write programs that don't require the press enter... line and you can then miss out all of the code above. But for learning that's fine. Or just run your programs inside IDLE or, as someone else suggested, Eclipse and PyDev (although personally that seems like overkill!) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ------------------------------ Message: 5 Date: Fri, 16 Mar 2012 00:29:37 +0000 From: Mark Lawrence To: tutor at python.org Subject: Re: [Tutor] how I overcame the problem "I cannot run Python programs" Message-ID: Content-Type: text/plain; charset=ISO-8859-1; format=flowed On 15/03/2012 22:30, eire1130 at gmail.com wrote: > > That's the nature of things I'm afraid. > > I do about half of my development on windows. My recomendation, download eclipse and install pydev. IDE choice is always a touchy subject but for windows, this should be your choice. > > I have notepad++ as well. Its great. But eclipse is better, especially for learning. I can't describe how much it helped me. > I believe that eclipse is crap. I tried it 10 years ago and gave up because it was so slow. I tried it a couple of months ago for two weeks and again gave up for the same reasons. Why not stick with pythonwin, it's perfectly adequate for my needs? -- Cheers. Mark Lawrence. ------------------------------ Message: 6 Date: Fri, 16 Mar 2012 11:35:35 +1100 From: Steven D'Aprano To: tutor at python.org Subject: Re: [Tutor] more about how I overcame not being able to run my programs Message-ID: <4F628AD7.6090303 at pearwood.info> Content-Type: text/plain; charset=us-ascii; format=flowed Alan Gauld wrote: > On 15/03/12 22:39, Tamar Osher wrote: > >> try: >> import os >> # my program >> finally: >> input ('\n\t\t\tPress the enter key to continue.') >> os.system ('pause') > > It's more conventional to put the import at the very top, before the > try: line. True, but in this case, if there is an import error, the message will flash by without being read. Wrapping the *entire* program, imports and all, ensures that the program will pause regardless of what happens. -- Steven ------------------------------ Message: 7 Date: Fri, 16 Mar 2012 01:10:39 +0000 From: Alan Gauld To: tutor at python.org Subject: Re: [Tutor] how I overcame the problem "I cannot run Python programs" Message-ID: Content-Type: text/plain; charset=ISO-8859-1; format=flowed On 16/03/12 00:29, Mark Lawrence wrote: >> I have notepad++ as well. Its great. But eclipse is better, especially >> for learning. I can't describe how much it helped me. > > I believe that eclipse is crap. No, it's not crap, it's one of the most powerful and extensible development tools available and used by thousands (millions?) of professional programmers worldwide. But... > I tried it 10 years ago and gave up because it was so slow. It's written in Java and 10 years ago few PCs had the horsepower to run Java well, and the Java compilers/VM were less efficient too. > I tried it a couple of months ago for two weeks and again gave up > for the same reasons. Unless you are still using the same 10 year old PC it shouldn't have been that bad! I certainly don't find it any slower than most large apps these days. > Why not stick with pythonwin, it's perfectly adequate for my needs? For a beginner to python I tend to agree with you. Not because Eclipse is slow but because it's way over powered for the simple programs beginners write. If you want to develop a large application with dozens/hundreds of files and packages on Windows then Eclipse (or Netbeans etc) is a useful tool to have. And if you need to develop code in many different languages again, Eclipse will provide consistency. And if you need to build design models in UML you get a choice of top-end tools. But, for single-file programs Pythonwin and even IDLE are perfectly adequate. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ------------------------------ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor End of Tutor Digest, Vol 97, Issue 41 ************************************* -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Fri Mar 16 15:44:34 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 16 Mar 2012 10:44:34 -0400 Subject: [Tutor] stuck on null values In-Reply-To: References: Message-ID: On Thu, Mar 15, 2012 at 5:45 PM, ADRIAN KELLY wrote: > > > > Adrian Kelly > 1 Bramble Close > Baylough > Athlone > County Westmeath > > 0879495663 > > >> Date: Thu, 15 Mar 2012 17:38:52 -0400 >> Subject: Re: [Tutor] stuck on null values >> From: joel.goldstick at gmail.com >> To: kellyadrian at hotmail.com >> CC: tutor at python.org > >> >> On Thu, Mar 15, 2012 at 5:24 PM, ADRIAN KELLY >> wrote: >> > Please can anyone tell me how to solve the problem i am having here, i >> > am >> > trying to loop if the value is left blank by the user >> > but how can i then use the value and multiply it. ?e.g. while >> > number_child==""............ i want to multiply the input i >> > get.........??? >> > >> > def main(): >> > ? ? print """ >> > ________________________________________________________ >> > >> > ? ? ? ? ? ? ? ? Welcome to the Travel Kiosk >> > ________________________________________________________ >> > """ >> > >> > ? ? adult=15 >> > ? ? child=5 >> > ? ? firstname=raw_input("Please enter your firstname: ") >> > ? ? lastname=raw_input ("Please enter your lastname: ") >> > ? ? number_child=raw_input("Enter the number of kids: ") >> > ? ? number_adults=raw_input("Enter the number of adults: ") >> > ? ? while number_child=="": >> > ? ? ? ? number_child=raw_input("Enter the number of kids: ") >> > ? ? price=child*number_child >> > >> > >> > ? ? print """ >> > _______________________________________________________ >> > >> > Thank you, the Price will be: """,price >> > ? ? print""" >> > _______________________________________________________ >> > """ >> > >> > main() >> > >> > >> > >> > >> > >> > >> > Adrian Kelly >> > 1 Bramble Close >> > Baylough >> > Athlone >> > County Westmeath >> > >> > 0879495663 >> > >> > _______________________________________________ >> > Tutor maillist ?- ?Tutor at python.org >> > To unsubscribe or change subscription options: >> > http://mail.python.org/mailman/listinfo/tutor >> > >> raw_input returns the values the user types as a string. In python if >> you have 3 * 'bob' the result will be "bobbobbob" >> >> So you need to turn the number_child into a number like so: >> int(number_child) >> >> You will need to do the same thing for the number of adults. >> >> That will get you started, but if your user types in something that >> isn't a number, your program will fail. See if you can get it to work >> for good data and then come back with what happens when you type in >> other than integers. >> >> Also, when your program fails, it prints out what is called a >> traceback. When you get this situation, be sure to post the traceback >> with your problem. It helps figure out what went wrong >> >> >> -- >> Joel Goldstick > > ............................................................................................................... > adrian replied, > i tried it with integers earlier and then i couldn't use while > number_children=="": > > First, don't reply to the last responder. Reply to the list Take a look at this: while True: num = raw_input("give me an integer: ") try: n = int(num) break except: print "Sorry, that wasn't and integer!" pass While True will keep doing forever the block underneath it try: is how python checks to see if something causes an except. An exception is something that isn't what you want to have happen for your code to continue happily if n can't be converted to an int, it raises an exception, and immediately jumps to the code at 'except: However, if n=int(num) is happy, break happens which will get you out of the while True loop -- Joel Goldstick From glez_b at comunidad.unam.mx Fri Mar 16 19:52:19 2012 From: glez_b at comunidad.unam.mx (Boris Vladimir Comi) Date: Fri, 16 Mar 2012 18:52:19 +0000 Subject: [Tutor] Help for to do a script Message-ID: Hello, I am writing to request your help in the realization of a script. I am new to this and I'm just learning the wonderful world of python and this has made me a little difficult. Briefly I commented what I intend to do: I detect a class of atmospheric phenomena known as Mesoscale Convective Systems (MCS). To accomplish this, I have a database of satellites by 2004, every half hour. These data were downloaded from the server: unidata2.ssec.wisc.edu and data format is: 200404271515.goes12ir (Area Format) The first thing to do is detect a convective system in the satellite data, using the following characteristics: MCS Criteria Minimum Size: Continuous cold cloud shield (TIR <219 K and Must Have an area> 34000 km ?) Duration: Definition of Minimum Size Must Be A Period of Exceed or ? 3h Initiation: Time When the Minimum Size is met Maximum Extention: Time when the continuous cloud shield (TIR <219 K) is at its maximum size Termination: When the Time Minimun Size is not satisfied where: Temperature Infrarred is TIR To achieve this, first I created a script in python to identify a MCS in my database (script in attached) The script is run from a linux terminal ($ python TIR.py), to run it I get the following error: File "/home/mcidasv/JYTHON/TIR.py", line 22 count = count + 1; ^ SyntaxError: invalid syntax If anyone can help me with this script or any idea you suggest to improve it, I would greatly appreciate. Boris Vladimir Comi Gonzalez Universidad Nacional Aut?noma de M?xico Grupo de Tormentas Convecivas -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: TIR.py Type: text/x-python Size: 848 bytes Desc: not available URL: From joel.goldstick at gmail.com Fri Mar 16 19:58:44 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 16 Mar 2012 14:58:44 -0400 Subject: [Tutor] Help for to do a script In-Reply-To: References: Message-ID: On Fri, Mar 16, 2012 at 2:52 PM, Boris Vladimir Comi wrote: > Hello, I am writing to request your help in the realization of a script. I > am new to this and I'm just learning the wonderful world of python and this > has made me a little difficult. > > Briefly I commented what I intend to do: > > I detect a class of atmospheric phenomena known as Mesoscale Convective > Systems (MCS). To accomplish this, I have a database of satellites by 2004, > every half hour. These data were downloaded from the server: > unidata2.ssec.wisc.edu and data format is: 200404271515.goes12ir (Area > Format) > > The first thing to do is detect a convective system in the satellite data, > using the following characteristics: > > MCS Criteria > > Minimum Size: Continuous cold cloud shield (TIR <219 K and Must Have an > area> 34000 km ?) > > Duration: Definition of Minimum Size Must Be A Period of Exceed or ? 3h > > Initiation: Time When the Minimum Size is met > > Maximum Extention: Time when the continuous cloud shield (TIR <219 K) is at > its maximum size > > Termination: When the Time Minimun Size is not satisfied > > where: Temperature Infrarred is TIR > > To achieve this, first I created a script in python to identify a MCS in my > database (script in attached) > > The script is run from a linux terminal ($ python TIR.py), to run it I get > the following error: > > > File "/home/mcidasv/JYTHON/TIR.py", line 22 > ??? count = count + 1; > ??????? ^ > SyntaxError: invalid syntax > > If anyone can help me with this script or any idea you suggest to improve > it, I would greatly appreciate. > > > > Boris Vladimir Comi Gonzalez > Universidad Nacional Aut?noma de M?xico > Grupo de Tormentas Convecivas > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Here is your code: for i in xrange(ad.getLines()): for j in xrange(ad.getElements()): if (data[0][i][j] > 199.5 and (data[0][i][j] < 200.5 count = count + 1; print "For file",name," count = ",count Notice that this line is broken: if (data[0][i][j] > 199.5 and (data[0][i][j] < 200.5 change it to this and try running again: if (data[0][i][j] > 199.5) and (data[0][i][j] < 200.5) -- Joel Goldstick From joel.goldstick at gmail.com Fri Mar 16 19:59:45 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 16 Mar 2012 14:59:45 -0400 Subject: [Tutor] Help for to do a script In-Reply-To: References: Message-ID: On Fri, Mar 16, 2012 at 2:58 PM, Joel Goldstick wrote: > On Fri, Mar 16, 2012 at 2:52 PM, Boris Vladimir Comi > wrote: >> Hello, I am writing to request your help in the realization of a script. I >> am new to this and I'm just learning the wonderful world of python and this >> has made me a little difficult. >> >> Briefly I commented what I intend to do: >> >> I detect a class of atmospheric phenomena known as Mesoscale Convective >> Systems (MCS). To accomplish this, I have a database of satellites by 2004, >> every half hour. These data were downloaded from the server: >> unidata2.ssec.wisc.edu and data format is: 200404271515.goes12ir (Area >> Format) >> >> The first thing to do is detect a convective system in the satellite data, >> using the following characteristics: >> >> MCS Criteria >> >> Minimum Size: Continuous cold cloud shield (TIR <219 K and Must Have an >> area> 34000 km ?) >> >> Duration: Definition of Minimum Size Must Be A Period of Exceed or ? 3h >> >> Initiation: Time When the Minimum Size is met >> >> Maximum Extention: Time when the continuous cloud shield (TIR <219 K) is at >> its maximum size >> >> Termination: When the Time Minimun Size is not satisfied >> >> where: Temperature Infrarred is TIR >> >> To achieve this, first I created a script in python to identify a MCS in my >> database (script in attached) >> >> The script is run from a linux terminal ($ python TIR.py), to run it I get >> the following error: >> >> >> File "/home/mcidasv/JYTHON/TIR.py", line 22 >> ??? count = count + 1; >> ??????? ^ >> SyntaxError: invalid syntax >> >> If anyone can help me with this script or any idea you suggest to improve >> it, I would greatly appreciate. >> >> >> >> Boris Vladimir Comi Gonzalez >> Universidad Nacional Aut?noma de M?xico >> Grupo de Tormentas Convecivas >> >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > Here is your code: > > ? ? for i in xrange(ad.getLines()): > ? ? ? ? ?for j in xrange(ad.getElements()): > ? ? ? ? ? ? ?if (data[0][i][j] > 199.5 and (data[0][i][j] < 200.5 > ? ? ? ? ? ? ? ? ?count = count + 1; > ? ? ?print "For file",name," count = ",count > > Notice that this line is broken: > > ? ? ? ? ? ? ?if (data[0][i][j] > 199.5 and (data[0][i][j] < 200.5 > > change it to this and try running again: > > ? ? ? ? ? ? ?if (data[0][i][j] > 199.5) and (data[0][i][j] < 200.5): > > > -- > Joel Goldstick Sorry, also put : at end of if statements -- Joel Goldstick From alan.gauld at btinternet.com Fri Mar 16 20:02:23 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 16 Mar 2012 19:02:23 +0000 Subject: [Tutor] stuck on null values In-Reply-To: References: Message-ID: On 16/03/12 14:44, Joel Goldstick wrote: > Take a look at this: > > while True: > num = raw_input("give me an integer: ") > try: > n = int(num) > break > except: > print "Sorry, that wasn't and integer!" > pass The pass is redundant it does nothing (thats its purpose! :-) You can also remove the variable n: while True: try: num = int(raw_input("give me an integer: ")) # use num now or keep it for later break except: print "Sorry, that wasn't an integer!" # can also use num here... HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Mar 16 20:07:37 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 16 Mar 2012 19:07:37 +0000 Subject: [Tutor] Help for to do a script In-Reply-To: References: Message-ID: On 16/03/12 18:52, Boris Vladimir Comi wrote: > *File "/home/mcidasv/JYTHON/TIR.py", line 22 > count = count + 1; > ^ > SyntaxError: invalid syntax* Error messages indicate where Python found the problem. Often the real problem is a line or so before that. In your case you omitted the colon after the if statement. Note that Python does not require semi colons at the end of lines. It rarely causes problems but it doesn't help either. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From joel.goldstick at gmail.com Fri Mar 16 20:08:55 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 16 Mar 2012 15:08:55 -0400 Subject: [Tutor] stuck on null values In-Reply-To: References: Message-ID: On Fri, Mar 16, 2012 at 3:02 PM, Alan Gauld wrote: > On 16/03/12 14:44, Joel Goldstick wrote: > >> Take a look at this: >> >> while True: >> ? num = raw_input("give me an integer: ") >> ? try: >> ? ? n = int(num) >> ? ? break >> ? except: >> ? ? print "Sorry, that wasn't and integer!" >> ? ? pass > > > > The pass is redundant it does nothing (thats its purpose! :-) > You can also remove the variable n: > > while True: > ? ?try: > ? ? ? num = int(raw_input("give me an integer: ")) > ? ? ? # use num now or keep it for later > ? ? ? break > ? ?except: > ? ? ?print "Sorry, that wasn't an integer!" > > # can also use num here... > > > HTH > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > Good Catch! I originally had the pass in alone, but then decided to give a helpful message. Didn't remove the pass > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- Joel Goldstick From lmergner at gmail.com Sat Mar 17 00:48:05 2012 From: lmergner at gmail.com (Luke Thomas Mergner) Date: Fri, 16 Mar 2012 19:48:05 -0400 Subject: [Tutor] Datetime objects Message-ID: <68A54AB8-3490-48B9-B099-78AE6ABF5F06@gmail.com> Hi, I am having trouble comparing two datetime objects. Using Sqlalchemy I save a string as a date into an sqlite field (which has no native date format, I gather). > import datetime as dt > date_obj = dt.datetime.strptime(date_string,'%m.%d.%Y') I want to compare that date later with an inputed date, which I created with strptime(). This function is only available for datetime.datetime.strptime() not datetime.date > >>> compare_date = dt.datetime.strptime('2011-01-27', '%Y-%m-%d') > >>> print compare_date > datetime.datetime(2012, 1, 27, 0, 0) Despite the fact that I don't care about the time fields, they still get added. It appears that I can get at the date object returned in an sqlalchemy object: > >>> for row in query_object: > ... type(row.date) > ... > 2012-03-16 19:18:18,420 INFO sqlalchemy.engine.base.Engine SELECT posts.date AS posts_date > FROM posts > 2012-03-16 19:18:18,420 INFO sqlalchemy.engine.base.Engine () > > > But when I compare them, it always returns false because datetime.date does not seem to compare to datetime.datetime... > >>> for row in q1: > ... print type (row.date), row.date, ' vs ', type(compare_date), compare_date, row.date == compare_date > ... > 2012-03-16 19:33:56,011 INFO sqlalchemy.engine.base.Engine SELECT posts.date AS posts_date > FROM posts > 2012-03-16 19:33:56,011 INFO sqlalchemy.engine.base.Engine () > 2011-11-05 vs 2012-01-27 00:00:00 False > 2011-11-29 vs 2012-01-27 00:00:00 False > 2011-12-23 vs 2012-01-27 00:00:00 False > 2012-01-18 vs 2012-01-27 00:00:00 False > 2012-01-17 vs 2012-01-27 00:00:00 False > 2012-01-27 vs 2012-01-27 00:00:00 False > 2012-01-14 vs 2012-01-27 00:00:00 False Can anyone help me out here? Thanks in advance. PS: I'm asking here since I think this is a simple object comparison question, not a question specific to a library (sqlalchemy). If it matters, I'm playing around with a small web log application built on Werkzeug, Sqlalchemy, and Jinja2. I'm actually very impressed with the progress I've made. Luke Mergner Mechanicsville, MD lmergner at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sat Mar 17 01:08:47 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 17 Mar 2012 11:08:47 +1100 Subject: [Tutor] Datetime objects In-Reply-To: <68A54AB8-3490-48B9-B099-78AE6ABF5F06@gmail.com> References: <68A54AB8-3490-48B9-B099-78AE6ABF5F06@gmail.com> Message-ID: <4F63D60F.4090404@pearwood.info> Luke Thomas Mergner wrote: > Hi, > > I am having trouble comparing two datetime objects. No you're not. You're having trouble comparing a datetime and a date object. [...] > But when I compare them, it always returns false because datetime.date does > not seem to compare to datetime.datetime... Use date_obj.date() to return a date object without the times, then compare that to the date objects sqlalchemy gives you. -- Steven From dave6502 at gmail.com Sat Mar 17 12:55:42 2012 From: dave6502 at gmail.com (dave selby) Date: Sat, 17 Mar 2012 11:55:42 +0000 Subject: [Tutor] Trying to send a cursor down key press string to a device Message-ID: HI, I have an attatched mymobiler device which I can send string to, I need to send a cursor down command but am having problems, I need to send ... 224 followed by 80 I found this by monitering msvcrt.getch() However I do not know how to construct this, chr(224) + chr(80) returns a loud bleep from my mymobiler device instead of moving the highlighte down one line Any ideas Cheers Dave -- Please avoid sending me Word or PowerPoint attachments. See http://www.gnu.org/philosophy/no-word-attachments.html From alan.gauld at btinternet.com Sat Mar 17 15:05:29 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 17 Mar 2012 14:05:29 +0000 Subject: [Tutor] Trying to send a cursor down key press string to a device In-Reply-To: References: Message-ID: On 17/03/12 11:55, dave selby wrote: > I have an attatched mymobiler device which I can send string to, I > need to send a cursor down command but am having problems, I have no idea what a mymobiler device is, nor how you would go about using Python with it. > I need to send ... 224 followed by 80 I found this by monitering msvcrt.getch() So send 224 followed by 80? Or maybe construct a byte string using the struct module and send that? > However I do not know how to construct this, chr(224) + chr(80) > returns a loud bleep from my mymobiler device instead of moving the > highlighte down one line Given we have no idea what you are doing to "send" the data we can only make wild guesses as to what might be happening. It might help if you posted on a mymobiler specific forum? Or maybe the main python list, since this is not really about learning Python, more about learning how to communicate with your device. But as a minimum, provide a lot more context and at least some code. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From pedrooconnell at gmail.com Sun Mar 18 12:19:58 2012 From: pedrooconnell at gmail.com (Pete O'Connell) Date: Mon, 19 Mar 2012 00:19:58 +1300 Subject: [Tutor] commands.getoutput equivalent in subprocess Message-ID: Hello I print a lot of values at work using grep and need to be constantly opening a shell window to do this (rather than staying within my main program which is Nuke by the Foundry). Is there a simple equilavent to commands.getoutput that is more up to date (I would assume within the subprocess module)? It sounds like the commands module will be phased out soonish. I am using Python 2.6 Here is the kind of thing I would like to do in subprocess import commands output = commands.getoutput("echo Hello World!") print output Thanks Pete From __peter__ at web.de Sun Mar 18 13:23:38 2012 From: __peter__ at web.de (Peter Otten) Date: Sun, 18 Mar 2012 13:23:38 +0100 Subject: [Tutor] commands.getoutput equivalent in subprocess References: Message-ID: Pete O'Connell wrote: > Hello I print a lot of values at work using grep and need to be > constantly opening a shell window to do this (rather than staying > within my main program which is Nuke by the Foundry). Is there a > simple equilavent to commands.getoutput that is more up to date (I > would assume within the subprocess module)? It sounds like the > commands module will be phased out soonish. I am using Python 2.6 > > Here is the kind of thing I would like to do in subprocess > > import commands > output = commands.getoutput("echo Hello World!") > print output Here's the equivalent for Python 3: >>> import subprocess >>> output = subprocess.getoutput("echo Hello World!") >>> print(output) Hello World! >>> ;) For invoking external programs you should still consider something more involved like >>> p = subprocess.Popen(["grep", "^def\s", "/usr/lib/python3.2/subprocess.py"], stdout=subprocess.PIPE) >>> print(p.communicate()[0].decode("utf-8")) def _cleanup(): def _eintr_retry_call(func, *args): def call(*popenargs, **kwargs): def check_call(*popenargs, **kwargs): def check_output(*popenargs, **kwargs): def list2cmdline(seq): def getstatusoutput(cmd): def getoutput(cmd): def _demo_posix(): def _demo_windows(): From dcdavemail at gmail.com Sun Mar 18 16:05:44 2012 From: dcdavemail at gmail.com (David Craig) Date: Sun, 18 Mar 2012 15:05:44 +0000 Subject: [Tutor] wave equation boundary conditions Message-ID: Hi, I have written some code which solve's the 2d wave equation (code is below). It seems to work, however when the wave reaches the boundaries it reflects off them and I would like to remove this effect. Does anyone know of a method to do this? Also, I would like to run it over a large area, but when I do the images take a long time to render (I've tried saving them as .png files instead, which is a bit faster) so if anyone has any suggestions how I can improve this I'd appreciate it. Thanks in advance, D import matplotlib.pyplot as plt import numpy as np import pylab as py from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm pi = np.pi #Set up grid. fig = py.figure() ax = Axes3D(fig) nx = 10 nz = 10 X = np.arange(0, nx, 1) Y = np.arange(0, nz, 1) X, Y = np.meshgrid(X, Y) nsteps = 100 # Constants for equation. c = 4000 dt = 1e-4 h = 1 # Set up source. xs = 0 zs = 0 #fig2 = py.figure() ts = np.arange(dt,nsteps*dt,dt) s = 0.5*np.sin(2*pi*100*ts) #py.plot(ts,s) #py.show() # Homogeneous pressure field. p = np.zeros([nx, nz, nsteps]) # Solve equation. for t in range(0,nsteps-1): for z in range(0,nz-1): for x in range(0,nx-1): p[xs,zs,t] = s[t] k = (c*dt/h)**2 p[x,z,t] = 2*p[x,z,t-1] - p[x,z,t-2] + k*(p[x+1,z,t-1]-4*p[x,z,t-1]+p[x-1,z,t-1]+p[x,z+1,t-1]+p[x,z-1,t-1]) snap = p[:,:,t] surf = ax.plot_surface(X,Y,snap, rstride=1, cstride=1, cmap=cm.jet, linewidth=0) #fig.colorbar(surf, shrink=0.5, aspect=5) py.draw() #py.savefig('/home/davcra/Desktop/plots/2Dwave/'+str(t)) -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Mar 18 20:27:58 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 18 Mar 2012 19:27:58 +0000 Subject: [Tutor] wave equation boundary conditions In-Reply-To: References: Message-ID: On 18/03/12 15:05, David Craig wrote: > Hi, I have written some code which solve's the 2d wave equation (code is > below). It seems to work, however when the wave reaches the boundaries > it reflects off them and I would like to remove this effect. Does anyone > know of a method to do this? We have a few math bods here so you may well get an answer but you could try gmane.comp.python.numeric.general too, since the question is as much about the algorithm as it is about learning Python. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From Xianming.Yan at intercallapac.com Mon Mar 19 08:38:35 2012 From: Xianming.Yan at intercallapac.com (Yan, Xianming) Date: Mon, 19 Mar 2012 18:38:35 +1100 Subject: [Tutor] Any book to study Python In-Reply-To: References: Message-ID: Hello all, I'm a new learning to python and does not know python anything at all. Anyone can recommend a book about python to read? I prefer a paper-based book, not online book. By the way, I'm from china, I hope the book is Chinese--:)--Reading in Chinese is quicker~:) Thanks Xianming From wescpy at gmail.com Mon Mar 19 09:20:43 2012 From: wescpy at gmail.com (wesley chun) Date: Mon, 19 Mar 2012 01:20:43 -0700 Subject: [Tutor] Any book to study Python In-Reply-To: References: Message-ID: ?? Xianming, I have a book -- *Python ? ? ? ? (???)* -- that is for people who already program but want to learn Python. It is available in China from at least 3 online stores: http://www.china-pub.com/39969 http://www.amazon.cn/dp/bkbk835890 http://mall.sina.com.cn/product_1749023.htm In the Amazon comments, it looks like there are critical replies about the translator. Since I cannot read Chinese, I don't know about the book's quality or translation accuracy because I write with American English, so you should do some research to see if it is a good book. To compare, the English one is at http://amzn.com/0132269937 Good luck! --Wesley - ??? (???) On Mon, Mar 19, 2012 at 12:38 AM, Yan, Xianming < Xianming.Yan at intercallapac.com> wrote: > Hello all, > > I'm a new learning to python and does not know python anything at all. > > Anyone can recommend a book about python to read? I prefer a paper-based > book, not online book. > > By the way, I'm from china, I hope the book is Chinese--:)--Reading in > Chinese is quicker~:) > > Thanks > Xianming > -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.chun : wescpy-gmail.com : @wescpy/+wescpy python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From Xianming.Yan at intercallapac.com Mon Mar 19 09:28:21 2012 From: Xianming.Yan at intercallapac.com (Yan, Xianming) Date: Mon, 19 Mar 2012 19:28:21 +1100 Subject: [Tutor] =?utf-8?b?562U5aSNOiAgQW55IGJvb2sgdG8gc3R1ZHkgUHl0aG9u?= In-Reply-To: References: Message-ID: Hello Wesley, Thanks for your reply. Yes, I saw this book in www.dangdang.com and just want to buy it. But there are a lot of critics about the translation. So I?m still researching with it. Hopefully I can find a very classical book for python and take me into its programming world. Thanks for your reply. Thanks Xianming ???: wesley chun [mailto:wescpy at gmail.com] ????: 2012?3?19? 16:21 ???: Yan, Xianming ??: tutor at python.org ??: Re: [Tutor] Any book to study Python ?? Xianming, I have a book -- Python ? ? ? ? (???) -- that is for people who already program but want to learn Python. It is available in China from at least 3 online stores: http://www.china-pub.com/39969 http://www.amazon.cn/dp/bkbk835890 http://mall.sina.com.cn/product_1749023.htm In the Amazon comments, it looks like there are critical replies about the translator. Since I cannot read Chinese, I don't know about the book's quality or translation accuracy because I write with American English, so you should do some research to see if it is a good book. To compare, the English one is at http://amzn.com/0132269937 Good luck! --Wesley - ??? (???) On Mon, Mar 19, 2012 at 12:38 AM, Yan, Xianming > wrote: Hello all, I'm a new learning to python and does not know python anything at all. Anyone can recommend a book about python to read? I prefer a paper-based book, not online book. By the way, I'm from china, I hope the book is Chinese--:)--Reading in Chinese is quicker~:) Thanks Xianming -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.chun : wescpy-gmail.com : @wescpy/+wescpy python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Mar 19 09:30:32 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 19 Mar 2012 08:30:32 +0000 Subject: [Tutor] Any book to study Python In-Reply-To: References: Message-ID: On 19/03/12 07:38, Yan, Xianming wrote: > Hello all, > > I'm a new learning to python and does not know python anything at all. > > Anyone can recommend a book about python to read? I prefer a paper-based book, not online book. > > By the way, I'm from china, I hope the book is Chinese--:)--Reading in Chinese is quicker~:) My book is aimed at complete beginners but is a little out of date now being based on Python v1.5. But it was available briefly in Chinese so you might be able to find a copy. It is still available in Japanese although that probably doesn't help much! Here is the url: http://www.alan-g.me.uk/book/index.htm Or on Amazon: http://www.amazon.com/Learn-Program-Using-Python-Self-Starters/dp/0201709384/ref=sr_1_1?ie=UTF8&qid=1332145741&sr=8-1 It is also available in a greatly expanded and up to date version online at the url below. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From __peter__ at web.de Mon Mar 19 10:01:42 2012 From: __peter__ at web.de (Peter Otten) Date: Mon, 19 Mar 2012 10:01:42 +0100 Subject: [Tutor] commands.getoutput equivalent in subprocess References: Message-ID: > Pete O'Connell wrote: > Hi, I am using Python 2.6 I can't use Python 3 in this particular situation. [Please reply to the list, not in private mail.] You can continue to use commands.getoutput() in 2.6 and 2.7, and once you are ready to make the jump to 3.x replace it with subprocess.getoutput(). From Xianming.Yan at intercallapac.com Mon Mar 19 10:39:44 2012 From: Xianming.Yan at intercallapac.com (Yan, Xianming) Date: Mon, 19 Mar 2012 20:39:44 +1100 Subject: [Tutor] Any book to study Python References: Message-ID: I'm following http://docs.python.org/tutorial/interpreter.html to type in the first script into python. According to the link, I typed below: >>> the_world_is_flat = 1 >>> if the_world_is_flat: ... print "Be careful not to fall off!" Then I get below output: File "", line1 Print "dd" ^ IndentationError:expected an indented block This is incorrect. According to the book, I should get: Be careful not to fall off! Anyone can tell me where the problem is or any suggestion about it? Thanks Xianming From Xianming.Yan at intercallapac.com Mon Mar 19 10:40:59 2012 From: Xianming.Yan at intercallapac.com (Yan, Xianming) Date: Mon, 19 Mar 2012 20:40:59 +1100 Subject: [Tutor] =?gb2312?b?tPC4tDogQW55IGJvb2sgdG8gc3R1ZHkgUHl0aG9u?= References: Message-ID: I guess I solved the problem. I should type in some space before the print "dd" statement. Sorry for disturbing you if the e-mail. Thanks Xianming -----????----- ???: Yan, Xianming ????: 2012?3?19? 17:40 ???: 'tutor at python.org' ??: Any book to study Python I'm following http://docs.python.org/tutorial/interpreter.html to type in the first script into python. According to the link, I typed below: >>> the_world_is_flat = 1 >>> if the_world_is_flat: ... print "Be careful not to fall off!" Then I get below output: File "", line1 Print "dd" ^ IndentationError:expected an indented block This is incorrect. According to the book, I should get: Be careful not to fall off! Anyone can tell me where the problem is or any suggestion about it? Thanks Xianming From pedrooconnell at gmail.com Mon Mar 19 11:58:37 2012 From: pedrooconnell at gmail.com (Pete O'Connell) Date: Mon, 19 Mar 2012 23:58:37 +1300 Subject: [Tutor] commands.getoutput equivalent in subprocess In-Reply-To: References: Message-ID: Ok thanks a lot. Pete On Mon, Mar 19, 2012 at 10:01 PM, Peter Otten <__peter__ at web.de> wrote: >> Pete O'Connell wrote: > >> Hi, I am using Python 2.6 I can't use Python 3 in this particular > situation. > > [Please reply to the list, not in private mail.] > > You can continue to use commands.getoutput() in 2.6 and 2.7, and once you > are ready to make the jump to 3.x replace it with subprocess.getoutput(). > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- Pete From brian.van.den.broek at gmail.com Mon Mar 19 14:40:40 2012 From: brian.van.den.broek at gmail.com (Brian van den Broek) Date: Mon, 19 Mar 2012 15:40:40 +0200 Subject: [Tutor] Any book to study Python In-Reply-To: References: Message-ID: On 19 Mar 2012 11:42, "Yan, Xianming" wrote: > > I'm following http://docs.python.org/tutorial/interpreter.html to type in the first script into python. > > According to the link, I typed below: > > >>> the_world_is_flat = 1 > >>> if the_world_is_flat: > ... print "Be careful not to fall off!" > > Then I get below output: > File "", line1 > Print "dd" > ^ > IndentationError:expected an indented block Xianming, I see you solved your problem; I am glad. But, a comment for future messages: Be sure to copy and paste (as in, do not retype) your code and any output that *that* code produces. The code you show cannot have produced the output you show. If you retype or mix and match code and output, you make it harder to help! Best wishes, Brian vdB -------------- next part -------------- An HTML attachment was scrubbed... URL: From suryak at live.com Mon Mar 19 15:30:20 2012 From: suryak at live.com (Surya K) Date: Mon, 19 Mar 2012 20:00:20 +0530 Subject: [Tutor] Unable to open .py files directly Message-ID: Hi there, I am facing a typical problem in opening .py files by clicking them (In windows). When ever I those files, there's a black window opening and closing immediately (I think, its output of python at python command line, NOT SURE). I have to open those files from IDE's or any test editors. I tried to fix it in 'default programs' list, but I just didn't find any problem there.. I use PyScripter IDE. I think, this is making trouble (don't know how). actually, this problem has occurred after installing it.(I use Win7) How do I fix it. -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Mon Mar 19 16:06:50 2012 From: emile at fenx.com (Emile van Sebille) Date: Mon, 19 Mar 2012 08:06:50 -0700 Subject: [Tutor] Unable to open .py files directly In-Reply-To: References: Message-ID: On 3/19/2012 7:30 AM Surya K said... > Hi there, > > I am facing a typical problem in opening .py files by clicking them (In > windows). > > When ever I those files, there's a black window opening and closing > immediately (I think, its output of python at python command line, NOT > SURE). I have to open those files from IDE's or any test editors. > > I tried to fix it in 'default programs' list, but I just didn't find any > problem there.. > > > > I use PyScripter IDE. I think, this is making trouble (don't know how). > actually, this problem has occurred after installing it. > (I use Win7) > > How do I fix it. > You need to set the registered file type extension handler properly in windows. For XP it's in Control Panel, Folder Options, File Types. I'm not sure for win7. Alternately, just install activestate python from http://www.activestate.com/activepython/downloads It will get you all the windows related support you're likely to want in a single installation. HTH, Emile From alan.gauld at btinternet.com Mon Mar 19 18:56:06 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 19 Mar 2012 17:56:06 +0000 Subject: [Tutor] Unable to open .py files directly In-Reply-To: References: Message-ID: On 19/03/12 14:30, Surya K wrote: > Hi there, > > I am facing a typical problem in opening .py files by clicking them (In > windows). > > When ever I those files, there's a black window opening and closing > immediately (I think, its output of python at python command line, NOT > SURE). I have to open those files from IDE's or any test editors. The simplest solution is just to add a line like: Python 2.x: raw_input("Hit any key to quit...") Python 3.x raw_input("Hit any key to quit...") There are various other options. They are discussed in my tutor in the "Add a little style" topic near the bottom. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Mar 19 20:23:08 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 19 Mar 2012 19:23:08 +0000 Subject: [Tutor] Unable to open .py files directly In-Reply-To: References: Message-ID: On 19/03/12 17:56, Alan Gauld wrote: > Python 3.x > > raw_input("Hit any key to quit...") oops. Should be: input("Hit any key to quit...") -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From russel at winder.org.uk Mon Mar 19 21:09:21 2012 From: russel at winder.org.uk (Russel Winder) Date: Mon, 19 Mar 2012 20:09:21 +0000 Subject: [Tutor] Any book to study Python In-Reply-To: References: Message-ID: <1332187761.11058.101.camel@launcelot.russel.org.uk> Xianming, On Mon, 2012-03-19 at 18:38 +1100, Yan, Xianming wrote: > Hello all, > > I'm a new learning to python and does not know python anything at all. > > Anyone can recommend a book about python to read? I prefer a paper-based book, not online book. > > By the way, I'm from china, I hope the book is Chinese--:)--Reading in Chinese is quicker~:) > > Thanks > Xianming The book Sarah Mount, James Shuttleworth and I wrote "Python for Rookies" is a book aimed to teach people who are not already programmers programming using Python. Not been translated to Chinese yet as far as I know. The book is Python 2.4/2.5, we are currently trying to work with the publisher to get out a new edition that can be Python 2.7/3.2. -- Russel. ============================================================================= Dr Russel Winder t: +44 20 7585 2200 voip: sip:russel.winder at ekiga.net 41 Buckmaster Road m: +44 7770 465 077 xmpp: russel at winder.org.uk London SW11 1EN, UK w: www.russel.org.uk skype: russel_winder -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 198 bytes Desc: This is a digitally signed message part URL: From bgailer at gmail.com Tue Mar 20 00:11:18 2012 From: bgailer at gmail.com (bob gailer) Date: Mon, 19 Mar 2012 19:11:18 -0400 Subject: [Tutor] Unable to open .py files directly In-Reply-To: References: Message-ID: <4F67BD16.3010303@gmail.com> On 3/19/2012 10:30 AM, Surya K wrote: > Hi there, > > I am facing a typical problem in opening .py files by clicking them > (In windows). In addition to the other advice - "open" is ambiguous. What do you want to happen? Edit or execute? clicking a file usually just selects it. Do you mean double-click or what? The more precise you are regarding what you want and what you do makes it a lot easier for us to help. -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From Xianming.Yan at intercallapac.com Tue Mar 20 02:36:09 2012 From: Xianming.Yan at intercallapac.com (Yan, Xianming) Date: Tue, 20 Mar 2012 12:36:09 +1100 Subject: [Tutor] =?utf-8?b?562U5aSNOiAgQW55IGJvb2sgdG8gc3R1ZHkgUHl0aG9u?= In-Reply-To: <1332187761.11058.101.camel@launcelot.russel.org.uk> References: <1332187761.11058.101.camel@launcelot.russel.org.uk> Message-ID: Hello Russel, Thanks for your recommendation and reply. I've bought the book named Python ? ? ? ? (???) on www.dangdang.com. I guess I can get the book today. To Wesley, I did not realize you are the author of Python ? ? ? ? (???) until I read the book's note online carefully and found your name. It's very exciting! You know this is the first time in my life that the book's author e-mail me. After I get it I shall start to read in my weekend and if there is any questions I shall write e-mail to you. Thanks again! And to Brian vdB, I have my job need to do on windows platforms, and I installed python on a linux virtual machine hosted on my PC, so I can't copy/paste the code here. But it is a very good point that install the python interepter on Windows platform and copy/paste the code in the command line to run it directly, this will avoid some type error. Thanks for your suggestion!. Thanks Xianming -----????----- ???: Russel Winder [mailto:russel at winder.org.uk] ????: 2012?3?20? 4:09 ???: Yan, Xianming ??: tutor at python.org; Sarah Mount; James Shuttleworth ??: Re: [Tutor] Any book to study Python Xianming, On Mon, 2012-03-19 at 18:38 +1100, Yan, Xianming wrote: > Hello all, > > I'm a new learning to python and does not know python anything at all. > > Anyone can recommend a book about python to read? I prefer a paper-based book, not online book. > > By the way, I'm from china, I hope the book is Chinese--:)--Reading in > Chinese is quicker~:) > > Thanks > Xianming The book Sarah Mount, James Shuttleworth and I wrote "Python for Rookies" is a book aimed to teach people who are not already programmers programming using Python. Not been translated to Chinese yet as far as I know. The book is Python 2.4/2.5, we are currently trying to work with the publisher to get out a new edition that can be Python 2.7/3.2. -- Russel. ============================================================================= Dr Russel Winder t: +44 20 7585 2200 voip: sip:russel.winder at ekiga.net 41 Buckmaster Road m: +44 7770 465 077 xmpp: russel at winder.org.uk London SW11 1EN, UK w: www.russel.org.uk skype: russel_winder From leamhall at gmail.com Tue Mar 20 02:44:58 2012 From: leamhall at gmail.com (Leam Hall) Date: Mon, 19 Mar 2012 21:44:58 -0400 Subject: [Tutor] =?utf-8?b?562U5aSNOiAgQW55IGJvb2sgdG8gc3R1ZHkgUHl0aG9u?= In-Reply-To: References: <1332187761.11058.101.camel@launcelot.russel.org.uk> Message-ID: <4F67E11A.2070508@gmail.com> On 03/19/2012 09:36 PM, Yan, Xianming wrote: > Hello Russel, > > Thanks for your recommendation and reply. ... Xianming, Wesley is a great help here as is Alan Gauld. One of the things I really like about the Python language is the experts who still help us new programmers. Leam From d at davea.name Tue Mar 20 03:05:03 2012 From: d at davea.name (Dave Angel) Date: Mon, 19 Mar 2012 22:05:03 -0400 Subject: [Tutor] =?utf-8?b?562U5aSNOiAgQW55IGJvb2sgdG8gc3R1ZHkgUHl0aG9u?= In-Reply-To: References: <1332187761.11058.101.camel@launcelot.russel.org.uk> Message-ID: <4F67E5CF.3030401@davea.name> On 03/19/2012 09:36 PM, Yan, Xianming wrote: > > And to Brian vdB, I have my job need to do on windows platforms, and I installed python on a linux virtual machine hosted on my PC, so I can't copy/paste the code here. But it is a very good point that install the python interepter on Windows platform and copy/paste the code in the command line to run it directly, this will avoid some type error. Thanks for your suggestion!. > On this, and most forums, it's good form to put your comments *after* the part you're quoting. What you did is called top-posting, and it makes the sequence out-of-order. But the real reason i'm responding is to suggest that you can certainly cut and paste between virtual machine and host. If you cannot on your particular setup, you should get it fixed. If that's not feasible, you can always share files between the two, and do your copy/paste that way. It's hard to imagine not having such capabilities. -- DaveA From wescpy at gmail.com Tue Mar 20 06:09:37 2012 From: wescpy at gmail.com (wesley chun) Date: Mon, 19 Mar 2012 22:09:37 -0700 Subject: [Tutor] =?gb2312?b?tPC4tDogIEFueSBib29rIHRvIHN0dWR5IFB5dGhvbg==?= In-Reply-To: References: <1332187761.11058.101.camel@launcelot.russel.org.uk> Message-ID: On Mon, Mar 19, 2012 at 6:36 PM, Yan, Xianming < Xianming.Yan at intercallapac.com> wrote: > > I've bought the book named Python ? ? ? ? (???) on www.dangdang.com. I > guess I can get the book today. > > To Wesley, I did not realize you are the author of Python ? ? ? ? (???) > until I read the book's note online carefully and found your name. It's > very exciting! You know this is the first time in my life that the book's > author e-mail me. After I get it I shall start to read in my weekend and if > there is any questions I shall write e-mail to you. Thanks again! > hi xian-ming, i'm replying here to address dave angel's comment to reply *after* the email (this is called "bottom-posting" so that people here can see what your issue and context are. many people normally "top-post" or reply at the beginning, but it is not as easy to read this when communicating in a technical forum like this. i can even remove the parts of your message which i am not responding to (like i did above). about Python ? ? ? ? (???) and my participation, thanks to you and Leam for your kind remarks, however i am a Python user just like everyone else here... the only difference is that i started using Python in 1997 which gives me more experience. :-) i'm also a crazy engineer that is also interested in *documentation* -- i know, i'm losing my reputation as a developer now. 8| i hope that the criticisms of the translator can be minimized (just watch out for the bad code indentation), and that they were able to interpret what i really wanted to say, otherwise you may have to find the English one. i try to use easy-to-understand English, so it should not be *too* bad. anyway, if you have more questions, please cut-n-paste your code here along with the output, and everyone can help you more effectively. ??! -- wesley - ??? - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "A computer never does what you want... only what you tell it." wesley chun : wescpy at gmail : @wescpy / +wescpy Python training & consulting : CyberwebConsulting.com "Core Python" books : CorePython.com Python-flavored blog: wescpy.blogspot.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From Xianming.Yan at intercallapac.com Tue Mar 20 06:28:41 2012 From: Xianming.Yan at intercallapac.com (Yan, Xianming) Date: Tue, 20 Mar 2012 16:28:41 +1100 Subject: [Tutor] =?gb2312?b?tPC4tDogtPC4tDogIEFueSBib29rIHRvIHN0dWR5IFB5?= =?gb2312?b?dGhvbg==?= In-Reply-To: References: <1332187761.11058.101.camel@launcelot.russel.org.uk> Message-ID: Okay, got it. Thanks for your suggestion! Thanks Xianming ???: wesley chun [mailto:wescpy at gmail.com] ????: 2012?3?20? 13:10 ???: Yan, Xianming ??: Russel Winder; Brian van den Broek; tutor at python.org; Sarah Mount; James Shuttleworth ??: Re: ??: [Tutor] Any book to study Python On Mon, Mar 19, 2012 at 6:36 PM, Yan, Xianming > wrote: I've bought the book named Python ? ? ? ? (???) on www.dangdang.com. I guess I can get the book today. To Wesley, I did not realize you are the author of Python ? ? ? ? (???) until I read the book's note online carefully and found your name. It's very exciting! You know this is the first time in my life that the book's author e-mail me. After I get it I shall start to read in my weekend and if there is any questions I shall write e-mail to you. Thanks again! hi xian-ming, i'm replying here to address dave angel's comment to reply *after* the email (this is called "bottom-posting" so that people here can see what your issue and context are. many people normally "top-post" or reply at the beginning, but it is not as easy to read this when communicating in a technical forum like this. i can even remove the parts of your message which i am not responding to (like i did above). about Python ? ? ? ? (???) and my participation, thanks to you and Leam for your kind remarks, however i am a Python user just like everyone else here... the only difference is that i started using Python in 1997 which gives me more experience. :-) i'm also a crazy engineer that is also interested in *documentation* -- i know, i'm losing my reputation as a developer now. 8| i hope that the criticisms of the translator can be minimized (just watch out for the bad code indentation), and that they were able to interpret what i really wanted to say, otherwise you may have to find the English one. i try to use easy-to-understand English, so it should not be *too* bad. anyway, if you have more questions, please cut-n-paste your code here along with the output, and everyone can help you more effectively. ??! -- wesley - ??? - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "A computer never does what you want... only what you tell it." wesley chun : wescpy at gmail : @wescpy/+wescpy Python training & consulting : CyberwebConsulting.com "Core Python" books : CorePython.com Python-flavored blog: wescpy.blogspot.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From suryak at live.com Wed Mar 21 14:00:29 2012 From: suryak at live.com (Surya K) Date: Wed, 21 Mar 2012 18:30:29 +0530 Subject: [Tutor] Unable to open .py files directly In-Reply-To: <4F67BD16.3010303@gmail.com> References: , <4F67BD16.3010303@gmail.com> Message-ID: Date: Mon, 19 Mar 2012 19:11:18 -0400 From: bgailer at gmail.com To: suryak at live.com CC: tutor at python.org Subject: Re: [Tutor] Unable to open .py files directly On 3/19/2012 10:30 AM, Surya K wrote: Hi there, I am facing a typical problem in opening .py files by clicking them (In windows). In addition to the other advice - "open" is ambiguous. What do you want to happen? Edit or execute? clicking a file usually just selects it. Do you mean double-click or what? The more precise you are regarding what you want and what you do makes it a lot easier for us to help. -- Bob Gailer 919-636-4239 Chapel Hill NC I was "double clicking".. and I want to open IDLE. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bodsda at googlemail.com Wed Mar 21 14:29:17 2012 From: bodsda at googlemail.com (Bod Soutar) Date: Wed, 21 Mar 2012 13:29:17 +0000 Subject: [Tutor] Unable to open .py files directly In-Reply-To: References: <4F67BD16.3010303@gmail.com> Message-ID: On Mar 21, 2012 1:03 PM, "Surya K" wrote: > > > > ________________________________ > Date: Mon, 19 Mar 2012 19:11:18 -0400 > From: bgailer at gmail.com > To: suryak at live.com > CC: tutor at python.org > Subject: Re: [Tutor] Unable to open .py files directly > > > On 3/19/2012 10:30 AM, Surya K wrote: >> >> Hi there, >> >> I am facing a typical problem in opening .py files by clicking them (In windows). > > > In addition to the other advice - > > "open" is ambiguous. What do you want to happen? Edit or execute? > > clicking a file usually just selects it. Do you mean double-click or what? > > The more precise you are regarding what you want and what you do makes it a lot easier for us to help. > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC > > > > I was "double clicking".. and I want to open IDLE. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > In that case, you need to change the file association of .py files to IDLE Bodsda -------------- next part -------------- An HTML attachment was scrubbed... URL: From suryak at live.com Wed Mar 21 15:42:29 2012 From: suryak at live.com (Surya K) Date: Wed, 21 Mar 2012 20:12:29 +0530 Subject: [Tutor] Unable to open .py files directly In-Reply-To: References: , <4F67BD16.3010303@gmail.com>, , Message-ID: Date: Wed, 21 Mar 2012 13:29:17 +0000 Subject: Re: [Tutor] Unable to open .py files directly From: bodsda at googlemail.com To: suryak at live.com CC: tutor at python.org; bgailer at gmail.com On Mar 21, 2012 1:03 PM, "Surya K" wrote: > > > > ________________________________ > Date: Mon, 19 Mar 2012 19:11:18 -0400 > From: bgailer at gmail.com > To: suryak at live.com > CC: tutor at python.org > Subject: Re: [Tutor] Unable to open .py files directly > > > On 3/19/2012 10:30 AM, Surya K wrote: >> >> Hi there, >> >> I am facing a typical problem in opening .py files by clicking them (In windows). > > > In addition to the other advice - > > "open" is ambiguous. What do you want to happen? Edit or execute? > > clicking a file usually just selects it. Do you mean double-click or what? > > The more precise you are regarding what you want and what you do makes it a lot easier for us to help. > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC > > > > I was "double clicking".. and I want to open IDLE. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > In that case, you need to change the file association of .py files to IDLE Bodsda Yeah, I tried that. The worst part is we don't have any exe file specifically for IDLE. I mean windows has to choose whether to edit or compile. In my case, the file associated with my .py files is python.exe (c:/python27/python.exe). I still don't understand why its not opening in IDLE. If I am wrong, is there any special application (exe file) for IDLE so that I can configure to?? -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Wed Mar 21 15:54:06 2012 From: bgailer at gmail.com (bob gailer) Date: Wed, 21 Mar 2012 10:54:06 -0400 Subject: [Tutor] Unable to open .py files directly In-Reply-To: References: , <4F67BD16.3010303@gmail.com> Message-ID: <4F69EB8E.3040801@gmail.com> On 3/21/2012 9:00 AM, Surya K wrote: > I was "double clicking".. and I want to open IDLE. Great. Better explanation. To make it even better I will now assume you want the file to be opened by IDLE in a script (edit) window. So an even better explanation is "when I double-click the file I want it to be opened by IDLE in a script (edit) window." On the other hand if I take what you say literally all you want to do is open IDLE. This is probably not the case. Again I say it is well worth the effort to be as thorough and explicit as possible. So that we can reproduce the behavior you want. -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Wed Mar 21 16:09:05 2012 From: bgailer at gmail.com (bob gailer) Date: Wed, 21 Mar 2012 11:09:05 -0400 Subject: [Tutor] Unable to open .py files directly In-Reply-To: References: , <4F67BD16.3010303@gmail.com>, , Message-ID: <4F69EF11.8070100@gmail.com> On 3/21/2012 10:42 AM, Surya K wrote: > > > In that case, you need to change the file association of .py files to > IDLE > Bodsda > > > > Yeah, I tried that. The worst part is we don't have any exe file > specifically for IDLE. I mean windows has to choose whether to edit or > compile. > > > In my case, the file associated with my .py files is python.exe > (c:/python27/python.exe). I still don't understand why its not opening > in IDLE. Try right-clicking the file. You will should geta "context menu" Do you see Edit with IDLE? If so, choose that. Also take a look at the Advanced settings for the file type .py On my windows 2003 server in the Explorer I click Tools -> Folder Options -> File Types, select .py then click Advanced. Here I see Edit with IDLE I select that and click Edit and see "D:\Python27\pythonw.exe" "D:\Python27\Lib\idlelib\idle.pyw" -e "%1" in your case that should read "C:\Python27\pythonw.exe" "C:\Python27\Lib\idlelib\idle.pyw" -e "%1" If you don't have an Edit with IDLE entry, click New and add one. If you want that to be the double-click behavior click Set Default. If your OS is different the route to the file associations may be different. -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From abhishek.vit at gmail.com Wed Mar 21 19:03:52 2012 From: abhishek.vit at gmail.com (Abhishek Pratap) Date: Wed, 21 Mar 2012 11:03:52 -0700 Subject: [Tutor] feedback on writing pipelines in python Message-ID: Hi Guys I am in the process of perl to python transition for good. I wanted to get some feedback or may be best practice for the following. 1. stitch pipelines : I want python to act as a glue allowing me to run various linux shell based programs. If needed wait for a program to finish and then move on, logs if required 2. run the same pipeline but on a local grid if required. (SGE flavor mainly) Any modules which can reduce the number of lines i write will be helpful. Thanks! -Abhi -------------- next part -------------- An HTML attachment was scrubbed... URL: From abhishek.vit at gmail.com Wed Mar 21 19:26:27 2012 From: abhishek.vit at gmail.com (Abhishek Pratap) Date: Wed, 21 Mar 2012 11:26:27 -0700 Subject: [Tutor] feedback on writing pipelines in python In-Reply-To: <4F6A1BFA.8010809@alchemy.com> References: <4F6A1BFA.8010809@alchemy.com> Message-ID: Hi Steve I agree Steve perl is perfectly fine for the stuff I described but I am also interested trying alternatives. I am seeing quite interesting data handling stuff coming up in Python and I would like to try and sometimes as a programmer I dont like so many ways of doing the same things but it is subjective. Having many options can be good for some. -Abhi On Wed, Mar 21, 2012 at 11:20 AM, Steve Willoughby wrote: > On 21-Mar-12 11:03, Abhishek Pratap wrote: > >> Hi Guys >> >> I am in the process of perl to python transition for good. I wanted to >> > > Why? Perl is still a perfectly good tool. Just not, IMHO, good for > exactly the same things Python is good for. > > > 1. stitch pipelines : I want python to act as a glue allowing me to run >> various linux shell based programs. If needed wait for a program to >> finish and then move on, logs if required >> > > Look at the subprocess standard library module. It offers a complete set > of options for launching processes, piping their data aound, waiting for > them, handling exceptions, and so forth. > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Mar 21 19:42:49 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 21 Mar 2012 18:42:49 +0000 Subject: [Tutor] Unable to open .py files directly In-Reply-To: References: , <4F67BD16.3010303@gmail.com> Message-ID: On 21/03/12 13:00, Surya K wrote: > "open" is ambiguous. What do you want to happen? Edit or execute? > > I was "double clicking".. and I want to open IDLE. That's not usually the behavior you want for .py files. Once you gain experience you will likely have a lot of programs written in python, all will be in files ending .py. So you will probably want a double click to run those programs. (You should really only use IDLE to write and debug your programs not for running them) So it's usually better to add an edit option to your context menu (right click) to edit in IDLE. The ActiveState installer sets that up for you the official python windows installer doesn't - or didn't last time I used it - over a year ago now. Bob has shown you what his settings look like and how to set it up if you don't already have that option. Just create a new menu entry rather than modifying the Open entry. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at alchemy.com Wed Mar 21 19:20:42 2012 From: steve at alchemy.com (Steve Willoughby) Date: Wed, 21 Mar 2012 11:20:42 -0700 Subject: [Tutor] feedback on writing pipelines in python In-Reply-To: References: Message-ID: <4F6A1BFA.8010809@alchemy.com> On 21-Mar-12 11:03, Abhishek Pratap wrote: > Hi Guys > > I am in the process of perl to python transition for good. I wanted to Why? Perl is still a perfectly good tool. Just not, IMHO, good for exactly the same things Python is good for. > 1. stitch pipelines : I want python to act as a glue allowing me to run > various linux shell based programs. If needed wait for a program to > finish and then move on, logs if required Look at the subprocess standard library module. It offers a complete set of options for launching processes, piping their data aound, waiting for them, handling exceptions, and so forth. From alan.gauld at btinternet.com Wed Mar 21 19:49:46 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 21 Mar 2012 18:49:46 +0000 Subject: [Tutor] feedback on writing pipelines in python In-Reply-To: References: Message-ID: On 21/03/12 18:03, Abhishek Pratap wrote: > 1. stitch pipelines : I want python to act as a glue allowing me to run > various linux shell based programs. If needed wait for a program to > finish and then move on, logs if required Python by default reads/writes to stdin/stdout so you can do stuff like: $ foo.py < fred.txt | bar.py | baz.py > joe.txt You can also control that explicitly by importing the sys module and reassigning sys.stdin/sys.stdout or even reading and writing explicitly from those file like objects. You can also use the subprocess module to execute other programs (either Python or any other ind of executable file) in a sub procvess or a separate shell and get full control over the pipes, stdin, stdout and stderr. Of course that flexibility brings a price and the full power of subprocess.Popen is a little complex but there are lots of examples in the documentation. > 2. run the same pipeline but on a local grid if required. (SGE flavor > mainly) I confess I have no idea what you mean by a local grid, or an SGE flavor thereof... Somebody else will need to address that one! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From krush1954 at yahoo.com Thu Mar 22 04:47:04 2012 From: krush1954 at yahoo.com (ken brockman) Date: Wed, 21 Mar 2012 20:47:04 -0700 (PDT) Subject: [Tutor] opening a Qt .py file from within another python app. Message-ID: <1332388024.54952.YahooMailNeo@web39305.mail.mud.yahoo.com> Evening all; I am trying to import a Python QT file, that had been?generated from a ui file into another python app. I have imported it, without?generating?an error, but the Qt window isn't opening. I have spent the afternoon googling the issue, have found?numerous articles, but none that have seemed to work for me.? I?have?tried: ?import file,?from?file import *, and a slew of other?suggested?ways to get it to run, all to no avail. I have tried to call the Class and other Def functions from the Qt file, up to and including __main__, but no good. I have spend well over an hour?perusing the Python on line Doc's, but If i had stumbled upon the answer I guess I am too slow to have?recognized?it. I had come?across?this great piece on Stack overflow: There are more than a few ways. I'll list them in order of inverted preference (i.e., best first, worst last): ????1. Treat it like a module:?import file. This is good because it's secure, fast, and maintainable. Code gets reused as it's supposed to be done. Most Python libraries run using multiple methods stretched over lots of files. Highly recommended. Note that if your file is called?file.py, your import?should?not?include the?.py?extension at the end. ????2. The infamous (and unsafe)?exec?command:?execfile('file.py'). Insecure, hacky, usually the wrong answer. Avoid where possible. ????3. Spawn a shell process:?os.system('python file.py'). Use when desperate. None of which had gotten the Qt window to open. Yet when I run it directly, on it's own, it open's and the Qt window is displayed. I am hoping it is a relatively simply Task to accomplish, but beyond the stunted abilities of my limited knowledge. At this point I am simply trying to get the Qt window to open from the second python app. After which I have a steep hill to climb to?try?to connect the input from the one app to the signals of the other, but that is for another day. Any and all help, would truly be appreciated. python3.2, Linux Ubuntu 11.10 Thank you Ken From wayne at waynewerner.com Thu Mar 22 08:08:00 2012 From: wayne at waynewerner.com (Wayne Werner) Date: Thu, 22 Mar 2012 02:08:00 -0500 (CDT) Subject: [Tutor] feedback on writing pipelines in python In-Reply-To: References: Message-ID: On Wed, 21 Mar 2012, Abhishek Pratap wrote: > Hi Guys > I am ?in the process of perl to python transition for > good. Welcome! > 1. stitch pipelines : I want python to act as a glue > allowing me to run various linux shell based programs. > If needed wait for a program to finish and then move on, > logs if required? You'll want to take a look at the subprocess module. One thing you will notice is that Perl has a lot more terse syntax when it comes to commands line integration. That being said, Python is still fully capable. You may want to check out an Oreilly book called Python for the system administrator by Noah Gift. It doesn't tell you much about each tool but it exposes you to a ton of them. HTH, Wayne From alan.gauld at btinternet.com Thu Mar 22 08:31:22 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 22 Mar 2012 07:31:22 +0000 Subject: [Tutor] opening a Qt .py file from within another python app. In-Reply-To: <1332388024.54952.YahooMailNeo@web39305.mail.mud.yahoo.com> References: <1332388024.54952.YahooMailNeo@web39305.mail.mud.yahoo.com> Message-ID: On 22/03/12 03:47, ken brockman wrote: > None of which had gotten the Qt window to open. > Yet when I run it directly, on it's own, it open's > and the Qt window is displayed. My guess is that there is an if __name__... clause at the bottom with some code that doesn't get executed when you import it. That clause has some initialisation code that starts the main window up. Try opening the file in an editor and seeing what is happening there. You will either need to move that into a function then call the function after importing, or replicate it in your top level file. Having said that the os.system technique should have worked regardless, but it won't let you do any more integration. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From krush1954 at yahoo.com Thu Mar 22 10:57:56 2012 From: krush1954 at yahoo.com (ken brockman) Date: Thu, 22 Mar 2012 02:57:56 -0700 (PDT) Subject: [Tutor] Opening a Qt .py file from within another python app Message-ID: <1332410276.99432.YahooMailNeo@web39306.mail.mud.yahoo.com> M On 22/03/12 03:47, ken brockman wrote: >> None of which had gotten the Qt window to open. >> Yet when I run it directly, on it's own, it open's >> and the Qt window is displayed. >My guess is that there is an if __name__... clause >at the bottom with some code that doesn't get >executed when you import it. That clause has some >initialisation code that starts the main window up. >Try opening the file in an editor and seeing what is >happening there. You will either need to move that >into a function then call the function after importing, >or replicate it in your top level file. >Having said that the os.system technique should have worked regardless, but it won't let you do any more integration. >-- Alan G Thanks?much Alan for you time and input. I had managed to get it to run, after reading that the if __name__=__main__ at the bottom of the Qt file is what makes it fire up if run directly. I had figured that if I were to copy those last few lines after that?statement?from the bottom of the Qt file into my main file, that it may just work.?And, after affixing the name of the Qt file, which i had import into my main app, to the beginning of one or two calls from that bit, it did run. Only problem was, that it was all it did. It open and displayed the window, but the rest of the file didn't ?run. I'm guessing it may have to do with?something?in the body of those few lines i had copied. Either that or something in the qt file its self, waiting for a connection or some such. Since i am fairly new to both python and Qt and hardly up to speed in either I will just have to prod along and try my?limited?best to work it out.. Curious how the os.system technique hadn't worked though? From what you?said?it should have done the trick. Oh well, thank you once again for your help. Have a good day. Ken PS Another odd bit, was on the python docs page. It had said that using ?import File_name, without the .py would?import?it, but not run it. Seems a glaring oversight not to have mentioned, what would have made it run. Sure would have made my life a lot easier anyway. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Mar 22 19:20:27 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 22 Mar 2012 18:20:27 +0000 Subject: [Tutor] Opening a Qt .py file from within another python app In-Reply-To: <1332410276.99432.YahooMailNeo@web39306.mail.mud.yahoo.com> References: <1332410276.99432.YahooMailNeo@web39306.mail.mud.yahoo.com> Message-ID: On 22/03/12 09:57, ken brockman wrote: > PS Another odd bit, was on the python docs page. It had said that using > import File_name, without the .py would import it, but not run it. Seems > a glaring oversight not to have mentioned, what would have made it run. Actually it does run it when you import, just not the bit after the if __name__ = "__main__". The point of modules is that you don't usually want them to run as a program, you import them so as to get access to the functions within them. You want to control when they are called from your own code. So although Python imports do run the file, normally all that happens is that a few classes and functions get defined and, possibly, a few global variables get initialized. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From emailkgnow at gmail.com Thu Mar 22 19:45:26 2012 From: emailkgnow at gmail.com (Khalid Al-Ghamdi) Date: Thu, 22 Mar 2012 21:45:26 +0300 Subject: [Tutor] Library of Module for Analyzing Answer Cards Message-ID: Hi All, I work in in academic testing environment and we employ expensive machines to scan answer sheets (the ones where you blacken the letter of the correct multiple choice answer). Anyway, I was thinking if there was a way we could use regular old scanners to scan the sheets than analyze the images to score the tests. Do you know any modules or libraries in python that can be helpful in that? Also, what approach if any would you employ to tackle this project? thanks a million, -------------- next part -------------- An HTML attachment was scrubbed... URL: From krush1954 at yahoo.com Thu Mar 22 20:39:55 2012 From: krush1954 at yahoo.com (ken brockman) Date: Thu, 22 Mar 2012 12:39:55 -0700 (PDT) Subject: [Tutor] Opening a Qt .py file from within another python app In-Reply-To: References: <1332410276.99432.YahooMailNeo@web39306.mail.mud.yahoo.com> Message-ID: <1332445195.69199.YahooMailNeo@web39305.mail.mud.yahoo.com> ________________________________ On 22/03/12 09:57, ken brockman wrote: >> PS Another odd bit, was on the python docs page. It had said that using >> import File_name, without the .py would import it, but not run it. Seems >> a glaring oversight not to have mentioned, what would have made it run. >Actually it does run it when you import, just not the bit after the >if __name__ = "__main__". >The point of modules is that you don't usually want them to run as a program, you import them so as to get access to the >functions within them. You want to control when they are called from your own code. >-- Alan G Thank you once more Alan, for taking the time to try to enlighten me. I had gone back to the python site, to try to get a?better?understanding of what it had said, with your insight in mind. But I think i am more?befuddled?now then i had been?prior, If that is humanly possible. Below an?excerpt?from the python site, (2.7) but i think it is still applicable.? ------------------------------------------------ 6.1.1. Executing modules as scripts When you run a Python module with python fibo.py the code in the module will be executed, just as if you imported it, but with the __name__ set to "__main__". That means that by adding this code at the end of your module: if __name__ == "__main__": ? ? import sys ? ? fib(int(sys.argv[1])) you can make the file usable as a script as well as an importable module, because the code that parses the command line only runs if the module is executed as the ?main? file: $ python fibo.py 50 If the module is imported, the code is not run: ---------------------------------------------------- Please bare with me, as I had said, I am a total novice. So if I understand this, which Is highly unlikely the, ?If __name__==__main__, is what makes the module run as a stand?alone?script? Which shouldn't effect it's?usability as a module which is imported? So why was it, that I couldn't get it to run without including that bit in my main python program. And I am?assuming the line I had mistook to mean the module wouldn't run, means instead that the ?"name ==main won't run, which once?again?leads to the question, then why would i need to?include?it to make it function???? Do you see my point. What am i missing here? Some vital piece of the puzzle seems to be eluding me. Ken -------------- next part -------------- An HTML attachment was scrubbed... URL: From krush1954 at yahoo.com Thu Mar 22 20:59:14 2012 From: krush1954 at yahoo.com (ken brockman) Date: Thu, 22 Mar 2012 12:59:14 -0700 (PDT) Subject: [Tutor] Opening a Qt .py file from within another python app In-Reply-To: References: <1332410276.99432.YahooMailNeo@web39306.mail.mud.yahoo.com> Message-ID: <1332446354.84859.YahooMailNeo@web39304.mail.mud.yahoo.com> ________________________________ Alan, no need to respond to that last missive of mine. I no sooner had hit the send key and reopened the apps in question then the answer hit me like a small mallet in the back of my head. ?Obviously, what makes the?additional?code at the bottom of the?second app, run it, is that it must replicate the code that would be needed ?to call it from the?main?app.? Jeez, my bad, as the kids say. ? Have a good one. Ken PS maybe time to find a new hobby. I hear that knitting is very relaxing and no heavy mental lifting. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Thu Mar 22 21:02:52 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 22 Mar 2012 20:02:52 +0000 Subject: [Tutor] Opening a Qt .py file from within another python app In-Reply-To: <1332445195.69199.YahooMailNeo@web39305.mail.mud.yahoo.com> References: <1332410276.99432.YahooMailNeo@web39306.mail.mud.yahoo.com> <1332445195.69199.YahooMailNeo@web39305.mail.mud.yahoo.com> Message-ID: <5B80DD153D7D744689F57F4FB69AF474026C6CAB@SCACMX008.exchad.jpmchase.net> > python fibo.py > the code in the module will be executed, just as if you imported it, but > with the __name__ set to "__main__". That means that by adding this code at > the end of your module: > > if __name__ == "__main__": > import sys > fib(int(sys.argv[1])) > you can make the file usable as a script as well as an importable module, > because the code that parses the command line only runs if the module is > executed as the ?main? file: > > $ python fibo.py 50 > > If the module is imported, the code is not run: > > ---------------------------------------------------- > Please bare with me, as I had said, I am a total novice. So if I understand > this, which Is highly unlikely the, If __name__==__main__, is what makes > the module run as a stand alone script? Which shouldn't effect > it's usability as a module which is imported? So why was it, that I > couldn't get it to run without including that bit in my main python > program. And I am assuming the line I had mistook to mean the module > wouldn't run, means instead that the "name ==main won't run, which > once again leads to the question, then why would i need to include it to > make it function?? > Do you see my point. What am i missing here? Some vital piece of the puzzle > seems to be eluding me. No everything in a module is run when imported. Usually modules are just a class and function definitions so nothing actually happens. Anything you put in a module that is not in a function or class will run. If you put a print statement in the module that is not in a function or class, it will print the statement every time you import the module. That is why the convention is to use the following code to only automatically run the module when running the script. if __name__ == '__main__': # this is only true if you are running the script directly # by doing something like python myscript.py run_something_here() Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From abhishek.vit at gmail.com Thu Mar 22 21:40:29 2012 From: abhishek.vit at gmail.com (Abhishek Pratap) Date: Thu, 22 Mar 2012 13:40:29 -0700 Subject: [Tutor] weird error in my python program : merge sort Message-ID: I am imlpementing a merge sort algo for clarity purposes but my program is giving me weird answers. Sometimes it is able to sort and other times it does funky things. Help appreciated from random import * from numpy import * nums = [random.randint(100) for num in range(4)] #nums = [3,7,2,10] def merge_sort(nums, message='None'): ? ? #print "%s : num of elements in the list %d" % (message,len(nums)) ? ? print '[merge_sort] %s : %s' % ( message, nums) ? ? if len(nums) <= 1: ? ? ? ? return nums ? ? middle = len(nums)/2 ? ? print '[merge_sort] Mid point is %d' % middle ? ? left ?= nums[:middle] ? ? right = nums[middle:] ? ? merge_sort(left,'left') ? ? merge_sort(right,'right') ? ? print '[merge_sort] Calling merge on left: %s right : %s' % (left,right) ? ? result = merge(left,right) ? ? print '[merge_sort] %s' % result ? ? return result def merge(left,right): ? ? result = [] ? ? i,j = 0,0 ? ? print '[merge] left %s, right %s' % (left, right) ? ? while i < len(left) and j < len(right): ? ? ? ? print '[merge]Comparing left %d to right %d' % (left[i],right[j]) ? ? ? ? if left[i] <= right[j]: ? ? ? ? ? ? result.append(left[i]) ? ? ? ? ? ? i += 1 ? ? ? ? else: ? ? ? ? ? ? result.append(right[j]) ? ? ? ? ? ? j += 1 ? ? ? ? print '[merge]pushing to result',result ? ? result.extend(left[i:]) ? ? result.extend(right[j:]) ? ? print '[merge] return',result ? ? return result merge_sort(nums,'start') From abhishek.vit at gmail.com Thu Mar 22 21:54:24 2012 From: abhishek.vit at gmail.com (Abhishek Pratap) Date: Thu, 22 Mar 2012 13:54:24 -0700 Subject: [Tutor] weird error in my python program : merge sort : resolved Message-ID: I was not updating the list from the recursive call. > ? ? merge_sort(left,'left') > ? ? merge_sort(right,'right') left = merge_sort(left,'left') right = merge_sort(right,'right') -A -Abhi On Thu, Mar 22, 2012 at 1:40 PM, Abhishek Pratap wrote: > I am imlpementing a merge sort algo for clarity purposes but my > program is giving me weird answers. Sometimes it is able to sort and > other times it does funky things. Help appreciated > > > from random import * > from numpy import * > > nums = [random.randint(100) for num in range(4)] > #nums = [3,7,2,10] > > def merge_sort(nums, message='None'): > ? ? #print "%s : num of elements in the list %d" % (message,len(nums)) > ? ? print '[merge_sort] %s : %s' % ( message, nums) > > ? ? if len(nums) <= 1: > ? ? ? ? return nums > > ? ? middle = len(nums)/2 > ? ? print '[merge_sort] Mid point is %d' % middle > ? ? left ?= nums[:middle] > ? ? right = nums[middle:] > > ? ? merge_sort(left,'left') > ? ? merge_sort(right,'right') > ? ? print '[merge_sort] Calling merge on left: %s right : %s' % (left,right) > ? ? result = merge(left,right) > ? ? print '[merge_sort] %s' % result > ? ? return result > > > def merge(left,right): > ? ? result = [] > ? ? i,j = 0,0 > > ? ? print '[merge] left %s, right %s' % (left, right) > > ? ? while i < len(left) and j < len(right): > ? ? ? ? print '[merge]Comparing left %d to right %d' % (left[i],right[j]) > ? ? ? ? if left[i] <= right[j]: > ? ? ? ? ? ? result.append(left[i]) > ? ? ? ? ? ? i += 1 > ? ? ? ? else: > ? ? ? ? ? ? result.append(right[j]) > ? ? ? ? ? ? j += 1 > > ? ? ? ? print '[merge]pushing to result',result > > ? ? result.extend(left[i:]) > ? ? result.extend(right[j:]) > ? ? print '[merge] return',result > ? ? return result > > > merge_sort(nums,'start') From sukhpreet2294sidhu at ymail.com Thu Mar 22 23:01:30 2012 From: sukhpreet2294sidhu at ymail.com (Sukhpreet Sdhu) Date: Fri, 23 Mar 2012 06:01:30 +0800 (SGT) Subject: [Tutor] python sorting Message-ID: <1332453690.79384.YahooMailNeo@web193002.mail.sg3.yahoo.com> i want to sort the list formed by two variable taken as raw_input().i have written following code; a=raw_input() b=raw_input() c=a+b list=c.split() how i can sort the list formed -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Mar 22 23:06:20 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 22 Mar 2012 22:06:20 +0000 Subject: [Tutor] Opening a Qt .py file from within another python app In-Reply-To: <1332446354.84859.YahooMailNeo@web39304.mail.mud.yahoo.com> References: <1332410276.99432.YahooMailNeo@web39306.mail.mud.yahoo.com> <1332446354.84859.YahooMailNeo@web39304.mail.mud.yahoo.com> Message-ID: On 22/03/12 19:59, ken brockman wrote: > PS maybe time to find a new hobby. I hear that knitting is very relaxing > and no heavy mental lifting. Nah, I tried that once. programming is much easier! :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From d at davea.name Thu Mar 22 23:08:13 2012 From: d at davea.name (Dave Angel) Date: Thu, 22 Mar 2012 18:08:13 -0400 Subject: [Tutor] python sorting In-Reply-To: <1332453690.79384.YahooMailNeo@web193002.mail.sg3.yahoo.com> References: <1332453690.79384.YahooMailNeo@web193002.mail.sg3.yahoo.com> Message-ID: <4F6BA2CD.5080402@davea.name> On 03/22/2012 06:01 PM, Sukhpreet Sdhu wrote: > i want to sort the list formed by two variable taken as raw_input().i have written following code; > a=raw_input() > b=raw_input() > c=a+b > list=c.split() > how i can sort the list formed Do a search on python.org for list + sort. First match I got: http://wiki.python.org/moin/HowTo/Sorting -- DaveA From sukhpreet2294sidhu at ymail.com Thu Mar 22 23:14:41 2012 From: sukhpreet2294sidhu at ymail.com (Sukhpreet Sdhu) Date: Fri, 23 Mar 2012 06:14:41 +0800 (SGT) Subject: [Tutor] python arthematics Message-ID: <1332454481.91857.YahooMailNeo@web193003.mail.sg3.yahoo.com> i want to write a program that reads simple arithematic epressions and calculates the result. for example input "1*3+2" should generate "5'" as result -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Thu Mar 22 23:29:24 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 22 Mar 2012 22:29:24 +0000 Subject: [Tutor] python arthematics In-Reply-To: <1332454481.91857.YahooMailNeo@web193003.mail.sg3.yahoo.com> References: <1332454481.91857.YahooMailNeo@web193003.mail.sg3.yahoo.com> Message-ID: <5B80DD153D7D744689F57F4FB69AF474026C6EE8@SCACMX008.exchad.jpmchase.net> >i want to write a program that reads simple arithematic epressions and calculates the result. >for example input "1*3+2" should generate "5'" as result So what is stopping you? Snark aside, this can get really complicated unless you make some well defined rules. This becomes difficult especially when you think about whether you want to support order of operations. Should ?1+3*2? generate ?7? or ?8?? Do you want to support longer expressions or just 2 operations? Personally, if I were learning the language I would make it do 1 operation. Then after that I could consider how to make it do more operations. Turning it into a true arithmetic calculator might be a bit much to start with. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. -------------- next part -------------- An HTML attachment was scrubbed... URL: From delegbede at dudupay.com Thu Mar 22 23:53:43 2012 From: delegbede at dudupay.com (delegbede at dudupay.com) Date: Thu, 22 Mar 2012 22:53:43 +0000 Subject: [Tutor] python arthematics In-Reply-To: <1332454481.91857.YahooMailNeo@web193003.mail.sg3.yahoo.com> References: <1332454481.91857.YahooMailNeo@web193003.mail.sg3.yahoo.com> Message-ID: <1981986776-1332456947-cardhu_decombobulator_blackberry.rim.net-653488279-@b25.c12.bise7.blackberry> What have you tried? What so u intend to achieve? There are math functions in python already; so, are you planning to use the functions in the math class for your program or you want to write yours separately? The later would be a little disturbing in my candid opinion. Regards. Sent from my BlackBerry wireless device from MTN -----Original Message----- From: Sukhpreet Sdhu Sender: tutor-bounces+delegbede=dudupay.com at python.org Date: Fri, 23 Mar 2012 06:14:41 To: tutor at python.org Reply-To: Sukhpreet Sdhu Subject: [Tutor] python arthematics _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From breamoreboy at yahoo.co.uk Fri Mar 23 01:10:20 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 23 Mar 2012 00:10:20 +0000 Subject: [Tutor] python arthematics In-Reply-To: <1332454481.91857.YahooMailNeo@web193003.mail.sg3.yahoo.com> References: <1332454481.91857.YahooMailNeo@web193003.mail.sg3.yahoo.com> Message-ID: On 22/03/2012 22:14, Sukhpreet Sdhu wrote: > i want to write a program that reads simple arithematic epressions and calculates the result. > for example input "1*3+2" should generate "5'" as result > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Take a look at the operator module as it should give you some ideas. -- Cheers. Mark Lawrence. From alan.gauld at btinternet.com Fri Mar 23 01:14:30 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 23 Mar 2012 00:14:30 +0000 Subject: [Tutor] python arthematics In-Reply-To: <1332454481.91857.YahooMailNeo@web193003.mail.sg3.yahoo.com> References: <1332454481.91857.YahooMailNeo@web193003.mail.sg3.yahoo.com> Message-ID: On 22/03/12 22:14, Sukhpreet Sdhu wrote: > i want to write a program that reads simple arithematic expressions and > calculates the result. OK, there are many ways to do this but they pretty much fall into three categories: 1) read the string and exec() it - easy but very risky from a security point of view. 2) Write a general text parser to break the input string into operands and operators and combine the results. 3) build a state machine that looks for valid input (this will be easier if you opt for reverse polish notation BTW) You can do No 1 real quick just for fun, but don't try that in a real world program. So that leaves 2 and 3. If you understand the concepts (or research them on wikipedia) you can have at it, write some code and lets see what you get to. Hint: Start with a limited subset - only 2 operands and one operator allowed, say. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Mar 23 01:46:29 2012 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Fri, 23 Mar 2012 00:46:29 +0000 (GMT) Subject: [Tutor] python arthematics In-Reply-To: <1332462050.32465.YahooMailNeo@web193001.mail.sg3.yahoo.com> References: <1332454481.91857.YahooMailNeo@web193003.mail.sg3.yahoo.com> <1332462050.32465.YahooMailNeo@web193001.mail.sg3.yahoo.com> Message-ID: <1332463589.92877.YahooMailNeo@web86703.mail.ird.yahoo.com> Please use ReplyAll when responding to posts, Thanks. i have tried??like this way but i want to read all integers and operators in one string. how can i do that. > > >As described below. > > >expr = raw_input("Type an expression: ") > > >Now you have the expression as a string in expr. >You just need to analyze it to identify the various components ?(this is called parsing). > > >One simplistic approach to get you started is to treat white-space and the operators? >as separators between operands. You can then scan the string to extract a list of? >operands and a list of operators. So " 3 + 4 * 6" yields: > > >operators = ["+", "*"] >operands = ["3", "4", "6"] > > >Since we are expecting the operands to be integers we can go further > > >operands = ?[int(n) for n in operands] > > >For the operators you need to do a lookup table and maybe map them? >to the operators module operations... > > >You can then start matching them and performing the operations just like you did? > >in your code with the values read separately. eg.?You can apply each operator in? >turn to the first pair of operands?in the list: > > >3 + 4 ?-> 7 >7 * 6 -> 42 >? >That doesn't take any account of the normal rules of precedence and? >thats when things start to get much more complex. Also it doesn't allow? >for parenthesised sub expressions etc. This is actually quite tricky to get right,? >but a very good learning exercise! (But much harder than you probably? >thought it would be!) > > >HTH > > > >________________________________ > From: Alan Gauld >To: tutor at python.org >Sent: Thursday, 22 March 2012 8:14 PM >Subject: Re: [Tutor] python arthematics > >On 22/03/12 22:14, Sukhpreet Sdhu wrote: >> i want to write a program that reads simple arithematic expressions and >> calculates the result. > >OK, there are many ways to do this but they pretty much >fall into three categories: > >1) read the string and exec() it - easy but very >? risky from a security point of view. > >2) Write a general text parser to break the input >? string into operands and operators and combine >? the results. > >3) build a state machine that looks for valid input >? (this will be easier if you opt for reverse polish >? notation BTW) > >You can do No 1 real quick just for fun, but don't try >that in a real world program. > >So that leaves 2 and 3. If you understand the concepts >(or research them on wikipedia) you can have at it, >write some code and lets see what you get to. >Hint: Start with a limited subset - only 2 operands and >one operator allowed, say. > >HTH >-- Alan G >Author of the Learn to Program web site >http://www.alan-g.me.uk/ > >_______________________________________________ >Tutor maillist? -? Tutor at python.org >To unsubscribe or change subscription options: >http://mail.python.org/mailman/listinfo/tutor > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Fri Mar 23 01:58:41 2012 From: bgailer at gmail.com (bob gailer) Date: Thu, 22 Mar 2012 20:58:41 -0400 Subject: [Tutor] Library of Module for Analyzing Answer Cards In-Reply-To: References: Message-ID: <4F6BCAC1.6020903@gmail.com> On 3/22/2012 2:45 PM, Khalid Al-Ghamdi wrote: > Hi All, > > I work in in academic testing environment and we employ expensive > machines to scan answer sheets (the ones where you blacken the letter > of the correct multiple choice answer). Anyway, I was thinking if > there was a way we could use regular old scanners to scan the sheets > than analyze the images to score the tests. This is not a Python solution - but www.cardiff-*teleform*.com/ offers a product called Teleform that does exactly what you want. I used it a while ago for a project where we scanned over 100,000 copies of 4 different forms. Worked like a charm. -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Fri Mar 23 02:01:56 2012 From: bgailer at gmail.com (bob gailer) Date: Thu, 22 Mar 2012 21:01:56 -0400 Subject: [Tutor] Library of Module for Analyzing Answer Cards better link In-Reply-To: References: Message-ID: <4F6BCB84.8090809@gmail.com> On 3/22/2012 2:45 PM, Khalid Al-Ghamdi wrote: > Hi All, > > I work in in academic testing environment and we employ expensive > machines to scan answer sheets (the ones where you blacken the letter > of the correct multiple choice answer). Anyway, I was thinking if > there was a way we could use regular old scanners to scan the sheets > than analyze the images to score the tests. This is not a Python solution - but http://www.cardiff.com/products/teleform/index.html offers a product called Teleform that does exactly what you want. I used it a while ago for a project where we scanned over 100,000 copies of 4 different forms. Worked like a charm. -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From fal at libero.it Fri Mar 23 12:52:33 2012 From: fal at libero.it (Francesco Loffredo) Date: Fri, 23 Mar 2012 12:52:33 +0100 Subject: [Tutor] python arthematics In-Reply-To: <1332454481.91857.YahooMailNeo@web193003.mail.sg3.yahoo.com> References: <1332454481.91857.YahooMailNeo@web193003.mail.sg3.yahoo.com> Message-ID: <4F6C6401.70908@libero.it> Sukhpreet Sdhu wrote: > i want to write a program that reads simple arithematic epressions and calculates the result. > for example input "1*3+2" should generate "5'" as result I'm happy to learn somebody else took the same path that I did to learn Python! First of all, a disclaimer: I'm NOT pretending that my program is perfect or that it cannot be improved in many ways; feel free to show me all my mistakes! I tried (and I think I succeeded) to build a "school calculator" that solves any arithmetic expression the same way that we were asked to at school. If you use a calculator, it just gives you the final result, but it doesn't show all the intermediate steps, and I addressed just that problem. I don't want to tell you exactly how I did it, but I'll give you some hints. First, the general look of the program: ------------------------------------------------------------------------ transcript of a real session Insert expression: {[(3+2)^2*2+5]:10}x3+1 --- Normalizing Expression --- from {[(3+2)^2*2+5]:10}x3+1 to (((3+2)^2*2+5)/10)*3+1 --- SOLUTION --- (((3+2)^2*2+5)/10)*3+1 = = ((5^2*2+5)/10)*3+1 = = ((25*2+5)/10)*3+1 = = ((50+5)/10)*3+1 = = (55/10)*3+1 = = 5.5*3+1 = = 16.5+1 = = 17.5 ... solved! Press just Enter to finish, or Insert expression: ----------------------------------------------------------------end of transcript----------------------- As you can see, it's very close to what you want, if not exactly that. The main loop is really trivial, it just calls repeatedly the main expression solver function. It could be changed to include the input prompt, to let E() process strings from any source, but for now it just does ---------------------------------------------------------- while E(): print "Press just Enter to finish, or" --------------------------------------------------------- E() is the interesting function, of course. After the input prompt: - it calls a function that "normalizes" the input string, to allow for some symbols Python cannot use in math expressions, but often used by little students. For example, you could enter "2 x 2 : 4" and Python must read "2*2/4". Or you could use graphically different parentheses: {} or [] instead of (), or you could enter any number of spaces to make the expression more human-readable This normalization seems just cosmetic, but it also solves a syntactical problem with raising to a power, as I'll explain later. - it recognizes the innermost parenthesis (this can be tricky, but you'll have to discover yourself) - it extracts the contents of that parenthesis in a string - it repeats calling a function that - extracts from the given string the highest-priority operation - calculates the result of that operation (!) - returns the string with the result substituted for the operation - until the string just contains a number (!!) - substitutes the number for the parenthesis in the expression - records the simplified expression in a list - starts over, until there are no more operations to calculate and the expression has become a single number (!!) - prints out the list (this could be moved in the main loop with the input prompt, but again I'm too lazy for that ;-) ) I found some problems in the points with exclamation marks, and I'll give you some hints about those, too: (!) - I use exec() to calculate the operation (after having thoroughly checked the input, so there's no security problem!), but I had to build special functions for division and for raising to a power. I wanted division to return an integer quotient whenever possible (both numbers a and b are integer, and a%b == 0), and a float otherwise. So I wrote the divok() function. Raising to a power is written "a ** b" in Python, but my simple parser cannot tell this from a double multiplication symbol, a syntax error. That's why I used ^ as a power symbol, and I also changed ** into ^ in my normalization routine to allow for the correct syntax. Python, of course, still needs **, so I wrote the powok() function to calculate a**b when it receives a^b. (!!) - The built-in s.isdigit() string method can be easily used to tell if a string is a number, but it fails recognizing negative and floating point numbers: >>> a = "7876787564" >>> a.isdigit() True >>> a = "7876787.564" >>> a.isdigit() False >>> a = "-7876" >>> a.isdigit() False That's why I wrote younumber() that returns True in the three above cases, and behaves like isdigit() otherwise. Hope this can be a good starting point for your project. Francesco ----- Nessun virus nel messaggio. Controllato da AVG - www.avg.com Versione: 2012.0.1913 / Database dei virus: 2114/4886 - Data di rilascio: 22/03/2012 -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Fri Mar 23 15:18:15 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 23 Mar 2012 14:18:15 +0000 Subject: [Tutor] python arthematics In-Reply-To: <1332457270.60823.YahooMailNeo@web193005.mail.sg3.yahoo.com> References: <1332454481.91857.YahooMailNeo@web193003.mail.sg3.yahoo.com> <5B80DD153D7D744689F57F4FB69AF474026C6EE8@SCACMX008.exchad.jpmchase.net> <1332457270.60823.YahooMailNeo@web193005.mail.sg3.yahoo.com> Message-ID: <5B80DD153D7D744689F57F4FB69AF474026C7CB7@SCACMX008.exchad.jpmchase.net> Please reply to the list (or at least include it) and not just the person responding. > i have tried upto two varibles but i want it to extend to mny more . I > just need an idea. i have tried like this > a=int(raw_input()) > b=int(raw_input()) > print "please enter operator" > operator=raw_input() > if operator == "+": > c=a+b > print c > elif operator == "-": > c=a-b > print c > elif operator == "/": > c=a/b > print c > elif operator == "*": > c=a*b > print c The easiest thing to do would be to put this in a loop and use the result as 'a'. This would not help with order of operations, but you can leave that to the user. Dumb, but much like a non- scientific calculator. Alan has already provided you with other options, but be warned they are not beginner-level projects. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From emile at fenx.com Fri Mar 23 17:35:57 2012 From: emile at fenx.com (Emile van Sebille) Date: Fri, 23 Mar 2012 09:35:57 -0700 Subject: [Tutor] Library of Module for Analyzing Answer Cards In-Reply-To: References: Message-ID: On 3/22/2012 11:45 AM Khalid Al-Ghamdi said... > Hi All, > > I work in in academic testing environment and we employ expensive > machines to scan answer sheets (the ones where you blacken the letter of > the correct multiple choice answer). Anyway, I was thinking if there was > a way we could use regular old scanners to scan the sheets than analyze > the images to score the tests. > > Do you know any modules or libraries in python that can be helpful in > that? Also, what approach if any would you employ to tackle this project? > For quick production deployment, I'd check out Bob's suggestion. If I were going to write a python based solution I'd start with PIL (see http://www.pythonware.com/products/pil/) I haven't tried doing something quite as detailed as what you're describing, but I do have PIL doing image analysis, cropping and resizing on an automated basis in a production environment. I think I'd examine the scanned image for a location marker, then from that and an answer template that provides the answer box locations, locate the answer box area for each question in turn and identify the filled in multiple choice response. HTH, Emile From mehgcap at gmail.com Sat Mar 24 04:51:24 2012 From: mehgcap at gmail.com (Alex Hall) Date: Fri, 23 Mar 2012 23:51:24 -0400 Subject: [Tutor] working with c_byte? Message-ID: Hi all, I am trying to read battery information. I found an example that sets up a ctypes structure to get the information from a kernel call, and it works... except that I just realized the values of some fields are added. For instance, a value of 1 means that the battery is "high", and 8 means it is charging. I didn't realize until just now that Windows will give both of these to me as 9, so the dict I set up to see what the value is won't work. Similarly, a value of 255 is always seen in Python as -128, even if I multiply it by -1 to flip it. The value I'm working with is a ctypes.c_byte. Here is the data structure: class SYSTEM_POWER_STATUS(ctypes.Structure): _fields_=[ ("ACLineStatus", ctypes.c_byte), ("BatteryFlag", ctypes.c_byte), ("BatteryLifePercent", ctypes.c_byte), ("Reserved1", ctypes.c_byte), ("BatteryLifeTime", ctypes.wintypes.DWORD), ("BatteryFullLiveTime", ctypes.wintypes.DWORD) ] and here is my dict to use when looking up the meaning of the BatteryFlag: status_constants = { 1:"high", 2:"low", 4:"critical", 8:"charging", 128:"no system battery", -128:"no system battery", #hack to get around odd negation of 128 flag... how to fix? 255:"unknown" } Of course, 9 means the battery is high and charging, but how do I interpret an arbitrary integer as the sum of its flags? Is there a binary trick I can use? I could record all the 1s in the binary number and look up their positions... but is there a simpler way? If I do that, where is the sign bit in c_byte? TIA. -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From d at davea.name Sat Mar 24 05:37:46 2012 From: d at davea.name (Dave Angel) Date: Sat, 24 Mar 2012 00:37:46 -0400 Subject: [Tutor] working with c_byte? In-Reply-To: References: Message-ID: <4F6D4F9A.2050705@davea.name> On 03/23/2012 11:51 PM, Alex Hall wrote: > Hi all, > I am trying to read battery information. I found an example that sets > up a ctypes structure to get the information from a kernel call, and > it works... except that I just realized the values of some fields are > added. For instance, a value of 1 means that the battery is "high", > and 8 means it is charging. I didn't realize until just now that > Windows will give both of these to me as 9, so the dict I set up to > see what the value is won't work. Similarly, a value of 255 is always > seen in Python as -128, even if I multiply it by -1 to flip it. Don't multiply by -1, simply convert to an int, and use modulo 256 to get it to a positive value. newval = int(cbyte) % 256 Or perhaps use c_ubyte instead of c_byte to get unsigned values in the first place. A signed value uses the highest bit to indicate a negative value. For an 8 bit signed value, the values range from -128 to 127. There is no positive value above 127, so multiplying by -1 is the wrong answer. Besides if there are other bits in the byte, they'll get changed as well. The modulo trick won't affect any of the 8 bits, only their interpretation. > The > value I'm working with is a ctypes.c_byte. Here is the data structure: > class SYSTEM_POWER_STATUS(ctypes.Structure): > _fields_=[ > ("ACLineStatus", ctypes.c_byte), > ("BatteryFlag", ctypes.c_byte), > ("BatteryLifePercent", ctypes.c_byte), > ("Reserved1", ctypes.c_byte), > ("BatteryLifeTime", ctypes.wintypes.DWORD), > ("BatteryFullLiveTime", ctypes.wintypes.DWORD) > ] > > and here is my dict to use when looking up the meaning of the BatteryFlag: > status_constants = { > 1:"high", > 2:"low", > 4:"critical", > 8:"charging", > 128:"no system battery", > -128:"no system battery", #hack to get around odd negation of 128 > flag... how to fix? > 255:"unknown" > } > cbyte & 1 will be nonzero (1) if that one "high" flag is set, regardless of the others. cbyte & 2 will be nonzero (2) if "low", and so on. for flag in 1,2,4,8,16,32,64,128: if cbyte & flag: print status_constants[cbyte & flag] > Of course, 9 means the battery is high and charging, but how do I > interpret an arbitrary integer as the sum of its flags? Is there a > binary trick I can use? I could record all the 1s in the binary number > and look up their positions... but is there a simpler way? If I do > that, where is the sign bit in c_byte? TIA. > > As I said earlier, the sign bit is 128, the highest bit in the byte. The number is 2's complement, which is why you must use modulo to convert it, not multiplication by -1. The latter approach would work if the machine used ones complement. -- DaveA From mehgcap at gmail.com Sat Mar 24 06:10:59 2012 From: mehgcap at gmail.com (Alex Hall) Date: Sat, 24 Mar 2012 01:10:59 -0400 Subject: [Tutor] working with c_byte? In-Reply-To: <4F6D4F9A.2050705@davea.name> References: <4F6D4F9A.2050705@davea.name> Message-ID: Thanks, the & (bitwise operator) trick seems to be promising. Should I still mod by 256? If so, could you explain why, since the value cannot exceed 127? Also, how does that work if a possible vlaue is 255, according to the documentation? On 3/24/12, Dave Angel wrote: > On 03/23/2012 11:51 PM, Alex Hall wrote: >> Hi all, >> I am trying to read battery information. I found an example that sets >> up a ctypes structure to get the information from a kernel call, and >> it works... except that I just realized the values of some fields are >> added. For instance, a value of 1 means that the battery is "high", >> and 8 means it is charging. I didn't realize until just now that >> Windows will give both of these to me as 9, so the dict I set up to >> see what the value is won't work. Similarly, a value of 255 is always >> seen in Python as -128, even if I multiply it by -1 to flip it. > > Don't multiply by -1, simply convert to an int, and use modulo 256 to > get it to a positive value. > newval = int(cbyte) % 256 > > Or perhaps use c_ubyte instead of c_byte to get unsigned values in the > first place. > > A signed value uses the highest bit to indicate a negative value. For > an 8 bit signed value, the values range from -128 to 127. There is no > positive value above 127, so multiplying by -1 is the wrong answer. > Besides if there are other bits in the byte, they'll get changed as > well. The modulo trick won't affect any of the 8 bits, only their > interpretation. > >> The >> value I'm working with is a ctypes.c_byte. Here is the data structure: >> class SYSTEM_POWER_STATUS(ctypes.Structure): >> _fields_=[ >> ("ACLineStatus", ctypes.c_byte), >> ("BatteryFlag", ctypes.c_byte), >> ("BatteryLifePercent", ctypes.c_byte), >> ("Reserved1", ctypes.c_byte), >> ("BatteryLifeTime", ctypes.wintypes.DWORD), >> ("BatteryFullLiveTime", ctypes.wintypes.DWORD) >> ] >> >> and here is my dict to use when looking up the meaning of the BatteryFlag: >> status_constants = { >> 1:"high", >> 2:"low", >> 4:"critical", >> 8:"charging", >> 128:"no system battery", >> -128:"no system battery", #hack to get around odd negation of 128 >> flag... how to fix? >> 255:"unknown" >> } >> > > cbyte & 1 will be nonzero (1) if that one "high" flag is set, > regardless of the others. > cbyte & 2 will be nonzero (2) if "low", and so on. > > for flag in 1,2,4,8,16,32,64,128: > if cbyte & flag: > print status_constants[cbyte & flag] > > >> Of course, 9 means the battery is high and charging, but how do I >> interpret an arbitrary integer as the sum of its flags? Is there a >> binary trick I can use? I could record all the 1s in the binary number >> and look up their positions... but is there a simpler way? If I do >> that, where is the sign bit in c_byte? TIA. >> >> > > As I said earlier, the sign bit is 128, the highest bit in the byte. > The number is 2's complement, which is why you must use modulo to > convert it, not multiplication by -1. The latter approach would work if > the machine used ones complement. > > -- > > DaveA > > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From d at davea.name Sat Mar 24 06:30:17 2012 From: d at davea.name (Dave Angel) Date: Sat, 24 Mar 2012 01:30:17 -0400 Subject: [Tutor] working with c_byte? In-Reply-To: References: <4F6D4F9A.2050705@davea.name> Message-ID: <4F6D5BE9.5090203@davea.name> On 03/24/2012 01:10 AM, Alex Hall wrote: > Thanks, the& (bitwise operator) trick seems to be promising. Should I > still mod by 256? If so, could you explain why, since the value cannot > exceed 127? Also, how does that work if a possible vlaue is 255, > according to the documentation? > You top-posted, which loses all earlier context. Please put your response *after* whatever you're quoting. I gave several possibilities; you should use whichever seems to make the code clearest to you. I think using a c_ubyte is the most straightforward. That has values from 0 to 255, so it'd match the documentation. But if you're sticking with c_byte, you have a signed value. So the docs lie about the range being 0 to 255. Or maybe they're written for some other language. If you want to explicitly get the values 0 to 255, you can use the expression I provided, using modulo 256. But the & operator doesn't care a bit. (no pun intended). You can use it on signed or on unsigned, or on unsigned modulo-ed data. No change. This all assumes you're running on a twos-complement processor, like the Intel Pentium. If you're on ones-complement, half this stuff breaks, and the other half doesn't work very well. Bit twiddling is quite processor specific. Fortunately for us, the vast majority of machines these days use twos-complement. One other thing: these problems are not specific to Python. I spent quite a while 15 years ago teaching a Java developer how to deal with similar issues. At that time at least, Java didn't even have unsigned bytes. -- DaveA From alan.gauld at btinternet.com Sat Mar 24 09:14:24 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 24 Mar 2012 08:14:24 +0000 Subject: [Tutor] working with c_byte? In-Reply-To: References: Message-ID: On 24/03/12 03:51, Alex Hall wrote: > Of course, 9 means the battery is high and charging, but how do I > interpret an arbitrary integer as the sum of its flags? Is there a > binary trick I can use? Dave has given the immediate answer which is a subset of a general technique known as bitwise masking. I discuss this with some other examples in the Operating System topic of my tutorial. You might find the write up interesting. Another useful bitwise operator is xor which can be used to tell is any flags have changed value since the last time you looked: oldflags = readFlags() while True: # look for a change newflags = readFlags() if newflags ^ oldflags: break # there's been a change # process newflags. And finally, the bitwise OR can be used to set a particular flag HiBattery = 8 flags = flags | HiBattery # sets HiBattery, preserving the rest. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From d at davea.name Sat Mar 24 09:41:38 2012 From: d at davea.name (Dave Angel) Date: Sat, 24 Mar 2012 04:41:38 -0400 Subject: [Tutor] working with c_byte? In-Reply-To: References: Message-ID: <4F6D88C2.2040004@davea.name> On 03/24/2012 04:14 AM, Alan Gauld wrote: > On 24/03/12 03:51, Alex Hall wrote: > >> Of course, 9 means the battery is high and charging, but how do I >> interpret an arbitrary integer as the sum of its flags? Is there a >> binary trick I can use? > > Dave has given the immediate answer which is a subset of a general > technique known as bitwise masking. > > I discuss this with some other examples in the Operating System topic > of my tutorial. You might find the write up interesting. > > Another useful bitwise operator is xor which can be used to tell is > any flags have changed value since the last time you looked: > > oldflags = readFlags() > > while True: # look for a change > newflags = readFlags() > if newflags ^ oldflags: > break # there's been a change > > # process newflags. > > And finally, the bitwise OR can be used to set a particular flag > > HiBattery = 8 > > flags = flags | HiBattery # sets HiBattery, preserving the rest. > > > HTH, > There are many useful purposes for xor, but your example could have just used the != operator. A better example is if you want to know which bit(s) changed, you xor the old with the new. One other technique which I forgot about when composing my earlier reply is to fetch individual bits. If you just want one bit at a time, and usually there's just a single one, it can be useful to have an algorithm which simply gives you the lowest nonzero bit. For any nonzero value, if you AND that value with -value, you'll get a single bit value. (only on twos-complement machines) so if you have a dict called flag_meanings, you could do something like: flag = flags & (-flags) meaning = flag_meanings[ flag ] And if flag_meanings has an entry for zero as well as for 1,2, 4, etc., then this will always give you a useful meaning. Now if you apply your xor technique here, you can do something like: flags ^= flag to clear out the flag you've processed, and repeat to process the rest. Something like: while flags: flag = flags & (-flags) print flag_meanings[flag] flags ^= flag This loop will behave similarly to the for-loop I suggested earlier. But it will loop around fewer times, and waste no cycles once the flags have been processed. This can be especially useful if you have hundreds of bits in your flags, rather than just 8. (above code fragments untested; it's late here) -- DaveA From fomcl at yahoo.com Sat Mar 24 21:13:53 2012 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sat, 24 Mar 2012 13:13:53 -0700 (PDT) Subject: [Tutor] getUncPath(mappedDrive) Message-ID: <1332620033.41135.YahooMailNeo@web110704.mail.gq1.yahoo.com> Hi, Is there a function that takes a file path with a mapped drive (z:\blah) and returns the associated UNC path (\\server\share\ding\dang\dong\blah)? I looked in os.path, but it doesn't seem to have this. The link below seems to be a solution (code in the bottom of the page), but I can't install win32com.client in the office :-( Is there any built-in function? ?http://stackoverflow.com/questions/2244767/python-check-network-map Thanks! Regards, Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~? -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Sat Mar 24 21:22:14 2012 From: mail at timgolden.me.uk (Tim Golden) Date: Sat, 24 Mar 2012 20:22:14 +0000 Subject: [Tutor] getUncPath(mappedDrive) In-Reply-To: <1332620033.41135.YahooMailNeo@web110704.mail.gq1.yahoo.com> References: <1332620033.41135.YahooMailNeo@web110704.mail.gq1.yahoo.com> Message-ID: <4F6E2CF6.6030205@timgolden.me.uk> On 24/03/2012 20:13, Albert-Jan Roskam wrote: > Hi, > > Is there a function that takes a file path with a mapped drive > (z:\blah) and returns the associated UNC path > (\\server\share\ding\dang\dong\blah)? I looked in os.path, but it > doesn't seem to have this. The link below seems to be a solution > (code in the bottom of the page), but I can't install win32com.client > in the office :-( Is there any built-in function? > > http://stackoverflow.com/questions/2244767/python-check-network-map There's nothing built-in. The easiest function to emulate through ctypes is probably WNetGetConnection: http://msdn.microsoft.com/en-us/library/windows/desktop/aa385453%28v=vs.85%29.aspx (this is available from pywin32 via the win32wnet package but I assume you can't install that either) TJG From fomcl at yahoo.com Sat Mar 24 22:29:43 2012 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sat, 24 Mar 2012 14:29:43 -0700 (PDT) Subject: [Tutor] getUncPath(mappedDrive) In-Reply-To: <4F6E2CF6.6030205@timgolden.me.uk> References: <1332620033.41135.YahooMailNeo@web110704.mail.gq1.yahoo.com> <4F6E2CF6.6030205@timgolden.me.uk> Message-ID: <1332624583.21709.YahooMailNeo@web110712.mail.gq1.yahoo.com> From: Tim Golden >To: >Cc: Python Mailing List >Sent: Saturday, March 24, 2012 9:22 PM >Subject: Re: [Tutor] getUncPath(mappedDrive) > >On 24/03/2012 20:13, Albert-Jan Roskam wrote: >> Hi, >> >> Is there a function that takes a file path with a mapped drive >> (z:\blah) and returns the associated UNC path >> (\\server\share\ding\dang\dong\blah)? I looked in os.path, but it >> doesn't seem to have this. The link below seems to be a solution >> (code in the bottom of the page), but I can't install win32com.client >> in the office :-( Is there any built-in function? >> >> http://stackoverflow.com/questions/2244767/python-check-network-map > >There's nothing built-in. The easiest function to emulate >through ctypes is probably WNetGetConnection: > >http://msdn.microsoft.com/en-us/library/windows/desktop/aa385453%28v=vs.85%29.aspx > >(this is available from pywin32 via the win32wnet package >but I assume you can't install that either) > >TJG >_______________________________________________ >Hi Tim, > >Thanks! This seems a feasible approach. I have found this Python project that exposes some of the functions of mpr.dll: http://sourceforge.net/projects/wnetconnect/ WNetGetConnection is not among the functions, but the code will help. I have to read up on ctypes.Structure though as I never really understood this. > >Cheers, >Albert-Jan > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mjolewis at gmail.com Sat Mar 24 23:20:56 2012 From: mjolewis at gmail.com (Michael Lewis) Date: Sat, 24 Mar 2012 15:20:56 -0700 Subject: [Tutor] Error handling Message-ID: Hi everyone, I am having a bit of trouble understanding what is going on below. What does the "e" in "except OSError, e:" do? Any other help you can provide regarding errno would be extremely appreciated. I've done help() and dir() on it, but I am not really understanding what's going on with "e.errno != errno.EEXIST:" Thanks. import os, errno try: os.makedirs('a/b/c') except OSError, e: if e.errno != errno.EEXIST: raise I am in the process of writing a script to move files from one directory to another. I am supplying both the source and destination directories at runtime. I want to create the destination file on the fly; however, if it already exists, I want to handle that error/ignore that error. Also, if the the same file exists in both the source and destination directory, I'd like to override the one in the destination directory with the one in the source directory. I am having trouble with the error handling portion. Here is a pastebin for my source code: http://pastebin.com/EU578xQs -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Sat Mar 24 23:25:39 2012 From: mail at timgolden.me.uk (Tim Golden) Date: Sat, 24 Mar 2012 22:25:39 +0000 Subject: [Tutor] getUncPath(mappedDrive) In-Reply-To: <1332624583.21709.YahooMailNeo@web110712.mail.gq1.yahoo.com> References: <1332620033.41135.YahooMailNeo@web110704.mail.gq1.yahoo.com> <4F6E2CF6.6030205@timgolden.me.uk> <1332624583.21709.YahooMailNeo@web110712.mail.gq1.yahoo.com> Message-ID: <4F6E49E3.6060604@timgolden.me.uk> On 24/03/2012 21:29, Albert-Jan Roskam wrote: > Thanks! This seems a feasible approach. I have found this Python > project that exposes some of the functions of mpr.dll: > http://sourceforge.net/projects/wnetconnect/ WNetGetConnection is > not among the functions, but the code will help. I have to read up > on ctypes.Structure though as I never really understood this. This particular function call doesn't require too much work in fact. Something like the following code -- error-handling mostly omitted -- should do the trick: import ctypes # # Get the ANSI version of the function from its DLL # WNetGetConnection = ctypes.windll.mpr.WNetGetConnectionA ERROR_MORE_DATA = 234 # # Set up the drive name to map back from # and an empty buffer with zero length. # local_name = "Z:" length = ctypes.c_long (0) remote_name = ctypes.create_string_buffer ("") # # Call the function, expecting to receive an ERROR_MORE_DATA # result, which indicates that the buffer is too small and # which populates the length field with the right length. # result = WNetGetConnection ( local_name, remote_name, ctypes.byref (length) ) # # Assuming we did get that error, recreate the buffer and # call again with the supplied length. This isn't strictly # necessary (you could probably get away with hard-coding # 2048 or whatever) but it does save you having to guess. # if result == ERROR_MORE_DATA: remote_name = ctypes.create_string_buffer (length.value) result = WNetGetConnection ( local_name, remote_name, ctypes.byref (length) ) # # If the result of either call was an error, raise an Exception # if result != 0: raise RuntimeError ("Error %d" % result) print "Remote name is", remote_name.value TJG From colton.myers at gmail.com Sat Mar 24 23:51:06 2012 From: colton.myers at gmail.com (Colton Myers) Date: Sat, 24 Mar 2012 16:51:06 -0600 Subject: [Tutor] Error handling In-Reply-To: References: Message-ID: > I am having a bit of trouble understanding what is going on below. What does the "e" in "except OSError, e:" do? > Any other help you can provide regarding errno would be extremely appreciated. I've done help() and dir() on it, but I am not really understanding what's going on with "e.errno != errno.EEXIST:" > > > Basically, that `except` block is catching all exceptions of type OSError, and storing the exception in variable `e`. This variable does not have to be called `e`, but that's the most commonly-used variable name. Once you have the exception stored (in this case in the variable `e`), you can then see what type of exception, using the `errno` property of the exception. You can read about the different types here: http://docs.python.org/library/errno.html > import os, errno try: os.makedirs('a/b/c') except OSError, e: if e.errno != errno.EEXIST: raise > > > > > > In this particular section, it's catching any OSError, and then if it turns out that the error was "File Exists", it is raising that exception again, to be either caught by an encapsulating try block, or which will bring the program to a halt with an exception shown by the interpreter. Is that the behavior you are going for? Any more confusion? -- Colton Myers -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Sun Mar 25 00:39:12 2012 From: bgailer at gmail.com (bob gailer) Date: Sat, 24 Mar 2012 19:39:12 -0400 Subject: [Tutor] Library of Module for Analyzing Answer Cards In-Reply-To: References: <4F6BCAC1.6020903@gmail.com> Message-ID: <4F6E5B20.6040403@gmail.com> Remember to always reply-all so a copy goes to the list. On 3/24/2012 7:49 AM, Khalid Al-Ghamdi wrote: > thanks a lot that was extremely helpful. > > On Fri, Mar 23, 2012 at 3:58 AM, bob gailer > wrote: > > On 3/22/2012 2:45 PM, Khalid Al-Ghamdi wrote: >> Hi All, >> >> I work in in academic testing environment and we employ expensive >> machines to scan answer sheets (the ones where you blacken the >> letter of the correct multiple choice answer). Anyway, I was >> thinking if there was a way we could use regular old scanners to >> scan the sheets than analyze the images to score the tests. > > This is not a Python solution - but www.cardiff > -*teleform*.com/ offers a product called > Teleform that does exactly what you want. I used it a while ago > for a project where we scanned over 100,000 copies of 4 different > forms. Worked like a charm. > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC > > -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/gif Size: 181 bytes Desc: not available URL: From mjolewis at gmail.com Sun Mar 25 07:12:54 2012 From: mjolewis at gmail.com (Michael Lewis) Date: Sat, 24 Mar 2012 22:12:54 -0700 Subject: [Tutor] Error handling In-Reply-To: References: Message-ID: On Sat, Mar 24, 2012 at 3:51 PM, Colton Myers wrote: > I am having a bit of trouble understanding what is going on below. What > does the "e" in "except OSError, e:" do? > Any other help you can provide regarding errno would be extremely > appreciated. I've done help() and dir() on it, but I am not really > understanding what's going on with "e.errno != errno.EEXIST:" > > Basically, that `except` block is catching all exceptions of type OSError, > and storing the exception in variable `e`. This variable does not have to > be called `e`, but that's the most commonly-used variable name. > > Once you have the exception stored (in this case in the variable `e`), you > can then see what type of exception, using the `errno` property of the > exception. You can read about the different types here: > > http://docs.python.org/library/errno.html > > import os, errnotry: > os.makedirs('a/b/c')except OSError, e: > if e.errno != errno.EEXIST: > raise > > In this particular section, it's catching any OSError, and then if it > turns out that the error was "File Exists", it is raising that exception > again, to be either caught by an encapsulating try block, or which will > bring the program to a halt with an exception shown by the interpreter. > > Is that the behavior you are going for? Any more confusion? > Why wouldn't it be errno.e instead of e.errno? > > -- > Colton Myers > > -- Michael J. Lewis mjolewis at gmail.com 415.815.7257 -------------- next part -------------- An HTML attachment was scrubbed... URL: From akazmi001 at gmail.com Sun Mar 25 07:31:05 2012 From: akazmi001 at gmail.com (Asif Kazmi) Date: Sun, 25 Mar 2012 01:31:05 -0400 Subject: [Tutor] Question about input Message-ID: Hello, I'm going through Python Programming for the Absolute Beginner, 3rd edition, on a Mac with Python 3.2. In the second chapter, the book gives sample code that shows how a logical error can occur: # Trust Fund Buddy - Bad # Demonstrates a logical error print( """ Trust Fund Buddy Totals your monthly spending so that your trust fund doesn't run out (and you're forced to get a real job). Please enter the requested, monthly costs. Since you're rich, ignore pennies and use only dollar amounts. """ ) car = input("Lamborghini Tune-Ups: ") rent = input("Manhattan Apartment: ") jet = input("Private Jet Rental: ") gifts = input("Gifts: ") food = input("Dining Out: ") staff = input("Staff (butlers, chef, driver, assistant): ") guru = input("Personal Guru and Coach: ") games = input("Computer Games: ") total = car + rent + jet + gifts + food + staff + guru + games print("\nGrand Total:", total) input("\n\nPress the enter key to exit.") This program should show the inputted numbers as a concatenation rather than a sum, I understand that is the mistake in the code. However, when I run it, it shows: Grand Total: 111Manhattan Apartment: 111Private Jet Rental: 111Gifts: 111Dining Out: 111Staff (butlers, chef, driver, assistant): 111Personal Guru and Coach: 111Computer Games: 111 It appears to be adding the input prompt as part of the variables? except for car? What am I missing? Thanks, Asif -------------- next part -------------- An HTML attachment was scrubbed... URL: From zebra05 at gmail.com Sun Mar 25 07:52:34 2012 From: zebra05 at gmail.com (Sithembewena Lloyd Dube) Date: Sun, 25 Mar 2012 07:52:34 +0200 Subject: [Tutor] Error handling In-Reply-To: References: Message-ID: That is because 'errno' is a property on the exception object called 'e', not the other way around. On Sun, Mar 25, 2012 at 7:12 AM, Michael Lewis wrote: > > > On Sat, Mar 24, 2012 at 3:51 PM, Colton Myers wrote: > >> I am having a bit of trouble understanding what is going on below. What >> does the "e" in "except OSError, e:" do? >> Any other help you can provide regarding errno would be extremely >> appreciated. I've done help() and dir() on it, but I am not really >> understanding what's going on with "e.errno != errno.EEXIST:" >> >> Basically, that `except` block is catching all exceptions of type >> OSError, and storing the exception in variable `e`. This variable does not >> have to be called `e`, but that's the most commonly-used variable name. >> >> Once you have the exception stored (in this case in the variable `e`), >> you can then see what type of exception, using the `errno` property of the >> exception. You can read about the different types here: >> >> http://docs.python.org/library/errno.html >> >> import os, errnotry: >> os.makedirs('a/b/c')except OSError, e: >> if e.errno != errno.EEXIST: >> raise >> >> In this particular section, it's catching any OSError, and then if it >> turns out that the error was "File Exists", it is raising that exception >> again, to be either caught by an encapsulating try block, or which will >> bring the program to a halt with an exception shown by the interpreter. >> >> Is that the behavior you are going for? Any more confusion? >> > > Why wouldn't it be errno.e instead of e.errno? > >> >> -- >> Colton Myers >> >> > > > -- > Michael J. Lewis > > mjolewis at gmail.com > 415.815.7257 > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Regards, Sithembewena Lloyd Dube -------------- next part -------------- An HTML attachment was scrubbed... URL: From russel at winder.org.uk Sun Mar 25 09:22:50 2012 From: russel at winder.org.uk (Russel Winder) Date: Sun, 25 Mar 2012 08:22:50 +0100 Subject: [Tutor] Error handling In-Reply-To: References: Message-ID: <1332660170.3671.45.camel@launcelot.winder.org.uk> Michael, On Sat, 2012-03-24 at 15:20 -0700, Michael Lewis wrote: [...] It is perhaps worth noting that in Python 3, the syntax has changed: > import os, errno > try: > > os.makedirs('a/b/c') > except OSError, e: except OSError as e : > > if e.errno != errno.EEXIST: > > raise This "as" syntax works in 2.6 and 2.7 so is probably the syntax to use unless you have to use very old versions of Python. I think the "as" syntax makes it clearer that e is a variable referring to the instance of OSError that causes the except clause to execute if it does. -- Russel. ============================================================================= Dr Russel Winder t: +44 20 7585 2200 voip: sip:russel.winder at ekiga.net 41 Buckmaster Road m: +44 7770 465 077 xmpp: russel at winder.org.uk London SW11 1EN, UK w: www.russel.org.uk skype: russel_winder -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 198 bytes Desc: This is a digitally signed message part URL: From fomcl at yahoo.com Sun Mar 25 10:12:00 2012 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sun, 25 Mar 2012 01:12:00 -0700 (PDT) Subject: [Tutor] getUncPath(mappedDrive) In-Reply-To: <4F6E49E3.6060604@timgolden.me.uk> References: <1332620033.41135.YahooMailNeo@web110704.mail.gq1.yahoo.com> <4F6E2CF6.6030205@timgolden.me.uk> <1332624583.21709.YahooMailNeo@web110712.mail.gq1.yahoo.com> <4F6E49E3.6060604@timgolden.me.uk> Message-ID: <1332663120.38220.YahooMailNeo@web110705.mail.gq1.yahoo.com> >________________________________ > From: Tim Golden >To: Albert-Jan Roskam >Cc: Python Mailing List >Sent: Saturday, March 24, 2012 11:25 PM >Subject: Re: [Tutor] getUncPath(mappedDrive) > >On 24/03/2012 21:29, Albert-Jan Roskam wrote: >>? ? Thanks! This seems a feasible approach. I have found this Python >>? ? project that exposes some of the functions of mpr.dll: >>? ? http://sourceforge.net/projects/wnetconnect/ WNetGetConnection is >>? ? not among the functions, but the code will help. I have to read up >>? ? on ctypes.Structure though as I never really understood this. > >This particular function call doesn't require too much work >in fact. Something like the following code -- error-handling >mostly omitted -- should do the trick: > > >import ctypes ># ># Get the ANSI version of the function from its DLL ># >WNetGetConnection = ctypes.windll.mpr.WNetGetConnectionA > >ERROR_MORE_DATA = 234 > ># ># Set up the drive name to map back from ># and an empty buffer with zero length. ># >local_name = "Z:" >length = ctypes.c_long (0) >remote_name = ctypes.create_string_buffer ("") > ># ># Call the function, expecting to receive an ERROR_MORE_DATA ># result, which indicates that the buffer is too small and ># which populates the length field with the right length. ># >result = WNetGetConnection ( >? local_name, >? remote_name, >? ctypes.byref (length) >) ># ># Assuming we did get that error, recreate the buffer and ># call again with the supplied length. This isn't strictly ># necessary (you could probably get away with hard-coding ># 2048 or whatever) but it does save you having to guess. ># >if result == ERROR_MORE_DATA: >? remote_name = ctypes.create_string_buffer (length.value) >? result = WNetGetConnection ( >? ? local_name, >? ? remote_name, >? ? ctypes.byref (length) >? ) > ># ># If the result of either call was an error, raise an Exception ># >if result != 0: >? raise RuntimeError ("Error %d" % result) > >print "Remote name is", remote_name.value > > > >TJG > >Hi Tim, > >Thank you so much for this! I think this would also be a valuable addition to os.path (where I'd expect it to be). >You call WNetGetConnection twice: one time with a 'dummy' string buffer, and one time with a buffer of the exact required length. If I'd run a function getUncPath() on a gazillion paths, wouldn't it be more effcient to hard-code the length to 2048 as you suggest in your comment? > >Regards, >Albert-Jan > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Sun Mar 25 10:18:58 2012 From: mail at timgolden.me.uk (Tim Golden) Date: Sun, 25 Mar 2012 09:18:58 +0100 Subject: [Tutor] getUncPath(mappedDrive) In-Reply-To: <1332663120.38220.YahooMailNeo@web110705.mail.gq1.yahoo.com> References: <1332620033.41135.YahooMailNeo@web110704.mail.gq1.yahoo.com> <4F6E2CF6.6030205@timgolden.me.uk> <1332624583.21709.YahooMailNeo@web110712.mail.gq1.yahoo.com> <4F6E49E3.6060604@timgolden.me.uk> <1332663120.38220.YahooMailNeo@web110705.mail.gq1.yahoo.com> Message-ID: <4F6ED4F2.8090706@timgolden.me.uk> On 25/03/2012 09:12, Albert-Jan Roskam wrote: > Thank you so much for this! I think this would also be a valuable > addition to os.path (where I'd expect it to be). > You call WNetGetConnection twice: one time with a 'dummy' string > buffer, and one time with a buffer of the exact required length. If > I'd run a function getUncPath() on a gazillion paths, wouldn't it be > more effcient to hard-code the length to 2048 as you suggest in your > comment? The fail-and-resize-the-buffer dance is fairly common on Windows. The advantage of the technique is that it will cope with any path length. If you hardcode to 2048 (or whatever length) then the time will come when you'll encounter a longer path and then you'll have to rewrite your code with 4096 or 8192 etc. Obviously, if you have control over all the paths you're interested in, and you know that they can't grow beyond MAXLEN characters, then by all means use MAXLEN as the buffer size and shorten your code. In terms of efficiency, I imagine you'd have to run the function on an unusually high number of paths -- and you've only got 26 possible drive letters in the first place -- so it looks to me like a premature optimisation! TJG From joel.goldstick at gmail.com Sun Mar 25 15:45:41 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sun, 25 Mar 2012 09:45:41 -0400 Subject: [Tutor] Question about input In-Reply-To: References: Message-ID: On Sun, Mar 25, 2012 at 1:31 AM, Asif Kazmi wrote: > Hello, > > I'm going through Python Programming for the Absolute Beginner, 3rd edition, > on a Mac with Python 3.2. > > In the second chapter, the book gives sample code that shows how a logical > error can occur: > > # Trust Fund Buddy - Bad > # Demonstrates a logical error > > print( > """ > ? ? ? ? ? ? Trust Fund Buddy > > Totals your monthly spending so that your trust fund doesn't run out > (and you're forced to get a real job). > > Please enter the requested, monthly costs. ?Since you're rich, ignore > pennies > and use only dollar amounts. > > """ > ) > > car = input("Lamborghini Tune-Ups: ") > rent = input("Manhattan Apartment: ") > jet = input("Private Jet Rental: ") > gifts = input("Gifts: ") > food = input("Dining Out: ") > staff = input("Staff (butlers, chef, driver, assistant): ") > guru = input("Personal Guru and Coach: ") > games = input("Computer Games: ") > > total = car + rent + jet + gifts + food + staff + guru + games > > print("\nGrand Total:", total) > > input("\n\nPress the enter key to exit.") > > > This program should show the inputted numbers as a concatenation rather than > a sum, I understand that is the mistake in the code. However, when I run it, > it shows: > > Grand Total: 111Manhattan Apartment: 111Private Jet Rental: 111Gifts: > 111Dining Out: 111Staff (butlers, chef, driver, assistant): 111Personal Guru > and Coach: 111Computer Games: 111 > > It appears to be adding the input prompt as part of the variables? except > for car? What am I missing? > > Thanks, > Asif > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Input returns a string in python 3. So you are doing something like '1' + '1' ... etc which will concatinate the strings. Test it out by typing in something other than a number for your inputs. Once you get that worked out, see what your code produces. -- Joel Goldstick From akazmi001 at gmail.com Sun Mar 25 17:52:25 2012 From: akazmi001 at gmail.com (Asif Kazmi) Date: Sun, 25 Mar 2012 11:52:25 -0400 Subject: [Tutor] Question about input In-Reply-To: References: Message-ID: The odd thing is that the same code runs perfectly in the Mac terminal, but incorrectly in Komodo Edit. In the latter, the input prompts are somehow being included into the variables themselves somehow due to the way Komodo works. Thanks for the help. I've just taken to running the code in the Mac terminal which is working great. Asif On Sun, Mar 25, 2012 at 9:45 AM, Joel Goldstick wrote: > On Sun, Mar 25, 2012 at 1:31 AM, Asif Kazmi wrote: > > Hello, > > > > I'm going through Python Programming for the Absolute Beginner, 3rd > edition, > > on a Mac with Python 3.2. > > > > In the second chapter, the book gives sample code that shows how a > logical > > error can occur: > > > > # Trust Fund Buddy - Bad > > # Demonstrates a logical error > > > > print( > > """ > > Trust Fund Buddy > > > > Totals your monthly spending so that your trust fund doesn't run out > > (and you're forced to get a real job). > > > > Please enter the requested, monthly costs. Since you're rich, ignore > > pennies > > and use only dollar amounts. > > > > """ > > ) > > > > car = input("Lamborghini Tune-Ups: ") > > rent = input("Manhattan Apartment: ") > > jet = input("Private Jet Rental: ") > > gifts = input("Gifts: ") > > food = input("Dining Out: ") > > staff = input("Staff (butlers, chef, driver, assistant): ") > > guru = input("Personal Guru and Coach: ") > > games = input("Computer Games: ") > > > > total = car + rent + jet + gifts + food + staff + guru + games > > > > print("\nGrand Total:", total) > > > > input("\n\nPress the enter key to exit.") > > > > > > This program should show the inputted numbers as a concatenation rather > than > > a sum, I understand that is the mistake in the code. However, when I run > it, > > it shows: > > > > Grand Total: 111Manhattan Apartment: 111Private Jet Rental: 111Gifts: > > 111Dining Out: 111Staff (butlers, chef, driver, assistant): 111Personal > Guru > > and Coach: 111Computer Games: 111 > > > > It appears to be adding the input prompt as part of the variables? except > > for car? What am I missing? > > > > Thanks, > > Asif > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > > Input returns a string in python 3. So you are doing something like > '1' + '1' ... etc which will concatinate the strings. Test it out by > typing in something other than a number for your inputs. > > Once you get that worked out, see what your code produces. > > > -- > Joel Goldstick > -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Sun Mar 25 18:00:42 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 25 Mar 2012 17:00:42 +0100 Subject: [Tutor] Error handling In-Reply-To: <1332660170.3671.45.camel@launcelot.winder.org.uk> References: <1332660170.3671.45.camel@launcelot.winder.org.uk> Message-ID: On 25/03/2012 08:22, Russel Winder wrote: > Michael, > > On Sat, 2012-03-24 at 15:20 -0700, Michael Lewis wrote: > [...] > > It is perhaps worth noting that in Python 3, the syntax has changed: > >> import os, errno >> try: >> >> os.makedirs('a/b/c') >> except OSError, e: > > except OSError as e : > >> >> if e.errno != errno.EEXIST: >> >> raise > > This "as" syntax works in 2.6 and 2.7 so is probably the syntax to use > unless you have to use very old versions of Python. I think the "as" > syntax makes it clearer that e is a variable referring to the instance > of OSError that causes the except clause to execute if it does. > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor It's worth noting that PEP 3151 has been implemented in Python 3.3 see http://docs.python.org/dev/whatsnew/3.3.html#pep-3151-reworking-the-os-and-io-exception-hierarchy Quoting from the above link. "Thanks to the new exceptions, common usages of the errno can now be avoided. For example, the following code written for Python 3.2: from errno import ENOENT, EACCES, EPERM try: with open("document.txt") as f: content = f.read() except IOError as err: if err.errno == ENOENT: print("document.txt file is missing") elif err.errno in (EACCES, EPERM): print("You are not allowed to read document.txt") else: raise can now be written without the errno import and without manual inspection of exception attributes: try: with open("document.txt") as f: content = f.read() except FileNotFoundError: print("document.txt file is missing") except PermissionError: print("You are not allowed to read document.txt") " -- Cheers. Mark Lawrence. From joel.goldstick at gmail.com Sun Mar 25 18:06:11 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sun, 25 Mar 2012 12:06:11 -0400 Subject: [Tutor] Question about input In-Reply-To: References: Message-ID: On Sun, Mar 25, 2012 at 11:52 AM, Asif Kazmi wrote: > The odd thing is that the same code runs perfectly in the Mac terminal, but > incorrectly in Komodo Edit. In the latter, the input prompts are somehow > being included ?into the variables themselves somehow due to the way Komodo > works. > > Thanks for the help. I've just taken to running the code in the Mac terminal > which is working great. > > Asif Are you sure that you are running python 3.x in each environment? I'm not familiar with Komodo, so I can't help you there, but in python v2.x input attempts to evaluate the values you enter. raw_input, on the other hand returns your data as a string. In python 3, input was removed and raw_input's name was changed to input. See if you have two different versions of python on your system. > > On Sun, Mar 25, 2012 at 9:45 AM, Joel Goldstick > wrote: >> >> On Sun, Mar 25, 2012 at 1:31 AM, Asif Kazmi wrote: >> > Hello, >> > >> > I'm going through Python Programming for the Absolute Beginner, 3rd >> > edition, >> > on a Mac with Python 3.2. >> > >> > In the second chapter, the book gives sample code that shows how a >> > logical >> > error can occur: >> > >> > # Trust Fund Buddy - Bad >> > # Demonstrates a logical error >> > >> > print( >> > """ >> > ? ? ? ? ? ? Trust Fund Buddy >> > >> > Totals your monthly spending so that your trust fund doesn't run out >> > (and you're forced to get a real job). >> > >> > Please enter the requested, monthly costs. ?Since you're rich, ignore >> > pennies >> > and use only dollar amounts. >> > >> > """ >> > ) >> > >> > car = input("Lamborghini Tune-Ups: ") >> > rent = input("Manhattan Apartment: ") >> > jet = input("Private Jet Rental: ") >> > gifts = input("Gifts: ") >> > food = input("Dining Out: ") >> > staff = input("Staff (butlers, chef, driver, assistant): ") >> > guru = input("Personal Guru and Coach: ") >> > games = input("Computer Games: ") >> > >> > total = car + rent + jet + gifts + food + staff + guru + games >> > >> > print("\nGrand Total:", total) >> > >> > input("\n\nPress the enter key to exit.") >> > >> > >> > This program should show the inputted numbers as a concatenation rather >> > than >> > a sum, I understand that is the mistake in the code. However, when I run >> > it, >> > it shows: >> > >> > Grand Total: 111Manhattan Apartment: 111Private Jet Rental: 111Gifts: >> > 111Dining Out: 111Staff (butlers, chef, driver, assistant): 111Personal >> > Guru >> > and Coach: 111Computer Games: 111 >> > >> > It appears to be adding the input prompt as part of the variables? >> > except >> > for car? What am I missing? >> > >> > Thanks, >> > Asif >> > >> > _______________________________________________ >> > Tutor maillist ?- ?Tutor at python.org >> > To unsubscribe or change subscription options: >> > http://mail.python.org/mailman/listinfo/tutor >> > >> Input returns a string in python 3. ?So you are doing something like >> '1' + '1' ... etc which will concatinate the strings. ?Test it out by >> typing in something other than a number for your inputs. >> >> Once you get that worked out, see what your code produces. >> >> >> -- >> Joel Goldstick > > -- Joel Goldstick From mjolewis at gmail.com Sun Mar 25 18:54:35 2012 From: mjolewis at gmail.com (Michael Lewis) Date: Sun, 25 Mar 2012 09:54:35 -0700 Subject: [Tutor] Error Handling Message-ID: In the below block, why is the if statement e.errno != errno.EEXIST? Why can the errno be both before and after the "."? import os, errno try: os.makedirs('a/b/c') except OSError, e: if e.errno != errno.EEXIST: raise -- Michael J. Lewis mjolewis at gmail.com 415.815.7257 -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Sun Mar 25 19:18:34 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sun, 25 Mar 2012 13:18:34 -0400 Subject: [Tutor] Error Handling In-Reply-To: References: Message-ID: On Sun, Mar 25, 2012 at 12:54 PM, Michael Lewis wrote: > In the below block, why is the if statement e.errno != errno.EEXIST? > Why can the errno be both before and after the "."? > > > > import os, errno > try: > ? ? os.makedirs('a/b/c') > except OSError, e: > ? ? if e.errno != errno.EEXIST: > ? ? ? ? raise errno is a dictionary of standard errors. You can learn about it in the python shell by importing errno then typing help(errno) or dir(errno). So, errno.EEXIST is just the number 17 as it turns out e is an exception object. It has an attribute called errno which identifies what the error number is. So this is just comparing what your actual error is to the EEXIST number. If it isn't that, then you 'raise' > > > -- > Michael J. Lewis > > mjolewis at gmail.com > 415.815.7257 > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick From mjolewis at gmail.com Sun Mar 25 22:52:25 2012 From: mjolewis at gmail.com (Michael Lewis) Date: Sun, 25 Mar 2012 13:52:25 -0700 Subject: [Tutor] Permissions Error Message-ID: Hi everyone, If I've created a folder, why would I receive a permissions error when trying to copy the file. My source code is here: http://pastebin.com/1iX7pGDw When I check the properties/security of the file in question, the system says I have full control. Thanks. -- Michael Lewis -------------- next part -------------- An HTML attachment was scrubbed... URL: From evert.rol at gmail.com Mon Mar 26 01:10:50 2012 From: evert.rol at gmail.com (Evert Rol) Date: Mon, 26 Mar 2012 01:10:50 +0200 Subject: [Tutor] Permissions Error In-Reply-To: References: Message-ID: > Hi everyone, > > If I've created a folder, why would I receive a permissions error when trying to copy the file. My source code is here: > http://pastebin.com/1iX7pGDw What's the permission error you get? Can't you copy the file, or not create the destination directory? Or you may not be allowed to remove the file in the destination directory if it already exists. Giving the traceback could be useful. > When I check the properties/security of the file in question, the system says I have full control. I think that copying file depends on the permissions of the folder, not the file. Not sure though, and it may depend on the OS in question. Cheers, Evert From steve at pearwood.info Mon Mar 26 01:52:19 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 26 Mar 2012 10:52:19 +1100 Subject: [Tutor] Permissions Error In-Reply-To: References: Message-ID: <4F6FAFB3.4060301@pearwood.info> Michael Lewis wrote: > Hi everyone, > > If I've created a folder, why would I receive a permissions error when > trying to copy the file. My source code is here: > http://pastebin.com/1iX7pGDw The usual answer to "why would I receive a permissions error" is that you don't actually have permission to access the file. What is the actual error you get? > When I check the properties/security of the file in question, the system > says I have full control. This does not sound like a Python problem, but an operating system problem. What OS are you using? You should check the permissions on the folder, not just the file. Also, if you OS supports it, check any extended permissions and ACLs that might apply. Can you copy the file using another language, e.g. using powershell, bash or applescript? Also check that you are running the Python script as the same user you used when creating the file. -- Steven From elainahyde at gmail.com Mon Mar 26 11:38:25 2012 From: elainahyde at gmail.com (Elaina Ann Hyde) Date: Mon, 26 Mar 2012 20:38:25 +1100 Subject: [Tutor] plotting several datasets and calling data from afar Message-ID: Hi everyone, I am trying to set up a code to do some plotting and before I get too far I wanted to ask some structure questions. Basically I want to tell python to read 2 datasets, plot them on the same scale on the same x-y axis , read a third dataset and match the name from the first dataset, then label certain values from the third... complicating matters is that all these data are part of much, much larger sets in seperate files, the paths look like: pathway1/namered.dat pathway2/nameblue.dat matchingfile.txt so I do fopen on the matchingfile, read it with asciitable, and then I have a column in that file called 'name' and a column called 'M', I sort the file, return a subset that is interesting, and get name1, name2, etc for every subset. I want to make a plot that looks like: plot pathway1/namered.dat and pathway2/nameblue.dat with label 'M' for every value in the subset name1, each row[i] I need to assign to a seperate window so that I get a multiplot with a shared x-axis, and stacking my plots up the y-axis. I do have multiplot working and I know how to plot 'M' for each subset. The conceptual trouble has come in, how do I match 'name' variable of my subset 'name1' with the plot I want to do for pathway1/namered.dat and pathway2/nameblue.dat... the key feature that is the same is the 'name' variable, but in one instance I have to match the 'name'+'red.dat' and in the other the 'name'+'blue.dat' Any ideas would be appreciated, thanks! ~Elaina Hyde -- PhD Candidate Department of Physics and Astronomy Faculty of Science Macquarie University North Ryde, NSW 2109, Australia -------------- next part -------------- An HTML attachment was scrubbed... URL: From evert.rol at gmail.com Mon Mar 26 14:14:26 2012 From: evert.rol at gmail.com (Evert Rol) Date: Mon, 26 Mar 2012 14:14:26 +0200 Subject: [Tutor] plotting several datasets and calling data from afar In-Reply-To: References: Message-ID: <9CC3EBA7-3C9F-41C6-B080-784E1EFC630E@gmail.com> Hi Elaina, > Hi everyone, > I am trying to set up a code to do some plotting and before I get too far I wanted to ask some structure questions. Basically I want to tell python to read 2 datasets, plot them on the same scale on the same x-y axis , read a third dataset and match the name from the first dataset, then label certain values from the third... complicating matters is that all these data are part of much, much larger sets in seperate files, the paths look like: > pathway1/namered.dat > pathway2/nameblue.dat > matchingfile.txt > > so I do fopen on the matchingfile, read it with asciitable, and then I have a column in that file called 'name' and a column called 'M', I sort the file, return a subset that is interesting, and get name1, name2, etc for every subset. I want to make a plot that looks like: > > plot pathway1/namered.dat and pathway2/nameblue.dat with label 'M' for every value in the subset name1, each row[i] I need to assign to a seperate window so that I get a multiplot with a shared x-axis, and stacking my plots up the y-axis. I do have multiplot working and I know how to plot 'M' for each subset. > > The conceptual trouble has come in, how do I match 'name' variable of my subset 'name1' with the plot I want to do for pathway1/namered.dat and pathway2/nameblue.dat... the key feature that is the same is the 'name' variable, but in one instance I have to match the 'name'+'red.dat' and in the other the 'name'+'blue.dat' It's not 100% clear to me what you precisely want to do, but here are a few possibilites: - use a dictionary. Assign each dataset to a dictionary with the name as the key (or the name + color). Eg, dataset['name1red'], dataset['name1blue'], dataset['name2red'] etc. Each value in this dictionary is a dataset read by asciitable. the (big) disadvantage is that you would read every single *.dat file beforehand - simply fopen the files with the filename deduced from the name. So, in a loop, that would be something like for name in subset_names: with fopen(name + 'red.dat') as datafile: # read data and plot with fopen(name + 'blue.dat') as datafile: # read data and plot But perhaps I misunderstand your problem. I can't really tell if the problem is in opening the selected data files, or plotting them, or creating the labels for the plot. This may actually be where some code comes in handy. Provided the plotting isn't the problem, you could make a very simple Python script that shows the concept and how you attempt to solve it. The simpler the script, the better probably the implementation, so even make such a simple script is incredibly useful. (Any example data sets of, say, just 2 lines each can also help with that.) From that, the problem may become clearer and we can help you improving the script. Of course, someone else may actually understand the problem properly and has a better suggestion. Cheers, Evert (yes, small world ;-) > Any ideas would be appreciated, thanks! > ~Elaina Hyde > > -- > PhD Candidate > Department of Physics and Astronomy > Faculty of Science > Macquarie University > North Ryde, NSW 2109, Australia > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From abhishek.vit at gmail.com Mon Mar 26 20:05:09 2012 From: abhishek.vit at gmail.com (Abhishek Pratap) Date: Mon, 26 Mar 2012 11:05:09 -0700 Subject: [Tutor] concurrent file reading using python Message-ID: Hi Guys I want to utilize the power of cores on my server and read big files (> 50Gb) simultaneously by seeking to N locations. Process each separate chunk and merge the output. Very similar to MapReduce concept. What I want to know is the best way to read a file concurrently. I have read about file-handle.seek(), os.lseek() but not sure if thats the way to go. Any used cases would be of help. PS: did find some links on stackoverflow but it was not clear to me if I found the right solution. Thanks! -Abhi From ramit.prasad at jpmorgan.com Mon Mar 26 21:02:52 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Mon, 26 Mar 2012 19:02:52 +0000 Subject: [Tutor] concurrent file reading using python In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF4740928C044@SCACMX008.exchad.jpmchase.net> > I want to utilize the power of cores on my server and read big files > (> 50Gb) simultaneously by seeking to N locations. Process each > separate chunk and merge the output. Very similar to MapReduce > concept. > > What I want to know is the best way to read a file concurrently. I > have read about file-handle.seek(), os.lseek() but not sure if thats > the way to go. Any used cases would be of help. > > PS: did find some links on stackoverflow but it was not clear to me if > I found the right solution. > Have you done any testing in this space? I would assume you would be memory/IO bound and not CPU bound. Using multiple cores would not help non-CPU bound tasks. I would try and write an initial program that does what you want without attempting to optimize and then do some profiling to see if you are using waiting on the CPU or if you are (as I suspect) waiting on hard disk / memory. Actually, if you only need small chunks of the file at a time and you iterate over the file (for line in file-handle:) instead of using file-handle.readlines() you will probably only be IO bound due to the way Python file handling works. But either way, test first then optimize. :) Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From steve at pearwood.info Tue Mar 27 00:21:13 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 27 Mar 2012 09:21:13 +1100 Subject: [Tutor] concurrent file reading using python In-Reply-To: References: Message-ID: <4F70EBD9.1030101@pearwood.info> Abhishek Pratap wrote: > Hi Guys > > > I want to utilize the power of cores on my server and read big files > (> 50Gb) simultaneously by seeking to N locations. Yes, you have many cores on the server. But how many hard drives is each file on? If all the files are on one disk, then you will *kill* performance dead by forcing the drive to seek backwards and forwards: seek to 12345678 read a block seek to 9947500 read a block seek to 5891124 read a block seek back to 12345678 + 1 block read another block seek back to 9947500 + 1 block read another block ... The drive will spend most of its time seeking instead of reading. Even if you have multiple hard drives in a RAID array, performance will depend strongly the details of how it is configured (RAID1, RAID0, software RAID, hardware RAID, etc.) and how smart the controller is. Chances are, though, that the controller won't be smart enough. Particularly if you have hardware RAID, which in my experience tends to be more expensive and less useful than software RAID (at least for Linux). And what are you planning on doing with the files once you have read them? I don't know how much memory your server has got, but I'd be very surprised if you can fit the entire > 50 GB file in RAM at once. So you're going to read the files and merge the output... by writing them to the disk. Now you have the drive trying to read *and* write simultaneously. TL; DR: Tasks which are limited by disk IO are not made faster by using a faster CPU, since the bottleneck is disk access, not CPU speed. Back in the Ancient Days when tape was the only storage medium, there were a lot of programs optimised for slow IO. Unfortunately this is pretty much a lost art -- although disk access is thousands or tens of thousands of times slower than memory access, it is so much faster than tape that people don't seem to care much about optimising disk access. > What I want to know is the best way to read a file concurrently. I > have read about file-handle.seek(), os.lseek() but not sure if thats > the way to go. Any used cases would be of help. Optimising concurrent disk access is a specialist field. You may be better off asking for help on the main Python list, comp.lang.python or python-list at python.org, and hope somebody has some experience with this. But chances are very high that you will need to search the web for forums dedicated to concurrent disk access, and translate from whatever language(s) they are using to Python. -- Steven From abhishek.vit at gmail.com Tue Mar 27 00:46:53 2012 From: abhishek.vit at gmail.com (Abhishek Pratap) Date: Mon, 26 Mar 2012 15:46:53 -0700 Subject: [Tutor] concurrent file reading using python In-Reply-To: References: Message-ID: Thanks Walter and Steven for the insight. I guess I will post my question to python main mailing list and see if people have anything to say. -Abhi On Mon, Mar 26, 2012 at 3:28 PM, Walter Prins wrote: > Abhi, > > On 26 March 2012 19:05, Abhishek Pratap wrote: >> I want to utilize the power of cores on my server and read big files >> (> 50Gb) simultaneously by seeking to N locations. Process each >> separate chunk and merge the output. Very similar to MapReduce >> concept. >> >> What I want to know is the best way to read a file concurrently. I >> have read about file-handle.seek(), ?os.lseek() but not sure if thats >> the way to go. Any used cases would be of help. > > Your idea won't work. ?Reading from disk is not a CPU-bound process, > it's an I/O bound process. ?Meaning, the speed by which you can read > from a conventional mechanical hard disk drive is not constrained by > how fast your CPU is, but generally by how fast your disk(s) can read > data from the disk surface, which is limited by the rotation speed and > areal density of the data on the disk (and the seek time), and by how > fast it can shovel the data down it's I/O bus. ?And *that* speed is > still orders of magnitude slower than your RAM and your CPU. ?So, in > reality even just one of your cores will spend the vast majority of > its time waiting for the disk when reading your 50GB file. ?There's > therefore __no__ way to make your file reading faster by increasing > your __CPU cores__ -- the only way is by improving your disk I/O > throughput. ?You can for example stripe several hard disks together in > RAID0 (but that increases the risk of data loss due to data being > spread over multiple drives) and/or ensure you use a faster I/O > subsystem (move to SATA3 if you're currently using SATA2 for example), > and/or use faster hard disks (use 10,000 or 15,000 RPM instead of > 7,200, or switch to SSD [solid state] disks.) ?Most of these options > will cost you a fair bit of money though, so consider these thoughts > in that light. > > Walter From elainahyde at gmail.com Tue Mar 27 02:58:38 2012 From: elainahyde at gmail.com (Elaina Ann Hyde) Date: Tue, 27 Mar 2012 11:58:38 +1100 Subject: [Tutor] plotting several datasets and calling data from afar In-Reply-To: <9CC3EBA7-3C9F-41C6-B080-784E1EFC630E@gmail.com> References: <9CC3EBA7-3C9F-41C6-B080-784E1EFC630E@gmail.com> Message-ID: On Mon, Mar 26, 2012 at 11:14 PM, Evert Rol wrote: > Hi Elaina, > > > > Hi everyone, > > I am trying to set up a code to do some plotting and before I get too > far I wanted to ask some structure questions. Basically I want to tell > python to read 2 datasets, plot them on the same scale on the same x-y axis > , read a third dataset and match the name from the first dataset, then > label certain values from the third... complicating matters is that all > these data are part of much, much larger sets in seperate files, the paths > look like: > > pathway1/namered.dat > > pathway2/nameblue.dat > > matchingfile.txt > > > > so I do fopen on the matchingfile, read it with asciitable, and then I > have a column in that file called 'name' and a column called 'M', I sort > the file, return a subset that is interesting, and get name1, name2, etc > for every subset. I want to make a plot that looks like: > > > > plot pathway1/namered.dat and pathway2/nameblue.dat with label 'M' for > every value in the subset name1, each row[i] I need to assign to a seperate > window so that I get a multiplot with a shared x-axis, and stacking my > plots up the y-axis. I do have multiplot working and I know how to plot > 'M' for each subset. > > > > The conceptual trouble has come in, how do I match 'name' variable of my > subset 'name1' with the plot I want to do for pathway1/namered.dat and > pathway2/nameblue.dat... the key feature that is the same is the 'name' > variable, but in one instance I have to match the 'name'+'red.dat' and in > the other the 'name'+'blue.dat' > > It's not 100% clear to me what you precisely want to do, but here are a > few possibilites: > > - use a dictionary. Assign each dataset to a dictionary with the name as > the key (or the name + color). Eg, dataset['name1red'], > dataset['name1blue'], dataset['name2red'] etc. Each value in this > dictionary is a dataset read by asciitable. > the (big) disadvantage is that you would read every single *.dat file > beforehand > - simply fopen the files with the filename deduced from the name. So, in a > loop, that would be something like > for name in subset_names: > with fopen(name + 'red.dat') as datafile: > # read data and plot > with fopen(name + 'blue.dat') as datafile: > # read data and plot > > But perhaps I misunderstand your problem. I can't really tell if the > problem is in opening the selected data files, or plotting them, or > creating the labels for the plot. > This may actually be where some code comes in handy. Provided the plotting > isn't the problem, you could make a very simple Python script that shows > the concept and how you attempt to solve it. The simpler the script, the > better probably the implementation, so even make such a simple script is > incredibly useful. (Any example data sets of, say, just 2 lines each can > also help with that.) > From that, the problem may become clearer and we can help you improving > the script. > > Of course, someone else may actually understand the problem properly and > has a better suggestion. > > Cheers, > > Evert > > (yes, small world ;-) > > > > Any ideas would be appreciated, thanks! > > ~Elaina Hyde > > > > -- > > PhD Candidate > > Department of Physics and Astronomy > > Faculty of Science > > Macquarie University > > North Ryde, NSW 2109, Australia > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > --------------------------------- Thanks Evert and Tino, The dictionaries look a bit like the right idea, but in the end I was able to manipulate my input table so they aren't quite necessary. The code I have now, which partially works, is as follows: ---------------------------- #!/usr/bin/python # import modules used here import sys import asciitable import matplotlib import matplotlib.path as mpath import matplotlib.pyplot as plt from matplotlib.pyplot import figure, show, axis from matplotlib.patches import Ellipse import scipy import numpy as np from numpy import * import math import pylab import random from pylab import * import astropysics import astropysics.obstools import astropysics.coords import string from astropysics.coords import ICRSCoordinates,GalacticCoordinates #File from Read_All x=open('LowZ_joinAll') dat=asciitable.read(x,Reader=asciitable.NoHeader, fill_values=['--','-999.99']) #gives dat file where filenames are first two columns ############################### bluefilename1=dat['col1'] filename1=dat['col2'] #other stuff I need #Ra/Dec in decimal radians Radeg1=dat[ 'col6']*180./math.pi #ra-drad Decdeg1=dat['col7']*180./math.pi #dec-drad Vmag=dat['col8'] Mag=dat['col15'] EW1=dat['col16'] EW2=dat['col17'] EW3=dat['col18'] #Horizontal Branch Estimate VHB=18.0 EWn = (0.5*abs(EW1)) + abs(EW2) + (0.6*abs(EW3)) # NEED ABS VALUE FOR FORMULA FEHn = -2.66 + 0.42*(EWn + 0.64*(Vmag - VHB)) EW1_G=dat['col23'] EW2_G=dat['col24'] EW3_G=dat['col25'] EWg = (0.5*abs(EW1_G)) + abs(EW2_G) + (0.6*abs(EW3_G)) FEHg = -2.66 + 0.42*(EWg + 0.64*(Vmag - VHB)) #use 0.15-0.2 dex as standard error -- R. Ibata FEHerror=0.2 #corrected velocity Vhel=dat['col37'] V_err=dat['col38'] m_H=dat['col74'] alpha_Fe=dat['col75'] microturb=dat['col76'] Vrot=dat['col77'] Chisq=dat['col78'] RVorig=dat['col79'] RVcorr=dat['col80'] Heliocentric_RV=RVorig+RVcorr #now if I want to make plots I have to access paths #example, trying with one element path1r='../Core2dfdr-red-sorted/'+filename1[1] path1b='../Core2dfdr-blue/'+bluefilename1[1] #and use a title in the plot title1='Data Fe/Hn='+str(FEHn[1])+' Fe/Hg='+str(FEHg[1]) for i in xrange(len(Radeg1)): if i<=5: #subset1 print 'filename= ',filename1[i],' ',bluefilename1[i],' FEHn= ',FEHn[i],' FEHg= ',FEHg[i] #multiplot1 fig1, (ax1, ax2, ax3, ax4, ax5) = plt.subplots(5, sharex=True) ax1.plot(path1r,'--ro') ax1.plot(path1b,'--bo') # ax1.set_title('Data Fe/Hn='+str(FEHn[1])+' Fe/Hg='+str(FEHg[1]), fontsize='11') # ax2.plot('../Core2dfdr-red-sorted/'filename1[2],'--ro') # ax2.plot('../Core2dfdr-blue/'filenameblueb[2],'--bo') # ax2.set_title('Data Fe/Hn='FEHn[2]' Fe/Hg='FEHg[2], fontsize='11') # ax3.plot('../Core2dfdr-red-sorted/'filename1[3],'--ro') # ax3.plot('../Core2dfdr-blue/'filenameblueb[3],'--bo') # ax3.set_title('Data Fe/Hn='FEHn[3]' Fe/Hg='FEHg[3], fontsize='11') # ax4.plot('../Core2dfdr-red-sorted/'filename1[4],'--ro') # ax4.plot('../Core2dfdr-blue/'filenameblueb[4],'--bo') # ax4.set_title('Data Fe/Hn='FEHn[4]' Fe/Hg='FEHg[4], fontsize='11') # ax5.plot('../Core2dfdr-red-sorted/'filename1[5],'--ro') # ax5.plot('../Core2dfdr-blue/'filenameblueb[5],'--bo') # ax5.set_title('Data Fe/Hn='FEHn[5]' Fe/Hg='FEHg[5], fontsize='11') plt.show() #subset2 # if i>5 and i<=10: # print 'filename= ',filename1[i],' FEHn= ',FEHn[i],' FEHg= ',FEHg[i] ..... this is where it breaks down. The path name it cannot follow, and the title is not fully a string. Since I will want to do this for many subset's I would prefer to loop but I don't see a good way to do that. If I try with just one element I get the error: filename= 100604F2_1red.0063.fits 100604F2_1blueb.0063.fits FEHn= -3.16295 FEHg= -3.216626 Traceback (most recent call last): File "plot_LowZ_targets.py", line 232, in ax1.plot(path1r,'--ro') File "/Library/Frameworks/Python.framework/Versions/7.2/lib/python2.7/site-packages/matplotlib/axes.py", line 3849, in plot self.add_line(line) File "/Library/Frameworks/Python.framework/Versions/7.2/lib/python2.7/site-packages/matplotlib/axes.py", line 1443, in add_line self._update_line_limits(line) File "/Library/Frameworks/Python.framework/Versions/7.2/lib/python2.7/site-packages/matplotlib/axes.py", line 1451, in _update_line_limits p = line.get_path() File "/Library/Frameworks/Python.framework/Versions/7.2/lib/python2.7/site-packages/matplotlib/lines.py", line 644, in get_path self.recache() File "/Library/Frameworks/Python.framework/Versions/7.2/lib/python2.7/site-packages/matplotlib/lines.py", line 401, in recache y = np.asarray(yconv, np.float_) File "/Library/Frameworks/Python.framework/Versions/7.2/lib/python2.7/site-packages/numpy/core/numeric.py", line 235, in asarray return array(a, dtype, copy=False, order=order) ValueError: could not convert string to float: ../Core2dfdr-red-sorted/100604F2_2red.0063.fits .......... Note that the print statement I put in works, so the correct values are called. I just haven't assigned in a way that python can read, and look at the path. Trying to make my path variables strings doesn't seem to work either, so I'm a little lost. Thanks everyone, and yes, small world Evert! ~Elaina -- PhD Candidate Department of Physics and Astronomy Faculty of Science Macquarie University North Ryde, NSW 2109, Australia -------------- next part -------------- An HTML attachment was scrubbed... URL: From thaonphuong at gmail.com Tue Mar 27 03:08:29 2012 From: thaonphuong at gmail.com (thao nguyen) Date: Tue, 27 Mar 2012 08:08:29 +0700 Subject: [Tutor] (no subject) Message-ID: Dear Support Team, I have built a function (enclosed here) to merge many files (in this example is 2 files: "a1.txt" and "a2.txt") lines by lines. The output file is called "final_file". However, i could not have it run successfully. Content of "a1.txt": 1 3 5 Content of "a2.txt": 2 4 6 Content of "final_file.txt" will be like: 1 2 3 4 5 6 In Python, i called just written module: import argument reload(argument) argument.test(2,"C:/a1.txt","C:/a2.txt") and get the error as below: "ValueError: I/O operation on closed file File "c:\append.py", line 5, in argument.test(2,"C:/a1.txt","C:/a2.txt") File "c:\argument.py", line 28, in test for line_data in f:" Could you please advise the resolution for this? Thank you -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: append.py Type: application/octet-stream Size: 80 bytes Desc: not available URL: From mjolewis at gmail.com Tue Mar 27 06:00:58 2012 From: mjolewis at gmail.com (Michael Lewis) Date: Mon, 26 Mar 2012 21:00:58 -0700 Subject: [Tutor] Permissions Error Message-ID: > > Message: 1 > Date: Mon, 26 Mar 2012 10:52:19 +1100 > From: Steven D'Aprano > To: tutor at python.org > Subject: Re: [Tutor] Permissions Error > Message-ID: <4F6FAFB3.4060301 at pearwood.info> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Michael Lewis wrote: > > Hi everyone, > > > > If I've created a folder, why would I receive a permissions error when > > trying to copy the file. My source code is here: > > http://pastebin.com/1iX7pGDw > > The usual answer to "why would I receive a permissions error" is that you > don't actually have permission to access the file. > > What is the actual error you get? > Traceback (most recent call last): File "C:\Python27\Utilities\copyfiles.py", line 47, in copyfiles(srcdir, dstdir) File "C:\Python27\Utilities\copyfiles.py", line 42, in copyfiles shutil.copy(srcfile, dstfile) File "C:\Python27\lib\shutil.py", line 116, in copy copyfile(src, dst) File "C:\Python27\lib\shutil.py", line 81, in copyfile with open(src, 'rb') as fsrc: IOError: [Errno 13] Permission denied: 'C:\\Users\\Chief Ninja\\Pictures\\testdir' I've noticed that the code runs if I use shutil.copyfiles instead of shutil.copy. Do you know why? I've also noticed that if I have a sub-directory, I receive a permission error. However, if I use os.walk, then my code runs if I have a sub-directory in my source directory. My problem then becomes that os.walk doesn't actually move the directory, but instead just moves the files within the sub-directory. Oddly, this code runs without permission error when I use shutil.copy unlike the above piece which raises an error when I use shutil.copy. However, if I use shutil.copyfile, I get the below error: (Do you know why?) Traceback (most recent call last): File "C:/Python27/Homework/oswalk.py", line 41, in copyfiles(srcdir, dstdir) File "C:/Python27/Homework/oswalk.py", line 36, in copyfiles shutil.copyfile(srcfile, dstdir) File "C:\Python27\lib\shutil.py", line 82, in copyfile with open(dst, 'wb') as fdst: IOError: [Errno 13] Permission denied: 'C:\\newtest' The code where I use os.walk is here: http://pastebin.com/1hchnmM1 > > > When I check the properties/security of the file in question, the system > > says I have full control. > > This does not sound like a Python problem, but an operating system problem. > What OS are you using? > I am using Windows XP > > You should check the permissions on the folder, not just the file. Also, if > you OS supports it, check any extended permissions and ACLs that might > apply. > Can you copy the file using another language, e.g. using powershell, bash > or > applescript? Also check that you are running the Python script as the same > user you used when creating the file. > I've checked the permissions on the folder and I have full control. I haven't yet checked extended permissions and ACL's etc, but will do so. Thanks! > > > > -- > Steven > -------------- next part -------------- An HTML attachment was scrubbed... URL: From evert.rol at gmail.com Tue Mar 27 09:13:02 2012 From: evert.rol at gmail.com (Evert Rol) Date: Tue, 27 Mar 2012 09:13:02 +0200 Subject: [Tutor] plotting several datasets and calling data from afar In-Reply-To: References: <9CC3EBA7-3C9F-41C6-B080-784E1EFC630E@gmail.com> Message-ID: <4CEF067A-F878-4A25-BFF0-2A465483FD65@gmail.com> See below, but not all the way. Interspersed in the code. > > I am trying to set up a code to do some plotting and before I get too far I wanted to ask some structure questions. Basically I want to tell python to read 2 datasets, plot them on the same scale on the same x-y axis , read a third dataset and match the name from the first dataset, then label certain values from the third... complicating matters is that all these data are part of much, much larger sets in seperate files, the paths look like: > > pathway1/namered.dat > > pathway2/nameblue.dat > > matchingfile.txt > > > > so I do fopen on the matchingfile, read it with asciitable, and then I have a column in that file called 'name' and a column called 'M', I sort the file, return a subset that is interesting, and get name1, name2, etc for every subset. I want to make a plot that looks like: > > > > plot pathway1/namered.dat and pathway2/nameblue.dat with label 'M' for every value in the subset name1, each row[i] I need to assign to a seperate window so that I get a multiplot with a shared x-axis, and stacking my plots up the y-axis. I do have multiplot working and I know how to plot 'M' for each subset. > > > > The conceptual trouble has come in, how do I match 'name' variable of my subset 'name1' with the plot I want to do for pathway1/namered.dat and pathway2/nameblue.dat... the key feature that is the same is the 'name' variable, but in one instance I have to match the 'name'+'red.dat' and in the other the 'name'+'blue.dat' > > It's not 100% clear to me what you precisely want to do, but here are a few possibilites: > > - use a dictionary. Assign each dataset to a dictionary with the name as the key (or the name + color). Eg, dataset['name1red'], dataset['name1blue'], dataset['name2red'] etc. Each value in this dictionary is a dataset read by asciitable. > the (big) disadvantage is that you would read every single *.dat file beforehand > The dictionaries look a bit like the right idea, but in the end I was able to manipulate my input table so they aren't quite necessary. The code I have now, which partially works, is as follows: > ---------------------------- > #!/usr/bin/python > > #File from Read_All > x=open('LowZ_joinAll') > > dat=asciitable.read(x,Reader=asciitable.NoHeader, fill_values=['--','-999.99']) > #gives dat file where filenames are first two columns > > ############################### > bluefilename1=dat['col1'] > filename1=dat['col2'] > > #other stuff I need > > #Ra/Dec in decimal radians > Radeg1=dat[ 'col6']*180./math.pi #ra-drad > Decdeg1=dat['col7']*180./math.pi #dec-drad > Vmag=dat['col8'] > Mag=dat['col15'] > EW1=dat['col16'] > EW2=dat['col17'] > EW3=dat['col18'] > #Horizontal Branch Estimate > VHB=18.0 > EWn = (0.5*abs(EW1)) + abs(EW2) + (0.6*abs(EW3)) > # NEED ABS VALUE FOR FORMULA > FEHn = -2.66 + 0.42*(EWn + 0.64*(Vmag - VHB)) > EW1_G=dat['col23'] > EW2_G=dat['col24'] > EW3_G=dat['col25'] > EWg = (0.5*abs(EW1_G)) + abs(EW2_G) + (0.6*abs(EW3_G)) > FEHg = -2.66 + 0.42*(EWg + 0.64*(Vmag - VHB)) > #use 0.15-0.2 dex as standard error -- R. Ibata > FEHerror=0.2 > #corrected velocity > Vhel=dat['col37'] > V_err=dat['col38'] > m_H=dat['col74'] > alpha_Fe=dat['col75'] > microturb=dat['col76'] > Vrot=dat['col77'] > Chisq=dat['col78'] > RVorig=dat['col79'] > RVcorr=dat['col80'] > Heliocentric_RV=RVorig+RVcorr > > #now if I want to make plots I have to access paths > > #example, trying with one element > path1r='../Core2dfdr-red-sorted/'+filename1[1] > path1b='../Core2dfdr-blue/'+bluefilename1[1] > > #and use a title in the plot > title1='Data Fe/Hn='+str(FEHn[1])+' Fe/Hg='+str(FEHg[1]) > > for i in xrange(len(Radeg1)): > if i<=5: > #subset1 > print 'filename= ',filename1[i],' ',bluefilename1[i],' FEHn= ',FEHn[i],' FEHg= ',FEHg[i] > #multiplot1 > fig1, (ax1, ax2, ax3, ax4, ax5) = plt.subplots(5, sharex=True) > ax1.plot(path1r,'--ro') > ax1.plot(path1b,'--bo') Here's where you go wrong. You're feeding plot() a path, not data. plot() just takes an x and y array of (float) values (and more options if wanted). Not like gnuplot for example, which can deal with a filename as input. This is also the ValueError you get below: plot() sees a string (the filename), which it tries to interpret as an array of y values (it assumes x is [0, 1, 2, ?] if it's missing), and that fails as it tries to convert the string to floats. So, you'll first have to read the file, extract the data, then plot those data. pyfits is the module you want to use for reading your data. Hope that gets you further, Evert > plt.show() > #subset2 > # if i>5 and i<=10: > # print 'filename= ',filename1[i],' FEHn= ',FEHn[i],' FEHg= ',FEHg[i] > > ..... > this is where it breaks down. > The path name it cannot follow, and the title is not fully a string. Since I will want to do this for many subset's I would prefer to loop but I don't see a good way to do that. If I try with just one element I get the error: > > filename= 100604F2_1red.0063.fits 100604F2_1blueb.0063.fits FEHn= -3.16295 FEHg= -3.216626 > Traceback (most recent call last): > File "plot_LowZ_targets.py", line 232, in > ax1.plot(path1r,'--ro') > File "/Library/Frameworks/Python.framework/Versions/7.2/lib/python2.7/site-packages/matplotlib/axes.py", line 3849, in plot > self.add_line(line) > File "/Library/Frameworks/Python.framework/Versions/7.2/lib/python2.7/site-packages/matplotlib/axes.py", line 1443, in add_line > self._update_line_limits(line) > File "/Library/Frameworks/Python.framework/Versions/7.2/lib/python2.7/site-packages/matplotlib/axes.py", line 1451, in _update_line_limits > p = line.get_path() > File "/Library/Frameworks/Python.framework/Versions/7.2/lib/python2.7/site-packages/matplotlib/lines.py", line 644, in get_path > self.recache() > File "/Library/Frameworks/Python.framework/Versions/7.2/lib/python2.7/site-packages/matplotlib/lines.py", line 401, in recache > y = np.asarray(yconv, np.float_) > File "/Library/Frameworks/Python.framework/Versions/7.2/lib/python2.7/site-packages/numpy/core/numeric.py", line 235, in asarray > return array(a, dtype, copy=False, order=order) > ValueError: could not convert string to float: ../Core2dfdr-red-sorted/100604F2_2red.0063.fits > > .......... > Note that the print statement I put in works, so the correct values are called. I just haven't assigned in a way that python can read, and look at the path. Trying to make my path variables strings doesn't seem to work either, so I'm a little lost. Thanks everyone, and yes, small world Evert! > ~Elaina > > > -- > PhD Candidate > Department of Physics and Astronomy > Faculty of Science > Macquarie University > North Ryde, NSW 2109, Australia From kushal.kumaran+python at gmail.com Tue Mar 27 11:07:58 2012 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Tue, 27 Mar 2012 14:37:58 +0530 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: On Tue, Mar 27, 2012 at 6:38 AM, thao nguyen wrote: > Dear Support Team, > > I have built a function (enclosed here) to merge many files (in this example > is 2 files: "a1.txt" and "a2.txt") lines by lines. The output file is called > "final_file". However, i could not have it run successfully. > > Content of "a1.txt": > 1 > 3 > 5 > > > Content of "a2.txt": > 2 > 4 > 6 > > > Content of "final_file.txt" will be like: > 1 > 2 > 3 > 4 > 5 > 6 > > > In Python, i called just written module: > > import argument > reload(argument) > argument.test(2,"C:/a1.txt","C:/a2.txt") > > and get the error as below: > ??? "ValueError: I/O operation on closed file > ???? File "c:\append.py", line 5, in > ???????????? argument.test(2,"C:/a1.txt","C:/a2.txt") > ???? File "c:\argument.py", line 28, in test > ??????????? for line_data in f:" > > Could you please advise the resolution for this? > To start with, the error mentions the argument.py file, so you should post that file as well. You don't need to use the reload function in append.py. Is there a reason why it is being called? -- regards, kushal From cwitts at compuscan.co.za Tue Mar 27 11:20:44 2012 From: cwitts at compuscan.co.za (Christian Witts) Date: Tue, 27 Mar 2012 11:20:44 +0200 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: <4F71866C.7000305@compuscan.co.za> On 2012/03/27 03:08 AM, thao nguyen wrote: > > Dear Support Team, > > I have built a function (enclosed here) to merge many files (in this > example is 2 files: "a1.txt" and "a2.txt") lines by lines. The output > file is called "final_file". However, i could not have it run > successfully. > > Content of "a1.txt": > 1 > 3 > 5 > > > Content of "a2.txt": > 2 > 4 > 6 > > > Content of "final_file.txt" will be like: > 1 > 2 > 3 > 4 > 5 > 6 > > > In Python, i called just written module: > > import argument > reload(argument) > argument.test(2,"C:/a1.txt","C:/a2.txt") > > and get the error as below: > "ValueError: I/O operation on closed file > File "c:\append.py", line 5, in > argument.test(2,"C:/a1.txt","C:/a2.txt") > File "c:\argument.py", line 28, in test > for line_data in f:" > > Could you please advise the resolution for this? > > > Thank you > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Your Exception states what the problem is, which is operating on a closed file, and your traceback indicates it is when you're iterating over it. As the error occurs in your argument.py file, you should post the relevant portions of that code too. You could also do `cat file1 file2 filen > final_file` in a *nix prompt if that is your use-case. -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Tue Mar 27 11:53:07 2012 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 27 Mar 2012 10:53:07 +0100 Subject: [Tutor] Permissions Error In-Reply-To: References: Message-ID: <4F718E03.6020202@timgolden.me.uk> On 27/03/2012 05:00, Michael Lewis wrote: > Traceback (most recent call last): > File "C:\Python27\Utilities\copyfiles.py", line 47, in > copyfiles(srcdir, dstdir) > File "C:\Python27\Utilities\copyfiles.py", line 42, in copyfiles > shutil.copy(srcfile, dstfile) > File "C:\Python27\lib\shutil.py", line 116, in copy > copyfile(src, dst) > File "C:\Python27\lib\shutil.py", line 81, in copyfile > with open(src, 'rb') as fsrc: > IOError: [Errno 13] Permission denied: 'C:\\Users\\Chief > Ninja\\Pictures\\testdir' It's not 100% clear what's going on, but it looks as though you've passed along paths whicih result in shutil trying to open a *directory* for reading -- which it won't be able to do. (It is, in fact, possible to get a file handle to a directory on Windows but you don't want to do that and shutil doesn't know how). > > I've noticed that the code runs if I use shutil.copyfiles instead of > shutil.copy. Do you know why? Assuming my premise above, it would be because it special-cases directories passed as parameter. (I haven't actually looked at the code to check). With this kind of problem the most helpful thing you can do for yourself -- and for us if you can't resolve it yourself -- is to pull yourself out of the depths of your copy/copyfiles architecture and to try to do a simple: open ("c:/path/to/file.txt", "rb") If that succeeds then obviuosly there's no permissions issue as such. If it fails (with an access error) then we're onto something. If it succeeds then, probably your more complex copyfiles code is doing something you don't think it's doing. Start chucking out print () statements or logging or something so you know *exactly* where the paths are pointing to which you're passing into the shutil or other stdlib functions. Hopefully all this will make it clearer what's going on. Full marks for posting your code -- that does help. But you'll do better if you post a *minimal* code example, and preferably a self-complete one. TJG From bgailer at gmail.com Tue Mar 27 16:16:36 2012 From: bgailer at gmail.com (bob gailer) Date: Tue, 27 Mar 2012 10:16:36 -0400 Subject: [Tutor] I/O operation on closed file? In-Reply-To: References: Message-ID: <4F71CBC4.7080109@gmail.com> in addition to posting the relevant code: please in future use a meaningful subject which I have provided this time. remember to reply-all so a copy goes to the list. On 3/26/2012 9:08 PM, thao nguyen wrote: > > Dear Support Team, > > I have built a function (enclosed here) to merge many files (in this > example is 2 files: "a1.txt" and "a2.txt") lines by lines. The output > file is called "final_file". However, i could not have it run > successfully. > > Content of "a1.txt": > 1 > 3 > 5 > > > Content of "a2.txt": > 2 > 4 > 6 > > > Content of "final_file.txt" will be like: > 1 > 2 > 3 > 4 > 5 > 6 > > > In Python, i called just written module: > > import argument > reload(argument) > argument.test(2,"C:/a1.txt","C:/a2.txt") > > and get the error as below: > "ValueError: I/O operation on closed file > File "c:\append.py", line 5, in > argument.test(2,"C:/a1.txt","C:/a2.txt") > File "c:\argument.py", line 28, in test > for line_data in f:" > > Could you please advise the resolution for this? > What does " I/O operation on closed file" suggest to you? -- Bob Gailer 919-636-4239 Chapel Hill NC From Xianming.Yan at intercallapac.com Wed Mar 28 12:17:16 2012 From: Xianming.Yan at intercallapac.com (Yan, Xianming) Date: Wed, 28 Mar 2012 21:17:16 +1100 Subject: [Tutor] =?gb2312?b?tPC4tDogVHV0b3IgRGlnZXN0LCBWb2wgOTcsIElzc3Vl?= =?gb2312?b?IDcy?= In-Reply-To: References: Message-ID: Hello, I'm new to studying python, Seems you don't have to import the argument module. You can simply open the two files and write then to another file. By using file("xxxx.xx",r) can open a file with read, by using file("xxxx",w) can open a file with write. And then you can using xx.readline() to read a line from file, then xx.writeline() to write into another file. Hope this helps you. Thanks Xianming -----????----- ???: tutor-bounces+xianming.yan=intercallapac.com at python.org [mailto:tutor-bounces+xianming.yan=intercallapac.com at python.org] ?? tutor-request at python.org ????: 2012?3?28? 18:00 ???: tutor at python.org ??: Tutor Digest, Vol 97, Issue 72 Send Tutor mailing list submissions to tutor at python.org To subscribe or unsubscribe via the World Wide Web, visit http://mail.python.org/mailman/listinfo/tutor or, via email, send a message with subject or body 'help' to tutor-request at python.org You can reach the person managing the list at tutor-owner at python.org When replying, please edit your Subject line so it is more specific than "Re: Contents of Tutor digest..." Today's Topics: 1. Re: I/O operation on closed file? (bob gailer) ---------------------------------------------------------------------- Message: 1 Date: Tue, 27 Mar 2012 10:16:36 -0400 From: bob gailer To: thao nguyen Cc: tutor at python.org Subject: Re: [Tutor] I/O operation on closed file? Message-ID: <4F71CBC4.7080109 at gmail.com> Content-Type: text/plain; charset=ISO-8859-1; format=flowed in addition to posting the relevant code: please in future use a meaningful subject which I have provided this time. remember to reply-all so a copy goes to the list. On 3/26/2012 9:08 PM, thao nguyen wrote: > > Dear Support Team, > > I have built a function (enclosed here) to merge many files (in this > example is 2 files: "a1.txt" and "a2.txt") lines by lines. The output > file is called "final_file". However, i could not have it run > successfully. > > Content of "a1.txt": > 1 > 3 > 5 > > > Content of "a2.txt": > 2 > 4 > 6 > > > Content of "final_file.txt" will be like: > 1 > 2 > 3 > 4 > 5 > 6 > > > In Python, i called just written module: > > import argument > reload(argument) > argument.test(2,"C:/a1.txt","C:/a2.txt") > > and get the error as below: > "ValueError: I/O operation on closed file > File "c:\append.py", line 5, in > argument.test(2,"C:/a1.txt","C:/a2.txt") > File "c:\argument.py", line 28, in test > for line_data in f:" > > Could you please advise the resolution for this? > What does " I/O operation on closed file" suggest to you? -- Bob Gailer 919-636-4239 Chapel Hill NC ------------------------------ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor End of Tutor Digest, Vol 97, Issue 72 ************************************* From d at davea.name Wed Mar 28 18:57:27 2012 From: d at davea.name (Dave Angel) Date: Wed, 28 Mar 2012 12:57:27 -0400 Subject: [Tutor] Strange ways of opening a file In-Reply-To: References: Message-ID: <4F7342F7.9010208@davea.name> On 03/28/2012 06:17 AM, Yan, Xianming wrote: > Hello, > Without a meaningful title, it's unclear just what your question is. When you do a reply on the digest, delete all the parts that aren't relevant to your post, and change the subject line to something appropriate. > I'm new to studying python, > > Seems you don't have to import the argument module. > The standard library has no module called argument. If you want to import a module, you need to write it, and save it to a file with a .py extension. Or perhaps you've installed such a module from some internet site. > You can simply open the two files and write then to another file. By using file("xxxx.xx",r) can open a file with read, by using file("xxxx",w) can open a file with write. > The standard way to open a file is with the built-in open() function. Otherwise your syntax is missing the quotes around the r and w. To open a text file, use: infile = open("xxxx", "r") outfile = open("yyyy", "w") > And then you can using xx.readline() to read a line from file, then xx.writeline() to write into another file. > Again, assuming the data is text. > Hope this helps you. > > Thanks > Xianming -- DaveA From wescpy at gmail.com Wed Mar 28 20:40:07 2012 From: wescpy at gmail.com (wesley chun) Date: Wed, 28 Mar 2012 11:40:07 -0700 Subject: [Tutor] =?utf-8?b?562U5aSNOiAgQW55IGJvb2sgdG8gc3R1ZHkgUHl0aG9u?= In-Reply-To: References: Message-ID: > I'm reading your book and just typeing the TCP server and client example scripts to my python and run it, but I did not get the expected results. > > For tstclnt.py(example 16.2,page 473 on the book),when I typed in vi and execut it by python tstclnt.py, I get the error of 'No route to host'. > > Of course I modified the IP address to 192.168.1.11 which is on another linux server in the script, I pinged the 192.168.1.11 and get successfully.(On 192.168.1.11 I run the TCP server program, it is the one on the book) > > Please see the screen shot for detail. > > Can you give me some suggestion on this error? hi xianming, any of the tutors here can help you, not just me! :-) instead of a screenshot (many people use only terminals to read email), it's best to just cut-n-paste the code and error traceback into your email. based on what you sent in, it would be worthwhile for you to also post the server code and output as well. note that a positive ping and the client speaking to an address are somewhat but not entirely related. the reason is that different network protocols are being used. ping uses ICMP -- http://en.wikipedia.org/wiki/Internet_Control_Message_Protocol -- while the code uses TCP -- http://en.wikipedia.org/wiki/Transmission_Control_Protocol -- instead. once you provide the server code and output, people may be able to help you better. best regards, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "A computer never does what you want... only what you tell it." ? ? wesley chun : wescpy at gmail?: @wescpy/+wescpy ? ? Python training & consulting :?CyberwebConsulting.com ? ? "Core Python" books :?CorePython.com ? ? Python-flavored blog: wescpy.blogspot.com From rjbrow2 at gmail.com Wed Mar 28 20:53:36 2012 From: rjbrow2 at gmail.com (Ricky Brown) Date: Wed, 28 Mar 2012 14:53:36 -0400 Subject: [Tutor] Lists and While Loops Message-ID: So I have to write a program that reads a message from the user and prints a new message that contains all the words from the original message but in the same order without repeating any of them unless they show up more than once in the original message. What I have thus far looks like this: message = input("Your message:") myList = message.split() y = random.choice(myList) z = len(myList) while z !=0: myList.remove(y) print(y) I can't figure out 1) How to remove "y" from the list and continue the loop; when I use .remove etc. it runs once then give me the error that "y" is not in the list. I imagine the answer is quite simple I'm just getting really frustrated trying to get this done any advice is appreciated. Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From leamhall at gmail.com Wed Mar 28 20:58:00 2012 From: leamhall at gmail.com (Leam Hall) Date: Wed, 28 Mar 2012 14:58:00 -0400 Subject: [Tutor] Any book to study Python In-Reply-To: References: Message-ID: <4F735F38.2000508@gmail.com> On 03/28/2012 02:40 PM, wesley chun wrote: > > hi xianming, > > any of the tutors here can help you, not just me! :-) > > once you provide the server code and output, people may be able to > help you better. > > best regards, > -- wesley Agreed. It depends on firewalls between the two IP addresses. Also, the Linux server may have IP tables installed which might prevent access to that port but allow ping. Leam From ramit.prasad at jpmorgan.com Wed Mar 28 21:04:34 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Wed, 28 Mar 2012 19:04:34 +0000 Subject: [Tutor] Any book to study Python In-Reply-To: <4F735F38.2000508@gmail.com> References: <4F735F38.2000508@gmail.com> Message-ID: <5B80DD153D7D744689F57F4FB69AF47409291BFC@SCACMX008.exchad.jpmchase.net> > > > > any of the tutors here can help you, not just me! :-) > > > > > once you provide the server code and output, people may be able to > > help you better. > Agreed. It depends on firewalls between the two IP addresses. Also, the > Linux server may have IP tables installed which might prevent access to > that port but allow ping. Or (if I remember correctly) allow access to the port but not ping. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From robert.sjoblom at gmail.com Wed Mar 28 22:14:06 2012 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Wed, 28 Mar 2012 22:14:06 +0200 Subject: [Tutor] Lists and While Loops In-Reply-To: References: Message-ID: > I can't figure out > 1) How to remove "y" from the list and continue the loop; when I use .remove > etc. it runs once then give me the error that "y" is not in the list. > > I imagine the answer is quite simple I'm just getting really frustrated > trying to get this done any advice is appreciated. This should tell you why you run into your error: >>> message = "This is a message." >>> m_list = message.split() >>> m_list ['This', 'is', 'a', 'message.'] >>> y = random.choice(m_list) >>> y 'message.' >>> m_list.remove(y) >>> m_list ['This', 'is', 'a'] >>> y 'message.' You should probably move your y = random.choice() into the while loop. A simpler way than to remove items from a list is to use random.sample: >>> message = "This is a message." >>> m_list = message.split() >>> random.sample(m_list, len(m_list)) ['is', 'This', 'a', 'message.'] -- best regards, Robert S. From emile at fenx.com Wed Mar 28 22:15:47 2012 From: emile at fenx.com (Emile van Sebille) Date: Wed, 28 Mar 2012 13:15:47 -0700 Subject: [Tutor] Lists and While Loops In-Reply-To: References: Message-ID: On 3/28/2012 11:53 AM Ricky Brown said... > So I have to write a program that reads a message from the user and > prints a new message ok -- > that contains all the words from the original > message but in the same order without repeating any of them unless they > show up more than once in the original message. ?? doesn't this mean repeat the exact same message? IOW if the user suppies: This is is a test test the above rule would resuire you to output exactly the same input I think.... > > What I have thus far looks like this: > > message = input("Your message:") so, "print message" does it... ... but I suspect your requirement isn't accurate. Emile > myList = message.split() > y = random.choice(myList) > z = len(myList) > while z !=0: > myList.remove(y) > print(y) > > I can't figure out > 1) How to remove "y" from the list and continue the loop; when I use > .remove etc. it runs once then give me the error that "y" is not in the > list. > > I imagine the answer is quite simple I'm just getting really frustrated > trying to get this done any advice is appreciated. > > Thanks > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From eire1130 at gmail.com Wed Mar 28 22:23:19 2012 From: eire1130 at gmail.com (James Reynolds) Date: Wed, 28 Mar 2012 16:23:19 -0400 Subject: [Tutor] Lists and While Loops In-Reply-To: References: Message-ID: On Wed, Mar 28, 2012 at 2:53 PM, Ricky Brown wrote: > So I have to write a program that reads a message from the user and prints > a new message that contains all the words from the original message but in > the same order without repeating any of them unless they show up more than > once in the original message. > > What I have thus far looks like this: > > message = input("Your message:") > myList = message.split() > y = random.choice(myList) > z = len(myList) > while z !=0: > myList.remove(y) > print(y) > > I can't figure out > 1) How to remove "y" from the list and continue the loop; when I use > .remove etc. it runs once then give me the error that "y" is not in the > list. > > I imagine the answer is quite simple I'm just getting really frustrated > trying to get this done any advice is appreciated. > > Thanks > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > You have two main issues, one, you are not designing the program to do what is specified in the directions, and two, the program you did write has a few things that you need to work on. For the later portion, I've provided some commentary below in the body of your code that I have copied over. message = input("Your message:") myList = message.split() y = random.choice(myList) #here you have saved some random choice from your list to the variable y. z = len(myList) #Here you save the length of the list to the variable z. while z !=0: #the above says, keep doing this loop while z is not equal to 0. myList.remove(y) #Here you remove an item from the list, the item stored to the variable y from above. #it's important to note that this does not change the value of z and this does not change the value of y. print(y) #y gets printed once The loop then goes back up and since z has not changed (and in fact never will change, because you have never told it to change) the while loop runs through another iteration. However, once myList.remove(y) is evaluated again for the second time it throws an error because y is no longer in the list. -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Wed Mar 28 23:01:46 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 28 Mar 2012 22:01:46 +0100 Subject: [Tutor] Lists and While Loops In-Reply-To: References: Message-ID: On 28/03/2012 21:15, Emile van Sebille wrote: > On 3/28/2012 11:53 AM Ricky Brown said... >> So I have to write a program that reads a message from the user and >> prints a new message > > ok -- > >> that contains all the words from the original >> message but in the same order without repeating any of them unless they >> show up more than once in the original message. > > ?? doesn't this mean repeat the exact same message? IOW if the user > suppies: > > This is is a test test > > the above rule would resuire you to output exactly the same input I > think.... > > >> >> What I have thus far looks like this: >> >> message = input("Your message:") > > so, "print message" does it... > > ... but I suspect your requirement isn't accurate. > > Emile > > What the OP is asking for would output your original This is is a test test as is is test test I have a strong sense of D?j? vu, namely gathering requirements being far more difficult than writing code :) I've no idea whether the requirement given is right or wrong. Whatever the case I'd be using the built-in set or on older Pythons the sets module. > > >> myList = message.split() >> y = random.choice(myList) >> z = len(myList) >> while z !=0: >> myList.remove(y) >> print(y) >> >> I can't figure out >> 1) How to remove "y" from the list and continue the loop; when I use >> .remove etc. it runs once then give me the error that "y" is not in the >> list. >> >> I imagine the answer is quite simple I'm just getting really frustrated >> trying to get this done any advice is appreciated. >> >> Thanks >> > -- Cheers. Mark Lawrence. From rjbrow2 at gmail.com Thu Mar 29 00:14:47 2012 From: rjbrow2 at gmail.com (Ricky Brown) Date: Wed, 28 Mar 2012 18:14:47 -0400 Subject: [Tutor] Lists and While Loops In-Reply-To: References: Message-ID: Thank you all for your input it was extremely helpful. Robert you were spot on with what I was trying to do, I tried to implement the random.sample earlier but I couldn't see to get it too work -- running smoothly now. Sorry for the trouble :) On Wed, Mar 28, 2012 at 4:14 PM, Robert Sjoblom wrote: > > I can't figure out > > 1) How to remove "y" from the list and continue the loop; when I use > .remove > > etc. it runs once then give me the error that "y" is not in the list. > > > > I imagine the answer is quite simple I'm just getting really frustrated > > trying to get this done any advice is appreciated. > > This should tell you why you run into your error: > > >>> message = "This is a message." > >>> m_list = message.split() > >>> m_list > ['This', 'is', 'a', 'message.'] > >>> y = random.choice(m_list) > >>> y > 'message.' > >>> m_list.remove(y) > >>> m_list > ['This', 'is', 'a'] > >>> y > 'message.' > > You should probably move your y = random.choice() into the while loop. > > A simpler way than to remove items from a list is to use random.sample: > >>> message = "This is a message." > >>> m_list = message.split() > >>> random.sample(m_list, len(m_list)) > ['is', 'This', 'a', 'message.'] > > -- > best regards, > Robert S. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bdrake at crosswire.org Fri Mar 30 16:04:09 2012 From: bdrake at crosswire.org (Barry Drake) Date: Fri, 30 Mar 2012 15:04:09 +0100 Subject: [Tutor] New to this list .... Message-ID: <4F75BD59.6090802@crosswire.org> Hi there .... I've just joined this list and thought I'd introduce myself. I used to be fairly competent in c but never made the grade to c++. I've done very little programming in the last couple of years or so. I'm getting a Raspberry-pi for our local Junior school and am starting to learn Python so I can show the year five and year six kids how to write simple games. I'm already enjoying this lovely language. One of the few c things I miss is the switch/case statement. if and elif in it's place is a bit cumbersome. Still, it works. One of the things I wanted to do is to use a four integer array to get four integers returned from a function. I ended up using what I think is a list. (I'm not really sure of the datatypes yet). This is what I did, and it works, but looks very inelegant to me: correct = 0 match = 0 wrong = 0 results = [correct, match, wrong] results = getflag(flag_1, results) results = getflag(flag_2, results) results = getflag(flag_3, results) results = getflag(flag_4, results) Any thoughts? Kind regards, Barry. -- From Barry Drake - a member of the Ubuntu advertising team From bdrake at crosswire.org Fri Mar 30 16:13:31 2012 From: bdrake at crosswire.org (Barry Drake) Date: Fri, 30 Mar 2012 15:13:31 +0100 Subject: [Tutor] New to this list .... In-Reply-To: <4F75BD59.6090802@crosswire.org> References: <4F75BD59.6090802@crosswire.org> Message-ID: <4F75BF8B.5040706@crosswire.org> On 30/03/12 15:04, Barry Drake wrote: > One of the things I wanted to do is to use a four integer array to get > four integers returned from a function. I ended up using what I think > is a list. (I'm not really sure of the datatypes yet). This is what I > did, and it works, but looks very inelegant to me: > > correct = 0 > match = 0 > wrong = 0 > results = [correct, match, wrong] > > results = getflag(flag_1, results) > results = getflag(flag_2, results) > results = getflag(flag_3, results) > results = getflag(flag_4, results) Sorry - I meant three-digit array, and the indents in the code fragment above were all in line originally. -- From Barry Drake is part of the Ubuntu advertising team. From evert.rol at gmail.com Fri Mar 30 17:19:34 2012 From: evert.rol at gmail.com (Evert Rol) Date: Fri, 30 Mar 2012 17:19:34 +0200 Subject: [Tutor] New to this list .... In-Reply-To: <4F75BD59.6090802@crosswire.org> References: <4F75BD59.6090802@crosswire.org> Message-ID: <79375360-BF66-4FAF-B8A3-2EEFF412A040@gmail.com> Hi and welcome Barry, > One of the things I wanted to do is to use a four integer array to get four integers returned from a function. I ended up using what I think is a list. (I'm not really sure of the datatypes yet). This is what I did, and it works, but looks very inelegant to me: > > correct = 0 > match = 0 > wrong = 0 > results = [correct, match, wrong] > > results = getflag(flag_1, results) > results = getflag(flag_2, results) > results = getflag(flag_3, results) > results = getflag(flag_4, results) > > Any thoughts? Not sure. In the sense that you can "optimise" (refactor) it in the same way you could do with C. Eg: results = [0, 0, 0] flags = [0, 1, 2, 3] for flag in flags: results = getflag(flag, results) I skipped the constant variables, but that should be clear. The only non-C thing here is the loop, but I would think that's pretty clear. Note that flag takes on integer values here of course. It could probably be done even more fancy/Pythonic, but I don't think there's a reason to do that. Of course, depending on the getflag function itself, you may be able to rewrite things differently, but that's for another question I guess. Cheers, Evert ps: I was going to comment on the indentation, but then spotted your other email. I am going to comment on the subject line though ;-), because that's not related to your actual question. A relevant subject helps a lot, among others for web searches from other people later one. > Kind regards, Barry. > > -- > From Barry Drake - a member of the Ubuntu advertising team > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From breamoreboy at yahoo.co.uk Fri Mar 30 17:26:34 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 30 Mar 2012 16:26:34 +0100 Subject: [Tutor] New to this list .... In-Reply-To: <4F75BF8B.5040706@crosswire.org> References: <4F75BD59.6090802@crosswire.org> <4F75BF8B.5040706@crosswire.org> Message-ID: On 30/03/2012 15:13, Barry Drake wrote: > On 30/03/12 15:04, Barry Drake wrote: >> One of the things I wanted to do is to use a four integer array to get >> four integers returned from a function. I ended up using what I think >> is a list. (I'm not really sure of the datatypes yet). This is what I Please read the tutorial if you haven't done so already at http://docs.python.org/tutorial/index.html >> did, and it works, but looks very inelegant to me: >> >> correct = 0 >> match = 0 >> wrong = 0 >> results = [correct, match, wrong] Usually written results = [0, 0, 0] or even results = [0] * 3 >> >> results = getflag(flag_1, results) >> results = getflag(flag_2, results) >> results = getflag(flag_3, results) >> results = getflag(flag_4, results) How is getflag defined and what are flag_1/2/3/4 ? > > Sorry - I meant three-digit array, and the indents in the code fragment > above were all in line originally. > -- Cheers. Mark Lawrence. From bdrake at crosswire.org Fri Mar 30 17:42:52 2012 From: bdrake at crosswire.org (Barry Drake) Date: Fri, 30 Mar 2012 16:42:52 +0100 Subject: [Tutor] New to this list .... In-Reply-To: <79375360-BF66-4FAF-B8A3-2EEFF412A040@gmail.com> References: <4F75BD59.6090802@crosswire.org> <79375360-BF66-4FAF-B8A3-2EEFF412A040@gmail.com> Message-ID: <4F75D47C.3010600@crosswire.org> On 30/03/12 16:19, Evert Rol wrote: > Not sure. In the sense that you can "optimise" (refactor) it in the same way you could do with C. Eg: > results = [0, 0, 0] > flags = [0, 1, 2, 3] > for flag in flags: > results = getflag(flag, results) > That's exactly what I hoped for. I hadn't realised I can initialise a list in one go - it seems that lists work a lot like the arrays I was used to in c. Thanks to the others who took the time to answer. Just now, Asokan's solution is a bit obscure to me - I'll work on that one, but the above is lovely and elegant; and easy to understand. Someone asked about the getflag function - it is: def getflag(thisflag, results): if (thisflag == 2): results[0] += 1 elif (thisflag == 1): results[1] += 1 elif (thisflag == 0): results[2] += 1 return(results) In c, I would have used switch and case, but I gather there is no direct equivalent in Python ... But it works as is. -- From Barry Drake - a member of the Ubuntu advertising team. From pasokan at talentsprint.com Fri Mar 30 18:03:01 2012 From: pasokan at talentsprint.com (Asokan Pichai) Date: Fri, 30 Mar 2012 21:33:01 +0530 Subject: [Tutor] New to this list .... In-Reply-To: <4F75D47C.3010600@crosswire.org> References: <4F75BD59.6090802@crosswire.org> <79375360-BF66-4FAF-B8A3-2EEFF412A040@gmail.com> <4F75D47C.3010600@crosswire.org> Message-ID: On Fri, Mar 30, 2012 at 9:12 PM, Barry Drake wrote: > On 30/03/12 16:19, Evert Rol wrote: >> >> Not sure. In the sense that you can "optimise" (refactor) it in the same >> way you could do with C. Eg: >> results = [0, 0, 0] >> flags = [0, 1, 2, 3] >> for flag in flags: >> ? ? results = getflag(flag, results) >> > > That's exactly what I hoped for. ?I hadn't realised I can initialise a list > in one go - it seems that lists work a lot like the arrays I was used to in > c. ?Thanks to the others who took the time to answer. ?Just now, Asokan's > solution is a bit obscure to me - I'll work on that one, but the above is > lovely and elegant; and easy to understand. ?Someone asked about the getflag > function - it is: > > def getflag(thisflag, results): > ? ?if (thisflag == 2): > ? ? ? ?results[0] += 1 > ? ?elif (thisflag == 1):> In c, I would have used switch and case, but I gather there is no direct > equivalent in Python ... But it works as is. > > -- > From Barry Drake - a member of the Ubuntu advertising team. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor and directly index on thisflag > ? ? ? ?results[1] += 1 > ? ?elif (thisflag == 0): > ? ? ? ?results[2] += 1 > ? ?return(results) > For the specific values it may be simpler to write: def getflag(thisflag, results): results[2- thisflag] += 1 return results Or you may rearrange the meaning of results and write results[thisflag] += 1 HTH Asokan Pichai From kantesh555 at gmail.com Fri Mar 30 18:05:33 2012 From: kantesh555 at gmail.com (Kantesh Raj) Date: Fri, 30 Mar 2012 21:35:33 +0530 Subject: [Tutor] problem with key in mailbox.Maildir Message-ID: hi everyone, i am not able to get email from my mailbox by using key. key is automatically removed after program termination but file is present there. i get data by same code method by using fresh key (which is generated by adding email again) import mailbox mailb = mailbox.Maildir('~/Maildir',factory=none) k=mailb.get_file('1333110477.M317089P8312Q1.Kantesh-Pc') Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.7/mailbox.py", line 359, in get_file f = open(os.path.join(self._path, self._lookup(key)), 'rb') File "/usr/lib/python2.7/mailbox.py", line 529, in _lookup raise KeyError('No message with key: %s' % key) KeyError: 'No message with key: 1333110477.M317089P8312Q1.Kantesh-Pc how to get email by key??? thanks in advance for help -- Kantesh Raj -------------- next part -------------- An HTML attachment was scrubbed... URL: From russel at winder.org.uk Fri Mar 30 18:10:02 2012 From: russel at winder.org.uk (Russel Winder) Date: Fri, 30 Mar 2012 17:10:02 +0100 Subject: [Tutor] New to this list .... In-Reply-To: <4F75D47C.3010600@crosswire.org> References: <4F75BD59.6090802@crosswire.org> <79375360-BF66-4FAF-B8A3-2EEFF412A040@gmail.com> <4F75D47C.3010600@crosswire.org> Message-ID: <1333123802.16015.19.camel@launcelot.winder.org.uk> Barry, On Fri, 2012-03-30 at 16:42 +0100, Barry Drake wrote: [...] > def getflag(thisflag, results): > if (thisflag == 2): > results[0] += 1 > elif (thisflag == 1): > results[1] += 1 > elif (thisflag == 0): > results[2] += 1 > return(results) Two thoughts spring to mind: -- is it possible to arrange the data model such that the value of the thisflag is the index into the sequence, then: def getflag(thisflag, results): results[thisflag] += 1 return results -- seriously "overengineered" for this particular example but the replacement for switch statement is a dictionary and function pointers. from functools import partial def alt(thisflag, results): def setflag(x): results[x] += 1 { 0: partial(setflag, 2), 1: partial(setflag, 1), 2: partial(setflag, 0), }[thisflag]() return results -- Russel. ============================================================================= Dr Russel Winder t: +44 20 7585 2200 voip: sip:russel.winder at ekiga.net 41 Buckmaster Road m: +44 7770 465 077 xmpp: russel at winder.org.uk London SW11 1EN, UK w: www.russel.org.uk skype: russel_winder -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 198 bytes Desc: This is a digitally signed message part URL: From __peter__ at web.de Fri Mar 30 18:19:49 2012 From: __peter__ at web.de (Peter Otten) Date: Fri, 30 Mar 2012 18:19:49 +0200 Subject: [Tutor] New to this list .... References: <4F75BD59.6090802@crosswire.org> <79375360-BF66-4FAF-B8A3-2EEFF412A040@gmail.com> <4F75D47C.3010600@crosswire.org> Message-ID: Barry Drake wrote: > On 30/03/12 16:19, Evert Rol wrote: >> Not sure. In the sense that you can "optimise" (refactor) it in the same >> way you could do with C. Eg: results = [0, 0, 0] >> flags = [0, 1, 2, 3] >> for flag in flags: >> results = getflag(flag, results) >> > > That's exactly what I hoped for. I hadn't realised I can initialise a > list in one go - it seems that lists work a lot like the arrays I was > used to in c. Thanks to the others who took the time to answer. Just > now, Asokan's solution is a bit obscure to me - I'll work on that one, > but the above is lovely and elegant; and easy to understand. Someone > asked about the getflag function - it is: > > def getflag(thisflag, results): > if (thisflag == 2): > results[0] += 1 > elif (thisflag == 1): > results[1] += 1 > elif (thisflag == 0): > results[2] += 1 > return(results) > > In c, I would have used switch and case, but I gather there is no direct > equivalent in Python ... But it works as is. Here is an alternative to if...elif..., a table (python list) that translates from the flag to an index into the results table. flag_to_result = [2, 1, 0] def update_results(flag, results): try: results[flag_to_result[flag]] += 1 except IndexError: pass # ignore flags other than 0, 1, 2 results = [0, 0, 0] flags = [0, 1, 2, 3, 4, 3, 2, 1] for flag in flags: update_results(flag, results) print results The following operates on an even higher level: from collections import Counter flags = [0, 1, 2, 3, 4, 3, 2, 1] counter = Counter(flags) results = [counter[2], counter[1], counter[0]] print results From ramit.prasad at jpmorgan.com Fri Mar 30 18:22:56 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 30 Mar 2012 16:22:56 +0000 Subject: [Tutor] New to this list .... In-Reply-To: <4F75D47C.3010600@crosswire.org> References: <4F75BD59.6090802@crosswire.org> <79375360-BF66-4FAF-B8A3-2EEFF412A040@gmail.com> <4F75D47C.3010600@crosswire.org> Message-ID: <5B80DD153D7D744689F57F4FB69AF47409294326@SCACMX008.exchad.jpmchase.net> > > Hi there .... I've just joined this list and thought I'd introduce myself. Welcome! > > correct = 0 > > match = 0 > > wrong = 0 > > results = [correct, match, wrong] > > > > results = getflag(flag_1, results) > > results = getflag(flag_2, results) > > results = getflag(flag_3, results) > > results = getflag(flag_4, results) >> def getflag(thisflag, results): >> if (thisflag == 2): >> results[0] += 1 >> elif (thisflag == 1): >> results[1] += 1 >> elif (thisflag == 0): >> results[2] += 1 >> return(results) >> >> In c, I would have used switch and case, but I gather there is no direct >> equivalent in Python ... But it works as is. C switch is just a different way of doing an if/elif tree, I do not really see any real difference. Although, if there is you can feel free to enlighten me. :) Unlike C, the parenthesis in if statements and returns are not necessary. > if (thisflag == 2): becomes if thisflag == 2: > return(results) becomes return results Furthermore, the way Python binds names means that modifying the list in getflags modifies it in the callee. No need to return and reassign results. >>> def foo(x): ... x[0] += 1 ... >>> bar = [ 1, 3, 4 ] >>> foo( bar ) >>> print bar [2, 3, 4] >>> foo( bar ) >>> print bar [3, 3, 4] Be careful of "results = [0] * 3". This style works fine for immutable types (int, float, str) but does not work as people new to Python think it does. >>> def foo(x): ... x[0][0] += 1 ... >>> bar = [ [0] ]*3 >>> print bar [[0], [0], [0]] >>> foo( bar ) >>> print bar [[1], [1], [1]] >>> foo( bar ) >>> print bar [[2], [2], [2]] This occurs because bar is a list containing 3 elements which are all the exact same object. Modifying one sub-list will modify the "others" as well. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From ramit.prasad at jpmorgan.com Fri Mar 30 18:33:25 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 30 Mar 2012 16:33:25 +0000 Subject: [Tutor] New to this list .... In-Reply-To: <5B80DD153D7D744689F57F4FB69AF47409294326@SCACMX008.exchad.jpmchase.net> References: <4F75BD59.6090802@crosswire.org> <79375360-BF66-4FAF-B8A3-2EEFF412A040@gmail.com> <4F75D47C.3010600@crosswire.org> <5B80DD153D7D744689F57F4FB69AF47409294326@SCACMX008.exchad.jpmchase.net> Message-ID: <5B80DD153D7D744689F57F4FB69AF47409294390@SCACMX008.exchad.jpmchase.net> > Furthermore, the way Python binds names means that modifying the list > in getflags modifies it in the callee. No need to return and reassign > results. I correct myself. It has nothing to do with name binding, but entirely to do with Python's object model. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From russel at winder.org.uk Fri Mar 30 18:36:27 2012 From: russel at winder.org.uk (Russel Winder) Date: Fri, 30 Mar 2012 17:36:27 +0100 Subject: [Tutor] New to this list .... In-Reply-To: <5B80DD153D7D744689F57F4FB69AF47409294326@SCACMX008.exchad.jpmchase.net> References: <4F75BD59.6090802@crosswire.org> <79375360-BF66-4FAF-B8A3-2EEFF412A040@gmail.com> <4F75D47C.3010600@crosswire.org> <5B80DD153D7D744689F57F4FB69AF47409294326@SCACMX008.exchad.jpmchase.net> Message-ID: <1333125387.16015.27.camel@launcelot.winder.org.uk> Ramit, On Fri, 2012-03-30 at 16:22 +0000, Prasad, Ramit wrote: [...] > C switch is just a different way of doing an if/elif tree, I do not > really see any real difference. Although, if there is you can feel free > to enlighten me. :) [...] 'fraid not -- though it depends on which compiler and how many cases. For 3 or more cases compilers will generate a hardware supported jump table: a switch statement is a jump table not a cascade of if statements. -- Russel. ============================================================================= Dr Russel Winder t: +44 20 7585 2200 voip: sip:russel.winder at ekiga.net 41 Buckmaster Road m: +44 7770 465 077 xmpp: russel at winder.org.uk London SW11 1EN, UK w: www.russel.org.uk skype: russel_winder -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 198 bytes Desc: This is a digitally signed message part URL: From ramit.prasad at jpmorgan.com Fri Mar 30 18:44:53 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 30 Mar 2012 16:44:53 +0000 Subject: [Tutor] New to this list .... In-Reply-To: <1333125387.16015.27.camel@launcelot.winder.org.uk> References: <4F75BD59.6090802@crosswire.org> <79375360-BF66-4FAF-B8A3-2EEFF412A040@gmail.com> <4F75D47C.3010600@crosswire.org> <5B80DD153D7D744689F57F4FB69AF47409294326@SCACMX008.exchad.jpmchase.net> <1333125387.16015.27.camel@launcelot.winder.org.uk> Message-ID: <5B80DD153D7D744689F57F4FB69AF474092943ED@SCACMX008.exchad.jpmchase.net> > [...] > > C switch is just a different way of doing an if/elif tree, I do not > > really see any real difference. Although, if there is you can feel free > > to enlighten me. :) > [...] > > 'fraid not -- though it depends on which compiler and how many cases. > For 3 or more cases compilers will generate a hardware supported jump > table: a switch statement is a jump table not a cascade of if > statements. Good point, I had forgotten that. Although, it sounded like the OP was referring more to syntax and coding practice than the low level implementation. >I'm already enjoying this lovely language. >One of the few c things I miss is the switch/case statement. if and >elif in it's place is a bit cumbersome. Still, it works. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From breamoreboy at yahoo.co.uk Fri Mar 30 18:58:06 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 30 Mar 2012 17:58:06 +0100 Subject: [Tutor] New to this list .... In-Reply-To: <4F75BD59.6090802@crosswire.org> References: <4F75BD59.6090802@crosswire.org> Message-ID: On 30/03/2012 15:04, Barry Drake wrote: > One of the few c things I miss is the switch/case statement. if and elif > in it's place is a bit cumbersome. Still, it works. The recipe here http://code.activestate.com/recipes/410692-readable-switch-construction-without-lambdas-or-di/ refers to several other recipes which you might want to take a look at, sorry I meant to mention this earlier. -- Cheers. Mark Lawrence. From leamhall at gmail.com Fri Mar 30 19:09:39 2012 From: leamhall at gmail.com (leam hall) Date: Fri, 30 Mar 2012 13:09:39 -0400 Subject: [Tutor] Problem Stripping Message-ID: Python 2.4.3 on Red Hat 5. Trying to use strip to remove characters but it doesn't seem to work like I thought. res = subprocess.Popen(['uname', '-a'], stdout=subprocess.PIPE) uname = res.stdout.read().strip() >>> uname 'Linux myserver 2.6.18-274.el5PAE #1 SMP Fri Jul 8 17:59:09 EDT 2011 i686 i686 i386 GNU/Linux' >>> uname.strip(':') 'Linux myserver 2.6.18-274.el5PAE #1 SMP Fri Jul 8 17:59:09 EDT 2011 i686 i686 i386 GNU/Linux' >>> 'www.example.com'.strip('cmowz.') 'example' Thoughts? Leam -- Mind on a Mission From evert.rol at gmail.com Fri Mar 30 19:24:31 2012 From: evert.rol at gmail.com (Evert Rol) Date: Fri, 30 Mar 2012 19:24:31 +0200 Subject: [Tutor] Problem Stripping In-Reply-To: References: Message-ID: > Python 2.4.3 on Red Hat 5. Trying to use strip to remove characters > but it doesn't seem to work like I thought. > > > res = subprocess.Popen(['uname', '-a'], stdout=subprocess.PIPE) > uname = res.stdout.read().strip() > >>>> uname > 'Linux myserver 2.6.18-274.el5PAE #1 SMP Fri Jul 8 17:59:09 EDT 2011 > i686 i686 i386 GNU/Linux' > >>>> uname.strip(':') > 'Linux myserver 2.6.18-274.el5PAE #1 SMP Fri Jul 8 17:59:09 EDT 2011 > i686 i686 i386 GNU/Linux' > >>>> 'www.example.com'.strip('cmowz.') > 'example' > > Thoughts? Read the documentation carefully: http://docs.python.org/library/stdtypes.html#str.strip It strips *any* of the characters in the strip() argument from either side of the string, up to the point where it can't strip a matching character anymore. Since the uname variable doesn't not start with a ':' on either side, it can't strip anything, and stops immediately, returning the resulting (full) string. You could look into split(':', maxsplit), with maxsplit not at its default value: http://docs.python.org/library/stdtypes.html#str.split Otherwise, regular experssions would be a (bit more drastic) solution. Btw, what *did* you actually expect it should do? That would give us a better hint into the result you want. Good luck, Evert > > Leam > -- > Mind on a Mission > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From joel.goldstick at gmail.com Fri Mar 30 19:25:11 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 30 Mar 2012 13:25:11 -0400 Subject: [Tutor] Problem Stripping In-Reply-To: References: Message-ID: On Fri, Mar 30, 2012 at 1:09 PM, leam hall wrote: > Python 2.4.3 on Red Hat 5. Trying to use strip to remove characters > but it doesn't seem to work like I thought. > > > res = subprocess.Popen(['uname', '-a'], stdout=subprocess.PIPE) > uname = res.stdout.read().strip() > >>>> uname > 'Linux myserver 2.6.18-274.el5PAE #1 SMP Fri Jul 8 17:59:09 EDT 2011 > i686 i686 i386 GNU/Linux' > >>>> uname.strip(':') > 'Linux myserver 2.6.18-274.el5PAE #1 SMP Fri Jul 8 17:59:09 EDT 2011 > i686 i686 i386 GNU/Linux' > >>>> 'www.example.com'.strip('cmowz.') > 'example' > > Thoughts? > > Leam > -- > Mind on a Mission > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor str.strip() removes characters from begining and end of the string -- Not any in between. Notice >>> example = "www.example.com".strip("wcomx") >>> example '.example.' >>> The x remains -- Joel Goldstick From ramit.prasad at jpmorgan.com Fri Mar 30 19:25:10 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 30 Mar 2012 17:25:10 +0000 Subject: [Tutor] Problem Stripping In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF474092944A2@SCACMX008.exchad.jpmchase.net> > Python 2.4.3 on Red Hat 5. Trying to use strip to remove characters > but it doesn't seem to work like I thought. > > > res = subprocess.Popen(['uname', '-a'], stdout=subprocess.PIPE) > uname = res.stdout.read().strip() > > >>> uname > 'Linux myserver 2.6.18-274.el5PAE #1 SMP Fri Jul 8 17:59:09 EDT 2011 > i686 i686 i386 GNU/Linux' > > >>> uname.strip(':') > 'Linux myserver 2.6.18-274.el5PAE #1 SMP Fri Jul 8 17:59:09 EDT 2011 > i686 i686 i386 GNU/Linux' > > >>> 'www.example.com'.strip('cmowz.') > 'example' > > Thoughts? Read the documentation. It is excellent and explains this behavior. http://docs.python.org/library/string.html If you are trying to remove ':' from the result of uname what you really want is uname.replace(':','') Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From bdrake at crosswire.org Fri Mar 30 19:27:16 2012 From: bdrake at crosswire.org (Barry Drake) Date: Fri, 30 Mar 2012 18:27:16 +0100 Subject: [Tutor] New to this list .... In-Reply-To: References: <4F75BD59.6090802@crosswire.org> Message-ID: <4F75ECF4.509@crosswire.org> On 30/03/12 17:58, Mark Lawrence wrote: > The recipe here > http://code.activestate.com/recipes/410692-readable-switch-construction-without-lambdas-or-di/ > > refers to several other recipes which you might want to take a look > at, sorry I meant to mention this earlier. > Oh, that's neat. Not worth putting into my little project, but I've bookmarked that on for when I need a lot of cases. It also shows how to define a class - that was something I had wondered about, but not yet tackled. I'm really grateful for the answers I have received. It will take me a while to get my head around some of the less obvious code fragment that folk have kindly posted, but I will play around with all of them in due course. Already the code I am playing with has shrunk to about half the number of lines it was before I joined this list and I'm even more than ever impressed with the language. I also like the fact that it can be played with as an interpreted language. Compiling and debugging c code could be a pain at times. In Python, a few print statements together with the syntax error messages from the interpreter make it very easy to see what's happening. Kind regards, Barry. -- From Barry Drake - a member of the Ubuntu advertising team. From emile at fenx.com Fri Mar 30 19:28:48 2012 From: emile at fenx.com (Emile van Sebille) Date: Fri, 30 Mar 2012 10:28:48 -0700 Subject: [Tutor] Problem Stripping In-Reply-To: References: Message-ID: On 3/30/2012 10:09 AM leam hall said... > Python 2.4.3 on Red Hat 5. Trying to use strip to remove characters > but it doesn't seem to work like I thought. ... but it works as advertised... Help on built-in function strip: strip(...) S.strip([chars]) -> string or unicode Return a copy of the string S with leading and trailing whitespace removed. If chars is given and not None, remove characters in chars instead. If chars is unicode, S will be converted to unicode before stripping If you're expecting the ":"s to be stripped out, try using replace: Help on built-in function replace: replace(...) S.replace (old, new[, count]) -> string Return a copy of string S with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced. HTH, Emile > > > res = subprocess.Popen(['uname', '-a'], stdout=subprocess.PIPE) > uname = res.stdout.read().strip() > >>>> uname > 'Linux myserver 2.6.18-274.el5PAE #1 SMP Fri Jul 8 17:59:09 EDT 2011 > i686 i686 i386 GNU/Linux' > >>>> uname.strip(':') > 'Linux myserver 2.6.18-274.el5PAE #1 SMP Fri Jul 8 17:59:09 EDT 2011 > i686 i686 i386 GNU/Linux' > >>>> 'www.example.com'.strip('cmowz.') > 'example' > > Thoughts? > > Leam From joel.goldstick at gmail.com Fri Mar 30 19:28:30 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 30 Mar 2012 13:28:30 -0400 Subject: [Tutor] Problem Stripping In-Reply-To: References: Message-ID: On Fri, Mar 30, 2012 at 1:25 PM, Joel Goldstick wrote: > On Fri, Mar 30, 2012 at 1:09 PM, leam hall wrote: >> Python 2.4.3 on Red Hat 5. Trying to use strip to remove characters >> but it doesn't seem to work like I thought. >> >> >> res = subprocess.Popen(['uname', '-a'], stdout=subprocess.PIPE) >> uname = res.stdout.read().strip() >> >>>>> uname >> 'Linux myserver 2.6.18-274.el5PAE #1 SMP Fri Jul 8 17:59:09 EDT 2011 >> i686 i686 i386 GNU/Linux' >> >>>>> uname.strip(':') >> 'Linux myserver 2.6.18-274.el5PAE #1 SMP Fri Jul 8 17:59:09 EDT 2011 >> i686 i686 i386 GNU/Linux' >> >>>>> 'www.example.com'.strip('cmowz.') >> 'example' >> >> Thoughts? >> >> Leam >> -- >> Mind on a Mission >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > str.strip() removes characters from begining and end of the string -- > Not any in between. ?Notice > >>>> example = "www.example.com".strip("wcomx") >>>> example > '.example.' >>>> > > The x remains You could do list comprehension > >>> n = "".join([x for x in "this has : some : colons" if x not in ':']) >>> n 'this has some colons' > -- Joel Goldstick From bdrake at crosswire.org Fri Mar 30 19:35:13 2012 From: bdrake at crosswire.org (Barry Drake) Date: Fri, 30 Mar 2012 18:35:13 +0100 Subject: [Tutor] New to this list .... In-Reply-To: <5B80DD153D7D744689F57F4FB69AF47409294326@SCACMX008.exchad.jpmchase.net> References: <4F75BD59.6090802@crosswire.org> <79375360-BF66-4FAF-B8A3-2EEFF412A040@gmail.com> <4F75D47C.3010600@crosswire.org> <5B80DD153D7D744689F57F4FB69AF47409294326@SCACMX008.exchad.jpmchase.net> Message-ID: <4F75EED1.8010600@crosswire.org> On 30/03/12 17:22, Prasad, Ramit wrote: > Unlike C, the parenthesis in if statements and returns are not > necessary. Furthermore, the way Python binds names means that > modifying the list in getflags modifies it in the callee. No need to > return and reassign results. This is lovely. It's so much friendlier than c. I'm used to c variables going out of scope once you leave the called function. I imagine if you want to leave the variables unchanged, you have to re-assign them inside the function. I quite like it that way. > Be careful of "results = [0] * 3". This style works fine for immutable > types (int, float, str) but does not work as people new to Python > think it does. Thanks for the warning. -- From Barry Drake - a member of the Ubuntu advertising team. From breamoreboy at yahoo.co.uk Fri Mar 30 19:37:42 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 30 Mar 2012 18:37:42 +0100 Subject: [Tutor] Problem Stripping In-Reply-To: References: Message-ID: On 30/03/2012 18:09, leam hall wrote: > Python 2.4.3 on Red Hat 5. Trying to use strip to remove characters > but it doesn't seem to work like I thought. What do you expect it to do? > > > res = subprocess.Popen(['uname', '-a'], stdout=subprocess.PIPE) > uname = res.stdout.read().strip() > >>>> uname > 'Linux myserver 2.6.18-274.el5PAE #1 SMP Fri Jul 8 17:59:09 EDT 2011 > i686 i686 i386 GNU/Linux' > >>>> uname.strip(':') > 'Linux myserver 2.6.18-274.el5PAE #1 SMP Fri Jul 8 17:59:09 EDT 2011 > i686 i686 i386 GNU/Linux' > >>>> 'www.example.com'.strip('cmowz.') > 'example' > > Thoughts? > > Leam Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> help(''.strip) Help on built-in function strip: strip(...) S.strip([chars]) -> string or unicode Return a copy of the string S with leading and trailing whitespace removed. If chars is given and not None, remove characters in chars instead. If chars is unicode, S will be converted to unicode before stripping So it appears that your examples are doing precisely what is defined above. HTH. -- Cheers. Mark Lawrence. From ramit.prasad at jpmorgan.com Fri Mar 30 19:56:50 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 30 Mar 2012 17:56:50 +0000 Subject: [Tutor] New to this list .... In-Reply-To: <4F75EED1.8010600@crosswire.org> References: <4F75BD59.6090802@crosswire.org> <79375360-BF66-4FAF-B8A3-2EEFF412A040@gmail.com> <4F75D47C.3010600@crosswire.org> <5B80DD153D7D744689F57F4FB69AF47409294326@SCACMX008.exchad.jpmchase.net> <4F75EED1.8010600@crosswire.org> Message-ID: <5B80DD153D7D744689F57F4FB69AF47409294523@SCACMX008.exchad.jpmchase.net> [snip] >I'm used to c > variables going out of scope once you leave the called function. I > imagine if you want to leave the variables unchanged, you have to > re-assign them inside the function. [snip] Lists are mutable objects. When you pass a list to a function you bind a name in the functions namespace to the list object. Every name binding to that object will have the ability to modify the list. If you want to modify the list but not change it for others usually you do something like new_list = list( old_list ) OR new_list = old_list[:] Now if you wanted to change an immutable object (like int) then you would have to return object because the name binding is only the function's scope. It should also be noted that you can modify the list but you cannot reassign the list from the function. Consider: >>> >>> def blah( a ): ... a = [] ... >>> b = [ 1, 3, 4 ] >>> blah( b ) >>> print b [1, 3, 4] >>> The reason b is untouched is because a = [] just binds the name 'a' to a new list object while the name 'b' is still bound to the original list object. To bind 'b' to the new list I would have had to return it from blah(). Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From ramit.prasad at jpmorgan.com Fri Mar 30 19:36:50 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 30 Mar 2012 17:36:50 +0000 Subject: [Tutor] Problem Stripping In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF474092944D0@SCACMX008.exchad.jpmchase.net> > strip(...) > S.strip([chars]) -> string or unicode > > Return a copy of the string S with leading and trailing > whitespace removed. > If chars is given and not None, remove characters in chars instead. > If chars is unicode, S will be converted to unicode before stripping You can get this text on the interpreter by doing help(str.strip) or help(''.strip). There is even an interactive help you can access by doing help(). I find it very useful, although usefulness varies with 3rd party code. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From emile at fenx.com Fri Mar 30 20:32:52 2012 From: emile at fenx.com (Emile van Sebille) Date: Fri, 30 Mar 2012 11:32:52 -0700 Subject: [Tutor] New to this list .... In-Reply-To: <5B80DD153D7D744689F57F4FB69AF47409294523@SCACMX008.exchad.jpmchase.net> References: <4F75BD59.6090802@crosswire.org> <79375360-BF66-4FAF-B8A3-2EEFF412A040@gmail.com> <4F75D47C.3010600@crosswire.org> <5B80DD153D7D744689F57F4FB69AF47409294326@SCACMX008.exchad.jpmchase.net> <4F75EED1.8010600@crosswire.org> <5B80DD153D7D744689F57F4FB69AF47409294523@SCACMX008.exchad.jpmchase.net> Message-ID: On 3/30/2012 10:56 AM Prasad, Ramit said... > Lists are mutable objects. When you pass a list to a function you bind > a name in the functions namespace to the list object. Every name > binding to that object will have the ability to modify the list. > > If you want to modify the list but not change it for others usually > you do something like > > new_list = list( old_list ) > OR > new_list = old_list[:] Be aware though that this copies only the 'top' level objects -- if those object are themselves mutable you may still have issues: >>> a = [1,2,3] >>> b = [4,5,6] >>> c = [a,b] >>> d = c[:] >>> d.append(1) >>> d [[1, 2, 3], [4, 5, 6], 1] >>> c [[1, 2, 3], [4, 5, 6]] >>> # so far so good ... >>> b.append(7) >>> d [[1, 2, 3], [4, 5, 6, 7], 1] >>> c [[1, 2, 3], [4, 5, 6, 7]] >>> To avoid this, look at copy.deepcopy as an alternative: >>> d = copy.deepcopy(c) >>> d [[1, 2, 3], [4, 5, 6, 7]] >>> b.append(8) >>> c [[1, 2, 3], [4, 5, 6, 7, 8]] >>> d [[1, 2, 3], [4, 5, 6, 7]] >>> HTH, Emile From russel at winder.org.uk Fri Mar 30 20:47:01 2012 From: russel at winder.org.uk (Russel Winder) Date: Fri, 30 Mar 2012 19:47:01 +0100 Subject: [Tutor] New to this list .... In-Reply-To: <4F75ECF4.509@crosswire.org> References: <4F75BD59.6090802@crosswire.org> <4F75ECF4.509@crosswire.org> Message-ID: <1333133221.16015.41.camel@launcelot.winder.org.uk> Barry, On Fri, 2012-03-30 at 18:27 +0100, Barry Drake wrote: > On 30/03/12 17:58, Mark Lawrence wrote: > > The recipe here > > http://code.activestate.com/recipes/410692-readable-switch-construction-without-lambdas-or-di/ > > > > refers to several other recipes which you might want to take a look > > at, sorry I meant to mention this earlier. > > > > Oh, that's neat. Not worth putting into my little project, but I've > bookmarked that on for when I need a lot of cases. It also shows how to > define a class - that was something I had wondered about, but not yet > tackled. Be aware of the sensible warnings though. switch in C is generally O(1) whereas this Python simulacrum remains O(n). The people who comment saying C switch is always O(n) have clearly never looked at any compiler output. Personally, I am in the camp that says: don't use a device that makes it appear the performance is not what it is. Thus I would prefer if/elif/else cascade over this device since it is simpler and more obvious that it is O(n). But it is a nice example of what Python can achieve even though I would not use it myself. -- Russel. ============================================================================= Dr Russel Winder t: +44 20 7585 2200 voip: sip:russel.winder at ekiga.net 41 Buckmaster Road m: +44 7770 465 077 xmpp: russel at winder.org.uk London SW11 1EN, UK w: www.russel.org.uk skype: russel_winder -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 198 bytes Desc: This is a digitally signed message part URL: From tim at akwebsoft.com Fri Mar 30 20:57:10 2012 From: tim at akwebsoft.com (Tim Johnson) Date: Fri, 30 Mar 2012 10:57:10 -0800 Subject: [Tutor] What to call a string with embedded descriptor? Message-ID: <20120330185710.GE360@mail.akwebsoft.com> This is kind of a theoretical question. I.E. I am looking for a keyword to do research on. Consider the following string: '3:2,6:2,4:3,5:0|age50height63nametimvalue' If the string above is split on the first occurance of '|', the result is a 'leftmost' component which can be decomposed into a nested list of integers which can then be used to parse the 'rightmost' string into a dictionary. What would be a generic term or a pythonist term for such a string? Thanks -- Tim tim at tee jay forty nine dot com or akwebsoft dot com http://www.akwebsoft.com From cranky.frankie at gmail.com Fri Mar 30 20:18:56 2012 From: cranky.frankie at gmail.com (Cranky Frankie) Date: Fri, 30 Mar 2012 14:18:56 -0400 Subject: [Tutor] New to this list .... Message-ID: Message: 1 Date: Fri, 30 Mar 2012 15:04:09 +0100 Barry Drake wrote: << I'm getting a Raspberry-pi for our local Junior school and am starting to learn Python so I can show the year five and year six kids how to write simple games.>> Here's what you need - he starts simple and winds up with some nice games: http://www.amazon.com/Python-Programming-Absolute-Beginner-Edition/dp/1435455002/ref=sr_1_6?ie=UTF8&qid=1333131438&sr=8-6 -- Frank L. "Cranky Frankie" Palmeri Risible Riding Raconteur & Writer ?The problem with quotes on the Internet is that it is often difficult to verify their authenticity.? - Abraham Lincoln From s.irfan.rizvi5 at gmail.com Fri Mar 30 21:57:50 2012 From: s.irfan.rizvi5 at gmail.com (S.Irfan Rizvi) Date: Fri, 30 Mar 2012 14:57:50 -0500 Subject: [Tutor] What to call a string with embedded descriptor? In-Reply-To: <20120330185710.GE360@mail.akwebsoft.com> References: <20120330185710.GE360@mail.akwebsoft.com> Message-ID: please help me disable this.......i made big mistake searching your site On Fri, Mar 30, 2012 at 1:57 PM, Tim Johnson wrote: > This is kind of a theoretical question. I.E. I am looking for a > keyword to do research on. > Consider the following string: > > '3:2,6:2,4:3,5:0|age50height63nametimvalue' > > If the string above is split on the first occurance of '|', > the result is a 'leftmost' component which can be decomposed into a > nested list of integers which can then be used to parse the > 'rightmost' string into a dictionary. > > What would be a generic term or a pythonist term for such a string? > > Thanks > -- > Tim > tim at tee jay forty nine dot com or akwebsoft dot com > http://www.akwebsoft.com > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- ? ? ? ?Regards ? ?? ~ S. Irfan Rizvi ?ADR-TS From emile at fenx.com Fri Mar 30 22:18:25 2012 From: emile at fenx.com (Emile van Sebille) Date: Fri, 30 Mar 2012 13:18:25 -0700 Subject: [Tutor] What to call a string with embedded descriptor? In-Reply-To: References: <20120330185710.GE360@mail.akwebsoft.com> Message-ID: On 3/30/2012 12:57 PM S.Irfan Rizvi said... > please help me disable this.......i made big mistake searching your site note that at the bottom of every email you're getting from this list has a link to the unsubscribe page... >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > > From emile at fenx.com Fri Mar 30 22:20:34 2012 From: emile at fenx.com (Emile van Sebille) Date: Fri, 30 Mar 2012 13:20:34 -0700 Subject: [Tutor] What to call a string with embedded descriptor? In-Reply-To: <20120330185710.GE360@mail.akwebsoft.com> References: <20120330185710.GE360@mail.akwebsoft.com> Message-ID: On 3/30/2012 11:57 AM Tim Johnson said... > This is kind of a theoretical question. I.E. I am looking for a > keyword to do research on. > Consider the following string: > > '3:2,6:2,4:3,5:0|age50height63nametimvalue' > > If the string above is split on the first occurance of '|', > the result is a 'leftmost' component which can be decomposed into a > nested list of integers which can then be used to parse the > 'rightmost' string into a dictionary. > > What would be a generic term or a pythonist term for such a string? > I've called them formatted or structured -- you could also say proprietary I imagine. I'm not aware if there's a formal name... Emile From x23chris at gmail.com Fri Mar 30 22:26:02 2012 From: x23chris at gmail.com (chris knarvik) Date: Fri, 30 Mar 2012 16:26:02 -0400 Subject: [Tutor] Syntax error help Message-ID: Alright i have been trying to right a (relatively) simple to calculate area and volume below is my current working code def areamenu(): print 'Square (1)' print 'triangle (2)' print 'rectangle (3)' print 'trapazoid (4)' print 'circle (5)' def squareacalc(): sidelength = input('enter side length: ') print ' the side length is' sidelength ** 2 def displaymenu(): print 'please make a selection'; print 'Area (1)'; choice = input(raw_input('enter selection number'): if (choice == 1): Areamenu(): else: print 'choice' , choice, ' is wrong try again' def selctiona(): Areamenu(); choicea = input(raw_input'enter selection'); if (choicea == 1): squareacalc() print 'good bye' I keep getting this error Traceback (most recent call last): File "", line 1, in import Area File "C:\Python27\Area.py", line 10 areamenu() ^ SyntaxError: invalid syntax can anyone tell me what im doing wrong i cant see the problem help would be appreciated -------------- next part -------------- An HTML attachment was scrubbed... URL: From evert.rol at gmail.com Fri Mar 30 22:50:36 2012 From: evert.rol at gmail.com (Evert Rol) Date: Fri, 30 Mar 2012 22:50:36 +0200 Subject: [Tutor] Syntax error help In-Reply-To: References: Message-ID: > Alright i have been trying to right a (relatively) simple to calculate area and volume below is my current working code > def areamenu(): > print 'Square (1)' > print 'triangle (2)' > print 'rectangle (3)' > print 'trapazoid (4)' > print 'circle (5)' > > def squareacalc(): > sidelength = input('enter side length: ') > print ' the side length is' sidelength ** 2 > > def displaymenu(): > print 'please make a selection'; > print 'Area (1)'; > choice = input(raw_input('enter selection number'): You're missing a closing parenthesis here. But see comments below. > if (choice == 1): > Areamenu(): > > else: > print 'choice' , choice, ' is wrong try again' > > def selctiona(): > Areamenu(); > choicea = input(raw_input'enter selection'); And here you're missing an openening parenthesis. > if (choicea == 1): > squareacalc() > > > > print 'good bye' > > I keep getting this error > Traceback (most recent call last): > File "", line 1, in > import Area > File "C:\Python27\Area.py", line 10 > areamenu() > ^ > SyntaxError: invalid syntax > > can anyone tell me what im doing wrong i cant see the problem > help would be appreciated A syntax error is often a typing error in the code. In this case, forgotten parentheses, but could be forgotten colons or an unclosed string. The parentheses problem can often be caught by using a good editor: these often lightlight when you close a set of parentheses, so you can spot syntax errors while you are typing. There are a number of other things wrong here, though. Style-wise: Python does not need (and prefers not to have) closing semicolons. In addition, there is no need to surround if statements with parentheses: "if choice == 1:" is perfectly fine and much more legible. Perhaps you think (coming from another language): "but it doesn't hurt, and I like it this way". But then you're still programming in that other language, and just translating to Python; not actually coding in Python. Also, this is odd, wrong and pretty bad: choice = input(raw_input('enter selection number')): Use either raw_input() (for Python 2.x) or input() (Python 3.x). It's wrong because you are waiting for input, then use that input as the next prompting string for further input. Like this >>> choice = input(raw_input('enter selection number')) enter selection number1 12 >>> print choice 2 (the 12 is the 1 I entered before, plus a 2 I just entered as a second entry.) So just use one function, and the appropriate one for the Python version. Lastly, choice will be a string, since input() and raw_input() return a string. In the if-statement, however, you are comparing that string to an integer. Python does not do implicit conversion, so you'll have to convert the string to an integer first, or compare to a string instead. (Something similar happens for the sidelength, btw.) Last thing I see glancing over the code: you define areamenu(), but call Areamenu(). Python is case sensitive, so you'd have to call areamenu() instead. This may be a bit more information than you asked for, but hopefully you don't mind. Good luck, Evert From tim at akwebsoft.com Fri Mar 30 23:16:20 2012 From: tim at akwebsoft.com (Tim Johnson) Date: Fri, 30 Mar 2012 13:16:20 -0800 Subject: [Tutor] What to call a string with embedded descriptor? In-Reply-To: References: <20120330185710.GE360@mail.akwebsoft.com> Message-ID: <20120330211620.GF360@mail.akwebsoft.com> * Emile van Sebille [120330 12:21]: <....> >If the string above is split on the first occurance of '|', > >the result is a 'leftmost' component which can be decomposed into a > >nested list of integers which can then be used to parse the > >'rightmost' string into a dictionary. > > > >What would be a generic term or a pythonist term for such a string? > > > > I've called them formatted or structured -- you could also say > proprietary I imagine. I'm not aware if there's a formal name... Back in the day when I worked in C and did a bit of reconstructing proprietory database schemes in legacy systems, it was common for a binary file to start with a "map" which defined how to search the subsequent content. I never did know if there was a formal terminology for such a setup. I guess there isn't. Thanks for the reply. -- Tim tim at tee jay forty nine dot com or akwebsoft dot com http://www.akwebsoft.com From bgailer at gmail.com Fri Mar 30 23:30:22 2012 From: bgailer at gmail.com (bob gailer) Date: Fri, 30 Mar 2012 17:30:22 -0400 Subject: [Tutor] Syntax error help In-Reply-To: References: Message-ID: <4F7625EE.4090701@gmail.com> On 3/30/2012 4:26 PM, chris knarvik wrote: > Alright i have been trying to right a (relatively) simple to calculate > area and volume below is my current working code Suggestion: start with a VERY SIMPLE program and get that working. Then add one new feature at a time. Is the following in Area.py? If it is then the traceback could not have come from importing this code, because line 10 does not mention areamenu(). In fact areamenu() appears ONLY in line 1, but not by itself! > def areamenu(): > print 'Square (1)' > print 'triangle (2)' > print 'rectangle (3)' > print 'trapazoid (4)' > print 'circle (5)' > > def squareacalc(): > sidelength = input('enter side length: ') > print ' the side length is' sidelength ** 2 > > def displaymenu(): > print 'please make a selection'; > print 'Area (1)'; > choice = input(raw_input('enter selection number'): > if (choice == 1): > Areamenu(): > > else: > print 'choice' , choice, ' is wrong try again' > > def selctiona(): > Areamenu(); > choicea = input(raw_input'enter selection'); > if (choicea == 1): > squareacalc() > > > > print 'good bye' > > I keep getting this error > Traceback (most recent call last): > File "", line 1, in > import Area > File "C:\Python27\Area.py", line 10 > areamenu() > ^ > SyntaxError: invalid syntax > > can anyone tell me what im doing wrong i cant see the problem > help would be appreciated > What are you using to run the above? I'll guess the interactive window of IDLE. Try reload(Area). Once a module is imported you must reload to import it again. (I am assuming you made changes after the initial error.) The above code should give you something like: Traceback (most recent call last): File "", line 1, in File "Script3.py", line 10 print ' the side length is' sidelength ** 2 ^ SyntaxError: invalid syntax fix that (do you know what to do?) then you should get a syntax error for line15. Why is there a : at the end of that line? then you have 1 more trailing : to deal with. then there is a missing ) then there is a missing ( Once you fix all the problems then you should see good bye since that is the only executable code in Area.py other than def statements. Suggestion: start with a VERY SIMPLE program and get that working. Then add one new feature at a time. -- Bob Gailer 919-636-4239 Chapel Hill NC From bdrake at crosswire.org Fri Mar 30 23:41:31 2012 From: bdrake at crosswire.org (Barry Drake) Date: Fri, 30 Mar 2012 22:41:31 +0100 Subject: [Tutor] New to this list .... In-Reply-To: References: Message-ID: <4F76288B.70401@crosswire.org> On 30/03/12 19:18, Cranky Frankie wrote: > Here's what you need - he starts simple and winds up with some nice games: > http://www.amazon.com/Python-Programming-Absolute-Beginner-Edition/dp/1435455002/ref=sr_1_6?ie=UTF8&qid=1333131438&sr=8-6 Wow! I found an e-book copy online and got it. Looks good! I've looked at 'Snake Wrangling for Kids'. Informative, but the example code is not going to inspire kids. Al Sweigarts two e-books are a bit better, but I think I'm going to get more mileage from the above. Thanks. Kind regards, Barry. -- From Barry Drake - a member of the Ubuntu advertising team. From modulok at gmail.com Fri Mar 30 23:49:57 2012 From: modulok at gmail.com (Modulok) Date: Fri, 30 Mar 2012 15:49:57 -0600 Subject: [Tutor] Syntax error help In-Reply-To: References: Message-ID: On 3/30/12, chris knarvik wrote: > Alright i have been trying to right a (relatively) simple to calculate area > and volume below is my current working code > def areamenu(): > print 'Square (1)' > print 'triangle (2)' > print 'rectangle (3)' > print 'trapazoid (4)' > print 'circle (5)' > > def squareacalc(): > sidelength = input('enter side length: ') > print ' the side length is' sidelength ** 2 > > def displaymenu(): > print 'please make a selection'; > print 'Area (1)'; > choice = input(raw_input('enter selection number'): > if (choice == 1): > Areamenu(): > > else: > print 'choice' , choice, ' is wrong try again' > > def selctiona(): > Areamenu(); > choicea = input(raw_input'enter selection'); > if (choicea == 1): > squareacalc() > > > > print 'good bye' > > I keep getting this error > Traceback (most recent call last): > File "", line 1, in > import Area > File "C:\Python27\Area.py", line 10 > areamenu() > ^ > SyntaxError: invalid syntax > > can anyone tell me what im doing wrong i cant see the problem > help would be appreciated Chris, Your code has numerous problems. First, the only lines that should end in a colon ':' are lines that define something, i.e. class and function signatures, etc. Your code has them sprinkled in places where they really don't belong. For instance: choice = input(raw_input('enter selection number'): #<-- No. Additionally, python statements are almost never terminated with a semicolon ';'. Your code has those in random places as well. Python statements *can* be semicolon terminated, but this should *only* be used if there is more than one statement per line. (Generally a discouraged practice, unless in the case of a list comprehensions): choicea = input(raw_input'enter selection'); #<-- Not needed. The other problem I see is a lot of mis-matched parentheses. For instance your code has places where there are two opening parentheses, but only one closing parenthesis: choice = input(raw_input('enter selection number'): Should be: choice = input(raw_input('enter selection number')) However, the above line is pretty nasty. It's making an unnecessary function call. Above, its waiting for user input to the 'input' function, and using the return value of the 'raw_input' function for that input, which itself is waiting for user input. i.e. an input waiting for an input. It should instead be something like this: choicea = input('enter selection: ') *If* you decide to use the 'raw_input()' function instead, remember to type-cast the value that gets entered. By default with 'raw_input()' it is interpreted as a string and not an integer. Thus, the comparison 'if (choicea == 1)' wouldn't work with 'raw_input()' expected. This is a problem as well: print ' the side length is' sidelength ** 2 The print statement only takes a single argument, or multiple arguments *if* they are comma separated, e.g: print ' the side length is', sidelength ** 2 However, this whole thing would be better written using string substitution:: print ' the side length is %s' % (sidelength ** 2) This is also incorrect: Areamenu() Your code defines a function named 'areamenu', not one named 'Areamenu'. Remember, python is case sEnsItiVe. e.g: Foo() and foo() are different. Good luck! -Modulok- From emile at fenx.com Fri Mar 30 23:54:13 2012 From: emile at fenx.com (Emile van Sebille) Date: Fri, 30 Mar 2012 14:54:13 -0700 Subject: [Tutor] New to this list .... In-Reply-To: <4F76288B.70401@crosswire.org> References: <4F76288B.70401@crosswire.org> Message-ID: On 3/30/2012 2:41 PM Barry Drake said... > On 30/03/12 19:18, Cranky Frankie wrote: >> Here's what you need - he starts simple and winds up with some nice >> games: >> http://www.amazon.com/Python-Programming-Absolute-Beginner-Edition/dp/1435455002/ref=sr_1_6?ie=UTF8&qid=1333131438&sr=8-6 >> > If you haven't already found reference to it, you might also find pygame interesting. http://pygame.org/docs/tut/newbieguide.html From x23chris at gmail.com Sat Mar 31 00:20:12 2012 From: x23chris at gmail.com (X23chris@gmail.com) Date: Fri, 30 Mar 2012 18:20:12 -0400 Subject: [Tutor] Syntax error help In-Reply-To: <4F7625EE.4090701@gmail.com> References: <4F7625EE.4090701@gmail.com> Message-ID: <9742C3BA-DFB0-4077-9749-D9DFD668B3A7@gmail.com> Thanks I've fixed Sent from my iPod On Mar 30, 2012, at 5:30 PM, bob gailer wrote: > On 3/30/2012 4:26 PM, chris knarvik wrote: >> Alright i have been trying to right a (relatively) simple to calculate area and volume below is my current working code > > Suggestion: start with a VERY SIMPLE program and get that working. Then add one new feature at a time. > > Is the following in Area.py? If it is then the traceback could not have come from importing this code, because line 10 does not mention areamenu(). > In fact areamenu() appears ONLY in line 1, but not by itself! > >> def areamenu(): >> print 'Square (1)' >> print 'triangle (2)' >> print 'rectangle (3)' >> print 'trapazoid (4)' >> print 'circle (5)' >> >> def squareacalc(): >> sidelength = input('enter side length: ') >> print ' the side length is' sidelength ** 2 >> >> def displaymenu(): >> print 'please make a selection'; >> print 'Area (1)'; >> choice = input(raw_input('enter selection number'): >> if (choice == 1): >> Areamenu(): >> >> else: >> print 'choice' , choice, ' is wrong try again' >> >> def selctiona(): >> Areamenu(); >> choicea = input(raw_input'enter selection'); >> if (choicea == 1): >> squareacalc() >> >> >> >> print 'good bye' >> >> I keep getting this error >> Traceback (most recent call last): >> File "", line 1, in >> import Area >> File "C:\Python27\Area.py", line 10 >> areamenu() >> ^ >> SyntaxError: invalid syntax >> >> can anyone tell me what im doing wrong i cant see the problem >> help would be appreciated >> > What are you using to run the above? I'll guess the interactive window of IDLE. Try reload(Area). Once a module is imported you must reload to import it again. (I am assuming you made changes after the initial error.) > > The above code should give you something like: > Traceback (most recent call last): > File "", line 1, in > File "Script3.py", line 10 > print ' the side length is' sidelength ** 2 > ^ > SyntaxError: invalid syntax > > fix that (do you know what to do?) then you should get a syntax error for line15. Why is there a : at the end of that line? > then you have 1 more trailing : to deal with. > then there is a missing ) > then there is a missing ( > > Once you fix all the problems then you should see > good bye > since that is the only executable code in Area.py other than def statements. > > Suggestion: start with a VERY SIMPLE program and get that working. Then add one new feature at a time. > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC > From bgailer at gmail.com Sat Mar 31 01:38:26 2012 From: bgailer at gmail.com (bob gailer) Date: Fri, 30 Mar 2012 19:38:26 -0400 Subject: [Tutor] Syntax error help In-Reply-To: <9742C3BA-DFB0-4077-9749-D9DFD668B3A7@gmail.com> References: <4F7625EE.4090701@gmail.com> <9742C3BA-DFB0-4077-9749-D9DFD668B3A7@gmail.com> Message-ID: <4F7643F2.8080403@gmail.com> On 3/30/2012 6:20 PM, X23chris at gmail.com wrote: > Thanks I've fixed Great. Please share with us your new program and tell us what you do to run it. -- Bob Gailer 919-636-4239 Chapel Hill NC From breamoreboy at yahoo.co.uk Sat Mar 31 02:31:36 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 31 Mar 2012 01:31:36 +0100 Subject: [Tutor] Problem Stripping In-Reply-To: References: Message-ID: On 30/03/2012 18:28, Joel Goldstick wrote: > On Fri, Mar 30, 2012 at 1:25 PM, Joel Goldstick > wrote: >> On Fri, Mar 30, 2012 at 1:09 PM, leam hall wrote: >>> Python 2.4.3 on Red Hat 5. Trying to use strip to remove characters >>> but it doesn't seem to work like I thought. >>> >>> >>> res = subprocess.Popen(['uname', '-a'], stdout=subprocess.PIPE) >>> uname = res.stdout.read().strip() >>> >>>>>> uname >>> 'Linux myserver 2.6.18-274.el5PAE #1 SMP Fri Jul 8 17:59:09 EDT 2011 >>> i686 i686 i386 GNU/Linux' >>> >>>>>> uname.strip(':') >>> 'Linux myserver 2.6.18-274.el5PAE #1 SMP Fri Jul 8 17:59:09 EDT 2011 >>> i686 i686 i386 GNU/Linux' >>> >>>>>> 'www.example.com'.strip('cmowz.') >>> 'example' >>> >>> Thoughts? >>> >>> Leam >>> -- >>> Mind on a Mission >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >> >> str.strip() removes characters from begining and end of the string -- >> Not any in between. Notice >> >>>>> example = "www.example.com".strip("wcomx") >>>>> example >> '.example.' >>>>> >> >> The x remains > > > You could do list comprehension >> >>>> n = "".join([x for x in "this has : some : colons" if x not in ':']) >>>> n > 'this has some colons' >> Yuck :( Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> "this has : some : colons".replace(':', '') 'this has some colons' -- Cheers. Mark Lawrence. From bgailer at gmail.com Sat Mar 31 04:01:27 2012 From: bgailer at gmail.com (bob gailer) Date: Fri, 30 Mar 2012 22:01:27 -0400 Subject: [Tutor] Problem Stripping In-Reply-To: References: Message-ID: <4F766577.9040703@gmail.com> Then, of course, there's "15:45".replace(':','') -- Bob Gailer 919-636-4239 Chapel Hill NC From bgailer at gmail.com Sat Mar 31 04:20:47 2012 From: bgailer at gmail.com (bob gailer) Date: Fri, 30 Mar 2012 22:20:47 -0400 Subject: [Tutor] Syntax error help In-Reply-To: References: <4F7625EE.4090701@gmail.com> <9742C3BA-DFB0-4077-9749-D9DFD668B3A7@gmail.com> <4F7643F2.8080403@gmail.com> Message-ID: <4F7669FF.7020504@gmail.com> Please always reply-all so a copy goes to the list. On 3/30/2012 8:01 PM, chris knarvik wrote: > that was incomplete it was supposed to be ive fixed most of my > problems with your help That's great. Would you post the correct program so we can all learn? And possibly make other helpful suggestions. > what do you mean what do i do to run it There are several ways to execute (run) a Python program. You can double-click the file in an explorer. You can at a command prompt type (e.g.) >python Area.py or you can start an interactive session then type >>>import Area or you can use an IDE such as IDLE. within IDLE you can write the program in an edit window then RUN or you can use the interactive window and type >>>import Area Which of these (or what else) do you do -- Bob Gailer 919-636-4239 Chapel Hill NC From s.irfan.rizvi5 at gmail.com Sat Mar 31 04:33:51 2012 From: s.irfan.rizvi5 at gmail.com (S.Irfan Rizvi) Date: Fri, 30 Mar 2012 21:33:51 -0500 Subject: [Tutor] Syntax error help In-Reply-To: <4F7669FF.7020504@gmail.com> References: <4F7625EE.4090701@gmail.com> <9742C3BA-DFB0-4077-9749-D9DFD668B3A7@gmail.com> <4F7643F2.8080403@gmail.com> <4F7669FF.7020504@gmail.com> Message-ID: Please remove me from list....i can't do it....they are doing it Attention On Mar 30, 2012 9:21 PM, "bob gailer" wrote: > Please always reply-all so a copy goes to the list. > > On 3/30/2012 8:01 PM, chris knarvik wrote: > >> that was incomplete it was supposed to be ive fixed most of my problems >> with your help >> > > That's great. Would you post the correct program so we can all learn? And > possibly make other helpful suggestions. > > what do you mean what do i do to run it >> > There are several ways to execute (run) a Python program. > You can double-click the file in an explorer. > You can at a command prompt type (e.g.) >python Area.py > or you can start an interactive session then type >>>import Area > or you can use an IDE such as IDLE. > within IDLE you can write the program in an edit window then RUN > or you can use the interactive window and type >>>import Area > Which of these (or what else) do you do > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Sat Mar 31 14:41:20 2012 From: bgailer at gmail.com (bob gailer) Date: Sat, 31 Mar 2012 08:41:20 -0400 Subject: [Tutor] Syntax error help In-Reply-To: References: <4F7625EE.4090701@gmail.com> <9742C3BA-DFB0-4077-9749-D9DFD668B3A7@gmail.com> <4F7643F2.8080403@gmail.com> <4F7669FF.7020504@gmail.com> Message-ID: <4F76FB70.7000002@gmail.com> Thank you for posting your code. Did you forget to reply-all? I am copying this to the list this time. You apparantly misunderstood my question about what you do to run the program. You said " I import then call the first function (the displaymenu) or I have it called in the code it does it automatically". I am running out of patience trying to get from you what we as a Tutor List need in order to help you. Please answer the following: What operating system are you using (Windows, Linux, Mac, ...) WHAT DO YOU DO RUN THE PROGRAM. I gave detailed examples of potential answers (see below). Do you not understand what I'm looking for? On 3/30/2012 11:22 PM, chris knarvik wrote: > Also here is my revised code with what i call a 'programmers error' > let me know if you see it because i dont > Why all the imports - you are not using any math, os or sys code. Also You should not do 2 different imports from math. It is better to drop the from ... > import math > import os, sys > from math import * > > def displaymenu(): > print 'please make a selection'; > print 'Area (1)'; > choice = raw_input('enter selection number') OK time to learn how to debug. Since the code goes from if to print, the if condition (choice == 1) must be False. What datatype does raw_input give you? Why would that cause the condition to be False? One way to answer that is to read the manual regarding raw_input. Another is to use print statements with type() to tell you the types. Therefore just before the if put print type(choice), type(1) > > if choice == 1: > selctiona() > else: > print'choice',choice,'is wrong' > print"why god wont this thing work" > > > def areamenu(): > print 'Square (1)' > print 'triangle (2)' > print 'rectangle (3)' > print 'trapazoid (4)' > print 'circle (5)' > > def selctiona(): > areamenu(); > choicea = raw_input('enter selection'); > if choicea == 1: > squareacalc() > > else: > print 'why god why' > > def squareacalc(): > sidelength = input('enter side length: ') > print "The Area Is", sidelength **2 > You don't seem to call reloadarea! > def reloadarea(): > print 'would you like to calculate again' > choicer = raw_input('yes(1) or no(2)') > if choicer == 1: This is called recursion. It is better in this kind of program to put the entire thing in a while loop(see below)* rather than to use a recursive call. > displaymenu() > elif choicer == 2: > print 'goodbye' > > displaymenu() > > i cant get past the display menu i get this result > please make a selection > Area (1) > enter selection number1 > choice 1 is wrong > why god wont this thing work > > >>> > let me know if you can see where i went wrong > I hope the guidance I gave above helps. * Using a while loop instead of recursion: while True: displaymenu() print 'would you like to calculate again' choicer = raw_input('yes(1) or no(2)') if choicer == 2: # this also will not work, for the same reason that choice == 1 does not work. Once you fix choice == 1 then you can also fix this. break > >> >> what do you mean what do i do to run it >> >> There are several ways to execute (run) a Python program. >> You can double-click the file in an explorer. >> You can at a command prompt type (e.g.) >python Area.py >> or you can start an interactive session then type >>>import Area >> or you can use an IDE such as IDLE. >> within IDLE you can write the program in an edit window then RUN >> or you can use the interactive window and type >>>import Area >> Which of these (or what else) do you do >> > -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Sat Mar 31 15:22:58 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 31 Mar 2012 14:22:58 +0100 Subject: [Tutor] Problem Stripping In-Reply-To: <4F766577.9040703@gmail.com> References: <4F766577.9040703@gmail.com> Message-ID: On 31/03/2012 03:01, bob gailer wrote: > Then, of course, there's "15:45".replace(':','') > For the record in earlier Python versions such as the one the OP is using you can do >>> allchars = "".join([chr(x) for x in range(256)]) >>> 'www.example.com'.translate(allchars, 'cmowz.') 'exaple' As of Python 2.6 you don't even need the allchars hence >>> 'www.example.com'.translate(None, 'cmowz.') 'exaple' -- Cheers. Mark Lawrence. From bdrake at crosswire.org Sat Mar 31 23:37:53 2012 From: bdrake at crosswire.org (Barry Drake) Date: Sat, 31 Mar 2012 22:37:53 +0100 Subject: [Tutor] breeds of Python ..... Message-ID: <4F777931.5010204@crosswire.org> After following the reading suggestions, I soon found myself looking at quite a few code examples that would only run under a particular version of python. Finally, I converted the example that I was working on to run under Python3. I just wondered if you guys would advise a newbie like me to concentrate on Python3 or stay with Python2 and get into bad habits when it comes to change eventually? Apart from the print and input functions, I haven't so far got a lot to re-learn. Kind regards, Barry. -- From Barry Drake - a member of the Ubuntu advertising team.