From steve at pearwood.info Fri Apr 1 00:16:21 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 01 Apr 2011 09:16:21 +1100 Subject: [Tutor] Importing sub modules In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2D94821A9A@EMARC112VS01.exchad.jpmchase.net> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2D9482150E@EMARC112VS01.exchad.jpmchase.net> <0604E20B5F6F2F4784C9C8C71C5DD4DD2D94821A9A@EMARC112VS01.exchad.jpmchase.net> Message-ID: <4D94FD35.9050209@pearwood.info> Prasad, Ramit wrote: > The joins are really just random calls. I was just curious if importing os.path could avoid any reading/overhead that might occur by importing os. No. Python has no way of knowing what os.path is until it has imported os and can do an attribute lookup on os.path. This is determined at runtime by the os module, and depends on your operating system: >>> import os.path >>> os >>> os.path DO NOT try importing posixpath (or equivalent for other OSes) directly, always use os.path. -- Steven From steve at pearwood.info Fri Apr 1 00:37:52 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 01 Apr 2011 09:37:52 +1100 Subject: [Tutor] Importing sub modules In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2D94821B9F@EMARC112VS01.exchad.jpmchase.net> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2D9482150E@EMARC112VS01.exchad.jpmchase.net><0604E20B5F6F2F4784C9C8C71C5DD4DD2D94821A9A@EMARC112VS01.exchad.jpmchase.net> <1515192433-1301608406-cardhu_decombobulator_blackberry.rim.net-909595448-@bda346.bisx.prod.on.blackberry> <0604E20B5F6F2F4784C9C8C71C5DD4DD2D94821B9F@EMARC112VS01.exchad.jpmchase.net> Message-ID: <4D950240.7080802@pearwood.info> Prasad, Ramit wrote: >>> In any event, you shouldn't be worrying about something like overhead until after your base prorgram is written. > > Base programs are written. I was just looking into insight about the mechanics behind importing :) > For instance, do these libraries normally lazy load? If you have mod1.mod2 and mod1.mod3 and import mod1 does it usually also internally load mod2/3? import mod1.mod2 (or do from mod1 import mod2) does it avoid any loading of mod3 or does it do that as part of loading mod1? That depends on the module. In the case of os, it has code like the following: if 'posix' in _names: name = 'posix' linesep = '\n' from posix import * try: from posix import _exit except ImportError: pass import posixpath as path import posix __all__.extend(_get_exports_list(posix)) del posix elif 'nt' in _names: # ... similar code elif 'os2' in _names: # ... elif 'mac' in _names: # ... elif 'ce' in _names: # ... elif 'riscos' in _names: # ... else: # raise exception So in the case of os, no, it does not lazily load path only when needed, and os.path is available as soon as you import os, without any further imports. However, if the module is a more modern package, the situation *may* be different. A package uses a directory with sub-modules, plus an __init__.py file. In this case, the behaviour is entirely up to the author. Here's an example from one of my own Python 3 libraries: I have a package that (currently) looks something like this: stats/ +-- __init__.py +-- co.py +-- order.py +-- utils.py +-- _tests/ +-- test_co.py ... etc. (greatly simplified). When you call "import stats", Python reads the file stats/__init__.py, compiles it and creates a module from it. __init__.py in turn includes a line "from . import utils". (This is Python 3 syntax, so it doesn't work with Python 2.) That line imports the stats/utils.py submodule and makes it available from within stats as stats.utils. However the sub-modules co.py and order.py are *not* imported by the main module. They are only loaded on demand, when you say "import stats.co" or "from stats.order import median" or similar. So it depends on the module. -- Steven From bgailer at gmail.com Fri Apr 1 03:22:31 2011 From: bgailer at gmail.com (bob gailer) Date: Thu, 31 Mar 2011 20:22:31 -0500 Subject: [Tutor] Importing sub modules In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2D9482150E@EMARC112VS01.exchad.jpmchase.net> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2D9482150E@EMARC112VS01.exchad.jpmchase.net> Message-ID: <4D9528D7.2000404@gmail.com> On 3/31/2011 1:07 PM, Prasad, Ramit wrote: > > > This communication is for informational purposes only. It is not > intended as an offer or solicitation for the purchase or sale of > any financial instrument or as an official confirmation of any > transaction. All market prices, data and other information are not > warranted as to completeness or accuracy and are subject to change > without notice. Any comments or statements made herein do not > necessarily reflect those of JPMorgan Chase& Co., its subsidiaries > and affiliates. > > This transmission may contain information that is privileged, > confidential, legally privileged, and/or exempt from disclosure > under applicable law. If you are not the intended recipient, you > are hereby notified that any disclosure, copying, distribution, or > use of the information contained herein (including any reliance > thereon) is STRICTLY PROHIBITED. Although this transmission and any > attachments are believed to be free of any virus or other defect > that might affect any computer system into which it is received and > opened, it is the responsibility of the recipient to ensure that it > is virus free and no responsibility is accepted by JPMorgan Chase& > Co., its subsidiaries and affiliates, as applicable, for any loss > or damage arising in any way from its use. If you received this > transmission in error, please immediately contact the sender and > destroy the material in its entirety, whether in electronic or hard > copy format. Thank you. > > Please refer to http://www.jpmorgan.com/pages/disclosures for > disclosures relating to European legal entities. > I hope your lawyers are happy with the above text. I personally find it annoying. I certainly would not be bothered to wonder whether i "received this transmission in error" or to contact the sender or destroy the material! "STRICTLY PROHIBITED" oh I am so scared! So there! -- Bob Gailer 919-636-4239 Chapel Hill NC From ranjand2005 at gmail.com Fri Apr 1 09:52:17 2011 From: ranjand2005 at gmail.com (ranjan das) Date: Fri, 1 Apr 2011 13:22:17 +0530 Subject: [Tutor] Removing values from a dictionary if they are present in a list Message-ID: I have the following information A={'g2': [4,5,3], 'g1': [1, 3]} B=[2,3,5] Now I want to remeove the elements in B if they are present (as values) in dictionary A. My expected solution is A= {'g2': [4], 'g1': [1] } I wrote the following piece of code which gives me thhe right code, but I am sure there must be a much shorter and more elegant way of doing it. Please suggest reject_list=[] for element in B: for key in A.keys(): for i in range(len(A[key])): if element==A[key][i]: reject_list.append((key,A[key][i])) print reject_list for i in range(len(reject_list)): print (reject_list[i][0],reject_list[i][1]) Index=A[reject_list[i][0]].index(reject_list[i][1]) print (reject_list[i][0],reject_list[i][1],Index) del A[reject_list[i][0]][Index] print A result obtained: {'g2': [4], 'g1': [1]} -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Apr 1 10:10:24 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 1 Apr 2011 09:10:24 +0100 Subject: [Tutor] Removing values from a dictionary if they are present in alist References: Message-ID: "ranjan das" wrote > A={'g2': [4,5,3], 'g1': [1, 3]} > > B=[2,3,5] > > Now I want to remeove the elements in B if they are present (as > values) in > dictionary A. My first thought was to start with the dictionary, something like for key in A: A[key] = [val for val in A[key] if val not in B] Dunno what the efficiency will be like because there are a lot of hidden loops going on - but at least they are in C not Python. But I don't think it would be much worse than your option... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From __peter__ at web.de Fri Apr 1 10:11:44 2011 From: __peter__ at web.de (Peter Otten) Date: Fri, 01 Apr 2011 10:11:44 +0200 Subject: [Tutor] Removing values from a dictionary if they are present in a list References: Message-ID: ranjan das wrote: > I have the following information > > A={'g2': [4,5,3], 'g1': [1, 3]} > > B=[2,3,5] > > Now I want to remeove the elements in B if they are present (as values) in > dictionary A. > > My expected solution is > > A= {'g2': [4], 'g1': [1] } > > I wrote the following piece of code which gives me thhe right code, but I > am sure there must be a much shorter and more elegant way of doing it. > Please suggest The following is a bit shorter, but not really elegant: >>> a = {'g2': [4, 5, 3], 'g1': [1, 3]} >>> b = [2, 3, 5] >>> for v in a.itervalues(): ... v[:] = [item for item in v if item not in b] ... >>> a {'g2': [4], 'g1': [1]} If you are free to choose your data types use sets instead of lists: >>> a = {'g2': set([4, 5, 3]), 'g1': set([1, 3])} >>> b = set([2, 3, 5]) >>> for v in a.itervalues(): ... v -= b ... >>> a {'g2': set([4]), 'g1': set([1])} From alan.gauld at btinternet.com Fri Apr 1 10:16:11 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 1 Apr 2011 09:16:11 +0100 Subject: [Tutor] Importing sub modules References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2D9482150E@EMARC112VS01.exchad.jpmchase.net> <4D9528D7.2000404@gmail.com> Message-ID: "bob gailer" wrote > On 3/31/2011 1:07 PM, Prasad, Ramit wrote: >> >> This communication is for informational purposes only. It is not >> intended as an offer or solicitation for the purchase or sale of >> any financial instrument or as an official confirmation of any >> transaction. All market prices, ..... >>....no responsibility is accepted by JPMorgan Chase& >>... > I hope your lawyers are happy with the above text. I personally find > it annoying. Its a sad fact of modern life that many companies insist on adding these legal notices to outgoing mail. My own company does the same to anything I send from my work account outside the business. Its not quite as long as JPs above but it has much the same tone. :-( Corporate paranoia is a sad but inevitable side effect of the litigation crazy society we now live in coupled to the universal reach of the internet... Alan G. From andreengels at gmail.com Fri Apr 1 10:25:54 2011 From: andreengels at gmail.com (Andre Engels) Date: Fri, 1 Apr 2011 10:25:54 +0200 Subject: [Tutor] Removing values from a dictionary if they are present in a list In-Reply-To: References: Message-ID: On Fri, Apr 1, 2011 at 9:52 AM, ranjan das wrote: > I have the following information > > A={'g2': [4,5,3], 'g1': [1, 3]} > > B=[2,3,5] > > Now I want to remeove the elements in B if they are present (as values) in > dictionary A. > > My expected solution is > > A= {'g2': [4], 'g1': [1] } > > I wrote the following piece of code which gives me thhe right code, but I am > sure there must be a much shorter and more elegant way of doing it. Please > suggest > > reject_list=[] > > for element in B: > > ??? for key in A.keys(): > > ??????? for i in range(len(A[key])): > > ??????????? if element==A[key][i]: > > ??????????????? reject_list.append((key,A[key][i])) > > > > print reject_list > > > for i in range(len(reject_list)): > > ??? print (reject_list[i][0],reject_list[i][1]) > > ??? Index=A[reject_list[i][0]].index(reject_list[i][1]) > > ??? print (reject_list[i][0],reject_list[i][1],Index) > > ??? del A[reject_list[i][0]][Index] First, your loops are distinctly unpythonic. In many other languages one does indeed go over a list or similar object by having a numeric loop variable i, and then using list[i], but in Python we loop over the list itself instead. Applying that to your code, and removing the in-between prints, we get: reject_list=[] for element in B: for key in A.keys(): for Aelement in A[key]: if element == Aelement: reject_list.append(key, Aelement) for deleteelement in reject_list: index = A[deletelement[0]].index(deleteelement[1]) del A[deleteelement[0]][index] Next, realize that we are comparing each element in B with each element in A, and then add information only on the element of A to the list. Also, there is no need to add something twice if it occurs twice in B. Thus, we can simplify this by just checking for each element of A whether it is in B: reject_list = [] for key in A.keys(): for element in A[key]: if element in B: reject_list.append(key, element) for deleteelement in reject_list: index = A[deletelement[0]].index(deleteelement[1]) del A[deleteelement[0]][index] However, when working this way, we will have all elements from one key in A together. We could also work with a separate list for each key, and do those in turns: for key in A.keys(): reject_list = [] for element in A[key]: if element in B: reject_list.append(element) for element in reject_list: index = A[key].index(element) del A[key][index] Still, we can go further. Why first create a list of things to do and then do it? We can do it immediately; however, then we have to change the loop variable, because things go wrong if you remove elements from a list while looping over that same list. for key in A.keys(): copy = A[key][:] for element in copy: if element in B: index = A[key].index(element) del A[key][index] A further small shortening is done by realizing that the default way of looping over a dictionary is to loop over its keys: for key in A: copy = A[key][:] for element in copy: if element in B: index = A[key].index(element) del A[key][index] A following step is to see that we only use the keys to get to the values. Why not use the values directly? for value in A.values(): copy = value[:] for element in copy: if element in B: index = value.index(element) del value[index] Can this still be shortened? Definitely. However, for the most obvious shortening I have to make an assumption, namely that the values in A are _not_ used elsewhere. Upto now we have removed elements from those values; we now will replace the value instead. This means that in Z = [0, 1] A = {"Hello": Z, "Goodbye: [0,2]} B = [0] # The previous code Z will have changed to [1] whereas in Z = [0, 1] A = {"Hello": Z, "Goodbye: [0,2]} B = [0] # The upcoming code Z will have remained [0,1] With this proviso, we have: for key in A: newvalue = [] for element in A[key]: if element not in B: newvalue.append(element) A[key] = newvalue This on itself is not shorter than the previous forms, but it can be used in a list expression like this: for key in A: A[key] = [element for element in A[key] if element not in B] -- Andr? Engels, andreengels at gmail.com From steve at pearwood.info Fri Apr 1 14:12:06 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 01 Apr 2011 23:12:06 +1100 Subject: [Tutor] Removing values from a dictionary if they are present in a list In-Reply-To: References: Message-ID: <4D95C116.7070400@pearwood.info> ranjan das wrote: > I have the following information > > A={'g2': [4,5,3], 'g1': [1, 3]} > > B=[2,3,5] > > Now I want to remeove the elements in B if they are present (as values) in > dictionary A. > > My expected solution is > > A= {'g2': [4], 'g1': [1] } Do you care about the order of the elements in A's values? Will there be any duplicate values? If the answer is No to both of those, the simplest solution is probably this: b = set(B) for key, values in A.items(): A[key] = list( set(values).difference(b) ) For Python 3, you will need to change the call A.items() to list(A.items()), but otherwise they should be the same. If you do care about order and duplicates, then this should do it: # untested for key, values in A.items(): A[key] = [x for x in values if x not in B] Not the most efficient code in the universe, but for small lists (say, a few hundred items) it should be perfectly fine. -- Steven From __peter__ at web.de Fri Apr 1 14:49:26 2011 From: __peter__ at web.de (Peter Otten) Date: Fri, 01 Apr 2011 14:49:26 +0200 Subject: [Tutor] Removing values from a dictionary if they are present in a list References: <4D95C116.7070400@pearwood.info> Message-ID: Steven D'Aprano wrote: > b = set(B) > for key, values in A.items(): > A[key] = list( set(values).difference(b) ) > > > For Python 3, you will need to change the call A.items() to > list(A.items()), but otherwise they should be the same. The documentation doesn't say so explicitly, see http://docs.python.org/dev/py3k/library/stdtypes.html """ Iterating views while adding or deleting entries in the dictionary may raise a RuntimeError or fail to iterate over all entries. """ but I think you can change the values without converting the dictview to a list first: >>> a = {1:2, 3:4, 5:6} >>> for k, v in a.items(): ... a[k] = "+" * v ... >>> a {1: '++', 3: '++++', 5: '++++++'} From ramit.prasad at jpmchase.com Fri Apr 1 17:08:28 2011 From: ramit.prasad at jpmchase.com (Prasad, Ramit) Date: Fri, 1 Apr 2011 11:08:28 -0400 Subject: [Tutor] Importing sub modules In-Reply-To: <4D950240.7080802@pearwood.info> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2D9482150E@EMARC112VS01.exchad.jpmchase.net><0604E20B5F6F2F4784C9C8C71C5DD4DD2D94821A9A@EMARC112VS01.exchad.jpmchase.net> <1515192433-1301608406-cardhu_decombobulator_blackberry.rim.net-909595448-@bda346.bisx.prod.on.blackberry> <0604E20B5F6F2F4784C9C8C71C5DD4DD2D94821B9F@EMARC112VS01.exchad.jpmchase.net> <4D950240.7080802@pearwood.info> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2D94902578@EMARC112VS01.exchad.jpmchase.net> >However the sub-modules co.py and order.py are *not* imported by the >main module. They are only loaded on demand, when you say "import >stats.co" or "from stats.order import median" or similar. >So it depends on the module. That is exactly what I wondering and an excellent example to illustrate it. Thank you! Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase & Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase & Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities. From markrivet at gsoftcon.com Fri Apr 1 17:42:07 2011 From: markrivet at gsoftcon.com (markrivet at gsoftcon.com) Date: Fri, 1 Apr 2011 11:42:07 -0400 (EDT) Subject: [Tutor] PyVISA GPIB Message-ID: <1301672527.898215843@192.168.4.58> I would like to control electronic instruments with PyVISA. I have downloaded PyVISA and unpacked the files into the Python27/lib/site-packages dir and in the IDLE GUI I run "import visa' for a quick check and I get this error: import visa Traceback (most recent call last): File "", line 1, in import visa ImportError: No module named visa I'm scratching my head. Help Mark R Rivet, Genesis Software Consulting ASCT(Computer Technologies), BSIT/SE(Software Engineering) Electrical Engineering Technician Member IEEE, Computer Society Do or do not; there is no try. From karim.liateni at free.fr Fri Apr 1 18:50:14 2011 From: karim.liateni at free.fr (Karim) Date: Fri, 01 Apr 2011 18:50:14 +0200 Subject: [Tutor] argparse csv + choices In-Reply-To: References: Message-ID: <4D960246.80105@free.fr> On 03/30/2011 06:05 PM, Robert Kern wrote: > On 3/30/11 10:32 AM, Neal Becker wrote: >> I'm trying to combine 'choices' with a comma-seperated list of >> options, so I >> could do e.g., >> >> --cheat=a,b >> >> parser.add_argument ('--cheat', choices=('a','b','c'), >> type=lambda x: >> x.split(','), default=[]) >> >> test.py --cheat a >> error: argument --cheat: invalid choice: ['a'] (choose from 'a', >> 'b', 'c') >> >> The validation of choice is failing, because parse returns a list, >> not an item. >> Suggestions? > > Do the validation in the type function. > > > import argparse > > class ChoiceList(object): > def __init__(self, choices): > self.choices = choices > > def __repr__(self): > return '%s(%r)' % (type(self).__name__, self.choices) > > def __call__(self, csv): > args = csv.split(',') > remainder = sorted(set(args) - set(self.choices)) > if remainder: > raise ValueError("invalid choices: %r (choose from %r)" % > (remainder, self.choices)) > return args > > > parser = argparse.ArgumentParser() > parser.add_argument('--cheat', type=ChoiceList(['a','b','c']), > default=[]) > print parser.parse_args(['--cheat=a,b']) > parser.parse_args(['--cheat=a,b,d']) > Hello, Great code, Simply for nicer output could be: def __call__(self, csv): try: args = csv.split(',') remainder = sorted(set(args) - set(self.choices)) if remainder: raise ValueError("invalid choices: %r (choose from %r)" % (remainder, self.choices)) return args except ValueError, e: raise argparse.ArgumentTypeError(e) Regards Karim From drbedsole at gmail.com Fri Apr 1 19:00:28 2011 From: drbedsole at gmail.com (Donald Bedsole) Date: Fri, 1 Apr 2011 13:00:28 -0400 Subject: [Tutor] PyVISA GPIB In-Reply-To: <1301672527.898215843@192.168.4.58> References: <1301672527.898215843@192.168.4.58> Message-ID: Hi Mark, On Fri, Apr 1, 2011 at 11:42 AM, wrote: > ?I would like to control electronic instruments with PyVISA. I have downloaded PyVISA and unpacked the files into the Python27/lib/site-packages dir and in the IDLE > GUI I run "import visa' for a quick check and I get this error: > > import visa > > Traceback (most recent call last): > ?File "", line 1, in > ? ?import visa > ImportError: No module named visa > > I'm scratching my head. Help > > Mark R Rivet, Genesis Software Consulting > ASCT(Computer Technologies), BSIT/SE(Software Engineering) > Electrical Engineering Technician > Member IEEE, Computer Society > > > Do or do not; there is no try. Could this be the problem? PyVISA doesn?t implement VISA itself. Instead, PyVISA provides bindings to the VISA library (a DLL or ?shared object? ?le). This library is usually shipped with your GPIB interface or software like LabVIEW. Alternatively, you can download it from your favourite equipment vendor (National Instruments, Agilent, etc). quote from this document: http://pyvisa.sourceforge.net/pyvisa.pdf From karim.liateni at free.fr Fri Apr 1 19:09:00 2011 From: karim.liateni at free.fr (Karim) Date: Fri, 01 Apr 2011 19:09:00 +0200 Subject: [Tutor] Meta language and code generation Message-ID: <4D9606AC.3020909@free.fr> Hello All, I would to ask you if somebody has experience or can give direction in a new project I have. I have a meta language description (in xml) from which I should generate code on different languages. In my case, lisp and tcl. Any idea in term of design, examples, links will be appreciated! Kind Regards Karim From drbedsole at gmail.com Fri Apr 1 19:11:17 2011 From: drbedsole at gmail.com (Donald Bedsole) Date: Fri, 1 Apr 2011 13:11:17 -0400 Subject: [Tutor] PyVISA GPIB In-Reply-To: References: <1301672527.898215843@192.168.4.58> Message-ID: Sorry, On Fri, Apr 1, 2011 at 1:00 PM, Donald Bedsole wrote: > Hi Mark, > > On Fri, Apr 1, 2011 at 11:42 AM, ? wrote: >> ?I would like to control electronic instruments with PyVISA. I have downloaded PyVISA and unpacked the files into the Python27/lib/site-packages dir and in the IDLE >> GUI I run "import visa' for a quick check and I get this error: >> >> import visa >> >> Traceback (most recent call last): >> ?File "", line 1, in >> ? ?import visa >> ImportError: No module named visa >> >> I'm scratching my head. Help >> >> Mark R Rivet, Genesis Software Consulting >> ASCT(Computer Technologies), BSIT/SE(Software Engineering) >> Electrical Engineering Technician >> Member IEEE, Computer Society >> >> >> Do or do not; there is no try. > > Could this be the problem? > > PyVISA doesn?t implement VISA itself. Instead, PyVISA provides > bindings to the VISA library (a DLL or > ?shared object? ?le). This library is usually shipped with your GPIB > interface or software like LabVIEW. Alternatively, you can download it > from your favourite equipment vendor (National Instruments, Agilent, > etc). > > quote from this document: > > http://pyvisa.sourceforge.net/pyvisa.pdf > I read the document a little better and visa is supposed to be part of the function. But maybe something else in the document might help you. From susana.delgado_s at utzmg.edu.mx Fri Apr 1 19:15:23 2011 From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez) Date: Fri, 1 Apr 2011 11:15:23 -0600 Subject: [Tutor] Run application from MS-DOS with sys.argv In-Reply-To: References: Message-ID: Hello! I'm going to answer to the question I posted in this list. After a search trouhg web and analize the code, I just had to add a try/except statement. Now I get what I need. Here is the information: directorio = sys.argv[1] extension = sys.argv[2] csv_salida = sys.argv[3] #Here I add the line: try: if len(sys.argv) == 4: ........................ ........................ else: print "Tus argumentos no son correctos" and here: except IndexError: print "Tus argumentos no son correctos" 2011/3/29 Susana Iraiis Delgado Rodriguez > Hello List: > > I developed a script to walk through a specific directory in my PC and > look for files with the same extension (.shp). I want the user to enter from > MS-DOS and write the the directory, file extension and csv filename. > My script reads the arguments from Windows console, but when I opened the > txt file and csv file I noticed that isn't walking through all the root I > wrote in MS-DOS. This is my module: > > import os, csv, time, socket, sys > from osgeo import ogr,gdal,osr > #This should be the order for the arguments('csv_args.py [root] > [file_extension] [csv filename]') > #The user is typing python csv_args.py C:\ .shp csv.csv > directorio = sys.argv[1] > extension = sys.argv[2] > csv_salida = sys.argv[3] > if len(sys.argv) == 4: > print 'Iniciando...' > gdal.AllRegister() > file_list = [] > folders = None > for root, folders, files in os.walk(directorio): > file_list.extend(os.path.join(root,fi) for fi in files if > fi.endswith(extension)) > f = open(csv_salida, 'wb') > log = open ('errores.txt','w') > writer = csv.writer(f) > ruta = 'Ruta' > archivo = 'archivo' > x_min = 'x_min' > x_max = 'x_max' > y_min = 'y_min' > y_max = 'y_max' > geometria = 'geometria' > num_elem = 'num_elem' > prj = '.prj' > proyeccion = 'proyeccion' > fecha = 'fecha_modificacion' > maq = 'maquina_host' > usu = 'usuario' > campos = > [ruta,archivo,x_min,x_max,y_min,y_max,geometria,num_elem,prj,proyeccion,fecha,maq,usu] > writer.writerow(campos) > for row, filepath in enumerate(file_list, start=1): > (ruta, filename) = os.path.split(filepath) > shapeData = ogr.Open(filepath) > shp = 'Error al abrir el archivo' +filepath > if shapeData is None: > print shp > log.write(shp+"\n") > else: > layer = shapeData.GetLayer() > feature = layer.GetNextFeature() > x_y = layer.GetExtent() > x1 = x_y[0] > x2 = x_y[1] > y1 = x_y[2] > y2 = x_y[3] > defn = layer.GetLayerDefn() > geo = defn.GetGeomType() > cuenta = layer.GetFeatureCount() > proy = layer.GetSpatialRef() > prjtext = ''+str(proy)+'' > n = os.path.splitext(filepath) > p = n[0]+'.prj' > shx = n[0]+'.shx' > dbf = n[0]+'.dbf' > filepath = ''+filepath+'' > filename = ''+filename+'' > t = time.strftime("%m/%d/%Y %I:%M:%S > %p",time.localtime(os.path.getmtime(filepath))) > modificacion = ''+t+'' > usuario = os.environ.get("USERNAME") > user = ''+usuario+'' > host = socket.gethostname() > maquina = ''+host+'' > if os.path.exists(shx): > print 'El archivo ' +shx +' existe' > else: > og.write('No existe el archivo ' +shx+"\n") > if os.path.exists(dbf): > print 'El archivo ' +dbf +' existe' > else: > log.write('No existe el archivo ' +dbf+"\n") > if os.path.exists(p): > aRow= [ filepath, filename, x1, x2, y1, y2, geo, cuenta, 1, > prjtext, modificacion, maquina, user] > writer.writerow(aRow) > else: > aRow1= [ filepath, filename, x1, x2, y1, y2, geo, cuenta, > 0, prjtext, modificacion, maquina, user] > writer.writerow(aRow1) > log.close() > f.close() > print "El archivo esta listo" > else: > print "Tus argumentos no son correctos" > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Fri Apr 1 19:16:34 2011 From: breamoreboy at yahoo.co.uk (Blockheads Oi Oi) Date: Fri, 01 Apr 2011 18:16:34 +0100 Subject: [Tutor] PyVISA GPIB In-Reply-To: References: <1301672527.898215843@192.168.4.58> Message-ID: On 01/04/2011 18:00, Donald Bedsole wrote: > Hi Mark, > > On Fri, Apr 1, 2011 at 11:42 AM, wrote: >> I would like to control electronic instruments with PyVISA. I have downloaded PyVISA and unpacked the files into the Python27/lib/site-packages dir and in the IDLE >> GUI I run "import visa' for a quick check and I get this error: >> >> import visa >> >> Traceback (most recent call last): >> File "", line 1, in >> import visa >> ImportError: No module named visa >> >> I'm scratching my head. Help >> >> Mark R Rivet, Genesis Software Consulting >> ASCT(Computer Technologies), BSIT/SE(Software Engineering) >> Electrical Engineering Technician >> Member IEEE, Computer Society >> >> >> Do or do not; there is no try. > > Could this be the problem? No. The problem above is at a higher level. This is what you get at a lower level trying to import the code. At least I think so :) c:\Users\Mark\Cashflow\Python>python -V Python 2.7.1 c:\Users\Mark\Cashflow\Python>python -c "import visa" Traceback (most recent call last): File "", line 1, in File "c:\python27\lib\site-packages\visa.py", line 1, in from pyvisa.visa import * File "c:\python27\lib\site-packages\pyvisa\visa.py", line 231, in resource_manager = ResourceManager() File "c:\python27\lib\site-packages\pyvisa\vpp43.py", line 105, in __new__ it.init(*args, **kwds) File "c:\python27\lib\site-packages\pyvisa\visa.py", line 227, in init self.session = self.vi = vpp43.open_default_resource_manager() File "c:\python27\lib\site-packages\pyvisa\vpp43.py", line 758, in open_default_resource_manager visa_library().viOpenDefaultRM(byref(session)) File "c:\python27\lib\site-packages\pyvisa\vpp43.py", line 175, in __call__ self.load_library() File "c:\python27\lib\site-packages\pyvisa\vpp43.py", line 141, in load_library self.__lib = windll.visa32 File "c:\python27\lib\ctypes\__init__.py", line 423, in __getattr__ dll = self._dlltype(name) File "c:\python27\lib\ctypes\__init__.py", line 353, in __init__ self._handle = _dlopen(self._name, mode) WindowsError: [Error 126] The specified module could not be found > > PyVISA doesn?t implement VISA itself. Instead, PyVISA provides > bindings to the VISA library (a DLL or > ?shared object? ?le). This library is usually shipped with your GPIB > interface or software like LabVIEW. Alternatively, you can download it > from your favourite equipment vendor (National Instruments, Agilent, > etc). > > quote from this document: > > http://pyvisa.sourceforge.net/pyvisa.pdf > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Cheers. Mark L. From karim.liateni at free.fr Fri Apr 1 19:16:55 2011 From: karim.liateni at free.fr (Karim) Date: Fri, 01 Apr 2011 19:16:55 +0200 Subject: [Tutor] counting a list of elements Message-ID: <4D960887.3030102@free.fr> Hello, I would like to get advice on the best practice to count elements in a list (built from scractch). The number of elements is in the range 1e3 and 1e6. 1) I could create a generator and set a counter (i +=1) in the loop. 2) or simply len(mylist). I don't need the content of the list, indeed, in term of memory I don't want to wast it. But I suppose len() is optimized too (C impementation). If you have some thought to share don't hesitate. Karim From oberoc at gmail.com Fri Apr 1 19:49:02 2011 From: oberoc at gmail.com (Tino Dai) Date: Fri, 1 Apr 2011 13:49:02 -0400 Subject: [Tutor] Meta language and code generation In-Reply-To: <4D9606AC.3020909@free.fr> References: <4D9606AC.3020909@free.fr> Message-ID: On Fri, Apr 1, 2011 at 1:09 PM, Karim wrote: > > Hello All, > > I would to ask you if somebody has experience or can give direction in a > new project I have. > I have a meta language description (in xml) from which I should generate > code on different > languages. In my case, lisp and tcl. > > Any idea in term of design, examples, links will be appreciated! > > Karim, You might want check out Anltr. We were using it to translate from one query language to another. http://www.antlr.org/ http://www.antlr.org/api/Python/index.html -Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: From markrivet at gsoftcon.com Fri Apr 1 19:55:02 2011 From: markrivet at gsoftcon.com (markrivet at gsoftcon.com) Date: Fri, 1 Apr 2011 13:55:02 -0400 (EDT) Subject: [Tutor] PyVISA GPIB In-Reply-To: References: <1301672527.898215843@192.168.4.58> Message-ID: <1301680502.413417380@192.168.4.58> "Donald Bedsole" said: > Sorry, > > On Fri, Apr 1, 2011 at 1:00 PM, Donald Bedsole wrote: >> Hi Mark, >> >> On Fri, Apr 1, 2011 at 11:42 AM, ? wrote: >>> ?I would like to control electronic instruments with PyVISA. I have >>> downloaded PyVISA and unpacked the files into the Python27/lib/site-packages dir >>> and in the IDLE >>> GUI I run "import visa' for a quick check and I get this error: >>> >>> import visa >>> >>> Traceback (most recent call last): >>> ?File "", line 1, in >>> ? ?import visa >>> ImportError: No module named visa >>> >>> I'm scratching my head. Help >>> >>> Mark R Rivet, Genesis Software Consulting >>> ASCT(Computer Technologies), BSIT/SE(Software Engineering) >>> Electrical Engineering Technician >>> Member IEEE, Computer Society >>> >>> >>> Do or do not; there is no try. >> >> Could this be the problem? >> >> PyVISA doesn?t implement VISA itself. Instead, PyVISA provides >> bindings to the VISA library (a DLL or >> ?shared object? ?le). This library is usually shipped with >> your GPIB >> interface or software like LabVIEW. Alternatively, you can download it >> from your favourite equipment vendor (National Instruments, Agilent, >> etc). >> >> quote from this document: >> >> http://pyvisa.sourceforge.net/pyvisa.pdf >> > > I read the document a little better and visa is supposed to be part of > the function. But maybe something else in the document might help > you. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Yes, I better download that doc and read it carefully; thanks Mark R Rivet, Genesis Software Consulting ASCT(Computer Technologies), BSIT/SE(Software Engineering) Electrical Engineering Technician Member IEEE, Computer Society Do or do not; there is no try. From markrivet at gsoftcon.com Fri Apr 1 19:54:05 2011 From: markrivet at gsoftcon.com (markrivet at gsoftcon.com) Date: Fri, 1 Apr 2011 13:54:05 -0400 (EDT) Subject: [Tutor] PyVISA GPIB In-Reply-To: References: <1301672527.898215843@192.168.4.58> Message-ID: <1301680445.79949544@192.168.4.58> "Donald Bedsole" said: > Hi Mark, > > On Fri, Apr 1, 2011 at 11:42 AM, wrote: >> ?I would like to control electronic instruments with PyVISA. I have >> downloaded PyVISA and unpacked the files into the Python27/lib/site-packages dir >> and in the IDLE >> GUI I run "import visa' for a quick check and I get this error: >> >> import visa >> >> Traceback (most recent call last): >> ?File "", line 1, in >> ? ?import visa >> ImportError: No module named visa >> >> I'm scratching my head. Help >> >> Mark R Rivet, Genesis Software Consulting >> ASCT(Computer Technologies), BSIT/SE(Software Engineering) >> Electrical Engineering Technician >> Member IEEE, Computer Society >> >> >> Do or do not; there is no try. > > Could this be the problem? > > PyVISA doesn?t implement VISA itself. Instead, PyVISA provides > bindings to the VISA library (a DLL or > ?shared object? ?le). This library is usually shipped with your > GPIB > interface or software like LabVIEW. Alternatively, you can download it > from your favourite equipment vendor (National Instruments, Agilent, > etc). > > quote from this document: > > http://pyvisa.sourceforge.net/pyvisa.pdf > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Hmmm, that shouldn't be a problem, I have LabView installed on my pc. Mark R Rivet, Genesis Software Consulting ASCT(Computer Technologies), BSIT/SE(Software Engineering) Electrical Engineering Technician Member IEEE, Computer Society Do or do not; there is no try. From markrivet at gsoftcon.com Fri Apr 1 20:04:43 2011 From: markrivet at gsoftcon.com (markrivet at gsoftcon.com) Date: Fri, 1 Apr 2011 14:04:43 -0400 (EDT) Subject: [Tutor] PyVISA GPIB In-Reply-To: References: <1301672527.898215843@192.168.4.58> Message-ID: <1301681083.116925998@192.168.4.58> "Donald Bedsole" said: > Sorry, > > On Fri, Apr 1, 2011 at 1:00 PM, Donald Bedsole wrote: >> Hi Mark, >> >> On Fri, Apr 1, 2011 at 11:42 AM, ? wrote: >>> ?I would like to control electronic instruments with PyVISA. I have >>> downloaded PyVISA and unpacked the files into the Python27/lib/site-packages dir >>> and in the IDLE >>> GUI I run "import visa' for a quick check and I get this error: >>> >>> import visa >>> >>> Traceback (most recent call last): >>> ?File "", line 1, in >>> ? ?import visa >>> ImportError: No module named visa >>> >>> I'm scratching my head. Help >>> >>> Mark R Rivet, Genesis Software Consulting >>> ASCT(Computer Technologies), BSIT/SE(Software Engineering) >>> Electrical Engineering Technician >>> Member IEEE, Computer Society >>> >>> >>> Do or do not; there is no try. >> >> Could this be the problem? >> >> PyVISA doesn?t implement VISA itself. Instead, PyVISA provides >> bindings to the VISA library (a DLL or >> ?shared object? ?le). This library is usually shipped with >> your GPIB >> interface or software like LabVIEW. Alternatively, you can download it >> from your favourite equipment vendor (National Instruments, Agilent, >> etc). >> >> quote from this document: >> >> http://pyvisa.sourceforge.net/pyvisa.pdf >> > > I read the document a little better and visa is supposed to be part of > the function. But maybe something else in the document might help > you. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Well, I have Labview installed on my system including the visa libraries. Mark R Rivet, Genesis Software Consulting ASCT(Computer Technologies), BSIT/SE(Software Engineering) Electrical Engineering Technician Member IEEE, Computer Society Do or do not; there is no try. From emile at fenx.com Fri Apr 1 20:03:59 2011 From: emile at fenx.com (Emile van Sebille) Date: Fri, 01 Apr 2011 11:03:59 -0700 Subject: [Tutor] counting a list of elements In-Reply-To: <4D960887.3030102@free.fr> References: <4D960887.3030102@free.fr> Message-ID: On 4/1/2011 10:16 AM Karim said... > I would like to get advice on the best practice to count elements Well, I suspect you're more interested in knowing the total count of how many as opposed to counting how many. To get the total count of how many use len(mylist). Emile From knacktus at googlemail.com Fri Apr 1 20:04:13 2011 From: knacktus at googlemail.com (Knacktus) Date: Fri, 01 Apr 2011 20:04:13 +0200 Subject: [Tutor] counting a list of elements In-Reply-To: <4D960887.3030102@free.fr> References: <4D960887.3030102@free.fr> Message-ID: <4D96139D.6070807@googlemail.com> Am 01.04.2011 19:16, schrieb Karim: > > > Hello, > > I would like to get advice on the best practice to count elements in a > list (built from scractch). It's not clear to me what your starting point is. If you don't have a list and don't need a list, but have a large number of objects you create in your code sequentially or a large number of other events and you want to know how many of those objects exist / events have occured, then simply use a counter while creating. If you have a list (for whatever reason), then use len(). HTH, Jan > The number of elements is in the range 1e3 and 1e6. > > 1) I could create a generator and set a counter (i +=1) in the loop. > > 2) or simply len(mylist). > > I don't need the content of the list, indeed, in term of memory I don't > want to wast it. But I suppose len() is optimized too (C impementation). > > If you have some thought to share don't hesitate. > > Karim > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From eire1130 at gmail.com Fri Apr 1 20:10:52 2011 From: eire1130 at gmail.com (James Reynolds) Date: Fri, 1 Apr 2011 14:10:52 -0400 Subject: [Tutor] counting a list of elements In-Reply-To: <4D960887.3030102@free.fr> References: <4D960887.3030102@free.fr> Message-ID: The nice thing about Python is you don't have to build things from scratch, and I imagine most people would discourage on account of it being a waste of time, other then education value. But the "best practice" in my humble opinion would be to use the built in len function. If what you are after is to see how often 1e3 comes up in your list, then you would use list.count('1e3'). In general, its best to use the python built ins. On Fri, Apr 1, 2011 at 1:16 PM, Karim wrote: > > > Hello, > > I would like to get advice on the best practice to count elements in a list > (built from scractch). > The number of elements is in the range 1e3 and 1e6. > > 1) I could create a generator and set a counter (i +=1) in the loop. > > 2) or simply len(mylist). > > I don't need the content of the list, indeed, in term of memory I don't > want to wast it. But I suppose len() is optimized too (C impementation). > > If you have some thought to share don't hesitate. > > Karim > _______________________________________________ > 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 knacktus at googlemail.com Fri Apr 1 20:29:09 2011 From: knacktus at googlemail.com (Knacktus) Date: Fri, 01 Apr 2011 20:29:09 +0200 Subject: [Tutor] Meta language and code generation In-Reply-To: <4D9606AC.3020909@free.fr> References: <4D9606AC.3020909@free.fr> Message-ID: <4D961975.7070102@googlemail.com> Am 01.04.2011 19:09, schrieb Karim: > > Hello All, > > I would to ask you if somebody has experience or can give direction in a > new project I have. > I have a meta language description (in xml) from which I should generate > code on different > languages. In my case, lisp and tcl. You need to provide more information of your description to get some specific hints. The other day a had a xml file containing a business object model with hierarchy and relations. Then I wrote a code generator to build a module with Python classes for each business item. The code generator created properties for lazily resolving relations modelled via ids in the database and stuff like that. This was very straightforeward using a simple print statements like the following: print "class %s(object):\n" % class_name print " def __init__(self, %s)" % constr_arg ... Cheers, Jan > > Any idea in term of design, examples, links will be appreciated! > > Kind Regards > Karim > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From knacktus at googlemail.com Fri Apr 1 20:41:46 2011 From: knacktus at googlemail.com (Knacktus) Date: Fri, 01 Apr 2011 20:41:46 +0200 Subject: [Tutor] counting a list of elements In-Reply-To: <4D960887.3030102@free.fr> References: <4D960887.3030102@free.fr> Message-ID: <4D961C6A.5060509@googlemail.com> Am 01.04.2011 19:16, schrieb Karim: > > > Hello, > > I would like to get advice on the best practice to count elements in a > list (built from scractch). > The number of elements is in the range 1e3 and 1e6. > > 1) I could create a generator and set a counter (i +=1) in the loop. > > 2) or simply len(mylist). > > I don't need the content of the list, indeed, in term of memory I don't > want to wast it. But I suppose len() is optimized too (C impementation). > > If you have some thought to share don't hesitate. Just a general suggestion: Provide code examples. I know most of the times you don't have code examples yet as you're thinking of how to solve your problems. But if you post one of the possible solutions the experienced guys here will very likely direct you in the proper direction. But without code it's hard to understand what you're after. Cheers, Jan > > Karim > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From karim.liateni at free.fr Fri Apr 1 20:56:16 2011 From: karim.liateni at free.fr (Karim) Date: Fri, 01 Apr 2011 20:56:16 +0200 Subject: [Tutor] Meta language and code generation In-Reply-To: <4D961975.7070102@googlemail.com> References: <4D9606AC.3020909@free.fr> <4D961975.7070102@googlemail.com> Message-ID: <4D961FD0.1000000@free.fr> On 04/01/2011 08:29 PM, Knacktus wrote: > Am 01.04.2011 19:09, schrieb Karim: >> >> Hello All, >> >> I would to ask you if somebody has experience or can give direction in a >> new project I have. >> I have a meta language description (in xml) from which I should generate >> code on different >> languages. In my case, lisp and tcl. > > You need to provide more information of your description to get some > specific hints. The other day a had a xml file containing a business > object model with hierarchy and relations. Then I wrote a code > generator to build a module with Python classes for each business > item. The code generator created properties for lazily resolving > relations modelled via ids in the database and stuff like that. This > was very straightforeward using a simple print statements like the > following: > > print "class %s(object):\n" % class_name > print " def __init__(self, %s)" % constr_arg > ... > > Cheers, > > Jan In fact in xml I have something like that: A metafunction in fact kind of x y I have to generate the call_back_do_stuff_function(x,y) in lisp and tcl according to a catalog of specs of what this function must do generically. I can do prints for each metafunctio I read but my concern is is there std libs to help to have good design and methodology. Is it interesting to use command module of something like that, is interesting to use a parser like pylex or pyparsing? I have 50 metafunctions in catalog for now. In fact, my point is to have a great extensive design methodology. Strategy pattern would suit? Other patterns? std modules? Lots of question here! Regards Karim > >> >> Any idea in term of design, examples, links will be appreciated! >> >> Kind Regards >> Karim >> _______________________________________________ >> 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 From markrrivet at aol.com Fri Apr 1 19:17:04 2011 From: markrrivet at aol.com (Mark R Rivet) Date: Fri, 1 Apr 2011 13:17:04 -0400 Subject: [Tutor] PyVISA In-Reply-To: References: <70adf37c-d18a-404b-8127-6c870508d196@a17g2000yqn.googlegroups.com> Message-ID: <002501cbf090$9f9a7d90$decf78b0$@com> Well I tried the setup file and here is what I get: C:\Users\Rivetmr\PyVisa_1.3\PyVISA-1.3>Python setup.py install Traceback (most recent call last): File "setup.py", line 60, in home_dir = os.environ['HOME'] File "C:\Python27\Lib\os.py", line 423, in __getitem__ return self.data[key.upper()] KeyError: 'HOME' From: Yashwin Kanchan [mailto:yashwinkanchan at gmail.com] Sent: Friday, April 01, 2011 11:53 AM To: Manatee Cc: python-list at python.org Subject: Re: PyVISA Hi Have you installed the module after unzipping it? python setup.py install Got it from the README file in the downloaded tar. Regards Yashwin Kanchan On 1 April 2011 16:29, Manatee wrote: I have unpacked the PyVISA files into the Python/lib/site-packages dir and from the IDLE GUI I get and error import visa Traceback (most recent call last): File "", line 1, in import visa ImportError: No module named visa There must be more to just putting the files in the correct directory. Need help configuring PyVISA to work. My ultimate goal is to control electronic instruments with Python through visa. -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Fri Apr 1 20:59:17 2011 From: breamoreboy at yahoo.co.uk (Blockheads Oi Oi) Date: Fri, 01 Apr 2011 19:59:17 +0100 Subject: [Tutor] Run application from MS-DOS with sys.argv In-Reply-To: References: Message-ID: On 01/04/2011 18:15, Susana Iraiis Delgado Rodriguez wrote: > Hello! > > I'm going to answer to the question I posted in this list. > After a search trouhg web and analize the code, I just had to add a > try/except statement. Now I get what I need. Here is the information: > > directorio = sys.argv[1] > extension = sys.argv[2] > csv_salida = sys.argv[3] > #Here I add the line: > try: > if len(sys.argv) == 4: > ........................ > ........................ > else: > print "Tus argumentos no son correctos" > and here: > except IndexError: > print "Tus argumentos no son correctos" > You appear to be mixing two ways of doing the same thing. Either check the number of entries in sys.argv or catch the index error, don't do both. Read this, it probably explains things better than I can http://mail.python.org/pipermail/python-list/2003-May/203039.html > > 2011/3/29 Susana Iraiis Delgado Rodriguez > > > Hello List: > > I developed a script to walk through a specific directory in my PC > and look for files with the same extension (.shp). I want the user > to enter from MS-DOS and write the the directory, file extension and > csv filename. > My script reads the arguments from Windows console, but when I > opened the txt file and csv file I noticed that isn't walking > through all the root I wrote in MS-DOS. This is my module: > > import os, csv, time, socket, sys > from osgeo import ogr,gdal,osr > #This should be the order for the arguments('csv_args.py [root] > [file_extension] [csv filename]') > #The user is typing python csv_args.py C:\ .shp csv.csv > directorio = sys.argv[1] > extension = sys.argv[2] > csv_salida = sys.argv[3] > if len(sys.argv) == 4: > print 'Iniciando...' > gdal.AllRegister() > file_list = [] > folders = None > for root, folders, files in os.walk(directorio): > file_list.extend(os.path.join(root,fi) for fi in files if > fi.endswith(extension)) > f = open(csv_salida, 'wb') > log = open ('errores.txt','w') > writer = csv.writer(f) > ruta = 'Ruta' > archivo = 'archivo' > x_min = 'x_min' > x_max = 'x_max' > y_min = 'y_min' > y_max = 'y_max' > geometria = 'geometria' > num_elem = 'num_elem' > prj = '.prj' > proyeccion = 'proyeccion' > fecha = 'fecha_modificacion' > maq = 'maquina_host' > usu = 'usuario' > campos = > [ruta,archivo,x_min,x_max,y_min,y_max,geometria,num_elem,prj,proyeccion,fecha,maq,usu] > writer.writerow(campos) > for row, filepath in enumerate(file_list, start=1): > (ruta, filename) = os.path.split(filepath) > shapeData = ogr.Open(filepath) > shp = 'Error al abrir el archivo' +filepath > if shapeData is None: > print shp > log.write(shp+"\n") > else: > layer = shapeData.GetLayer() > feature = layer.GetNextFeature() > x_y = layer.GetExtent() > x1 = x_y[0] > x2 = x_y[1] > y1 = x_y[2] > y2 = x_y[3] > defn = layer.GetLayerDefn() > geo = defn.GetGeomType() > cuenta = layer.GetFeatureCount() > proy = layer.GetSpatialRef() > prjtext = ''+str(proy)+'' > n = os.path.splitext(filepath) > p = n[0]+'.prj' > shx = n[0]+'.shx' > dbf = n[0]+'.dbf' > filepath = ''+filepath+'' > filename = ''+filename+'' > t = time.strftime("%m/%d/%Y %I:%M:%S > %p",time.localtime(os.path.getmtime(filepath))) > modificacion = ''+t+'' > usuario = os.environ.get("USERNAME") > user = ''+usuario+'' > host = socket.gethostname() > maquina = ''+host+'' > if os.path.exists(shx): > print 'El archivo ' +shx +' existe' > else: > og.write('No existe el archivo ' +shx+"\n") > if os.path.exists(dbf): > print 'El archivo ' +dbf +' existe' > else: > log.write('No existe el archivo ' +dbf+"\n") > if os.path.exists(p): > aRow= [ filepath, filename, x1, x2, y1, y2, geo, > cuenta, 1, prjtext, modificacion, maquina, user] > writer.writerow(aRow) > else: > aRow1= [ filepath, filename, x1, x2, y1, y2, geo, > cuenta, 0, prjtext, modificacion, maquina, user] > writer.writerow(aRow1) > log.close() > f.close() > print "El archivo esta listo" > else: > print "Tus argumentos no son correctos" > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Cheers. Mark L. From alan.gauld at btinternet.com Fri Apr 1 21:10:37 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 1 Apr 2011 20:10:37 +0100 Subject: [Tutor] PyVISA References: <70adf37c-d18a-404b-8127-6c870508d196@a17g2000yqn.googlegroups.com> <002501cbf090$9f9a7d90$decf78b0$@com> Message-ID: "Mark R Rivet" wrote > Well I tried the setup file and here is what I get: > C:\Users\Rivetmr\PyVisa_1.3\PyVISA-1.3>Python setup.py install > Traceback (most recent call last): > File "setup.py", line 60, in > home_dir = os.environ['HOME'] Windows doesn't by default define a HOME environment variable. Are you sure your module is not Unix specific? If not then the easiest solution is probably to just define a value for HOME... and see if it works! HTH, Alan G. From breamoreboy at yahoo.co.uk Fri Apr 1 21:22:13 2011 From: breamoreboy at yahoo.co.uk (Blockheads Oi Oi) Date: Fri, 01 Apr 2011 20:22:13 +0100 Subject: [Tutor] PyVISA In-Reply-To: References: <70adf37c-d18a-404b-8127-6c870508d196@a17g2000yqn.googlegroups.com> <002501cbf090$9f9a7d90$decf78b0$@com> Message-ID: On 01/04/2011 20:10, Alan Gauld wrote: > > "Mark R Rivet" wrote > >> Well I tried the setup file and here is what I get: >> C:\Users\Rivetmr\PyVisa_1.3\PyVISA-1.3>Python setup.py install >> Traceback (most recent call last): >> File "setup.py", line 60, in >> home_dir = os.environ['HOME'] > > Windows doesn't by default define a HOME environment variable. > Are you sure your module is not Unix specific? > > If not then the easiest solution is probably to just define a value for > HOME... and see if it works! > > HTH, > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > I think someone has already said this, but just to be sure there's a Windows executable here http://sourceforge.net/projects/pyvisa/files/PyVISA/1.3/ HTH. Mark L. From karim.liateni at free.fr Fri Apr 1 21:31:19 2011 From: karim.liateni at free.fr (Karim) Date: Fri, 01 Apr 2011 21:31:19 +0200 Subject: [Tutor] counting a list of elements In-Reply-To: <4D961C6A.5060509@googlemail.com> References: <4D960887.3030102@free.fr> <4D961C6A.5060509@googlemail.com> Message-ID: <4D962807.5050101@free.fr> On 04/01/2011 08:41 PM, Knacktus wrote: > Am 01.04.2011 19:16, schrieb Karim: >> >> >> Hello, >> >> I would like to get advice on the best practice to count elements in a >> list (built from scractch). >> The number of elements is in the range 1e3 and 1e6. >> >> 1) I could create a generator and set a counter (i +=1) in the loop. >> >> 2) or simply len(mylist). >> >> I don't need the content of the list, indeed, in term of memory I don't >> want to wast it. But I suppose len() is optimized too (C impementation). >> >> If you have some thought to share don't hesitate. > > Just a general suggestion: Provide code examples. I know most of the > times you don't have code examples yet as you're thinking of how to > solve your problems. But if you post one of the possible solutions the > experienced guys here will very likely direct you in the proper > direction. But without code it's hard to understand what you're after. > > Cheers, > > Jan > Thank you all for you answers to clarified I built a collection of dictionnaries which represent database query on a bug tracking system: backlog_tables , csv_backlog_table = _backlog_database(table=table, periods=intervals_list) backlog_tables is a dictionnary of bug info dictionnaries. The keys of backlog_tables is a time intervall (YEAR-MONTH) as shown below: backlog_tables= {'2011-01-01': [{'Assigned Date': datetime.date(2010, 10, 25), 'Category': 'Customer_claim', 'Date': datetime.date(2010, 10, 22), 'Duplicate Date': None, 'Fixed Reference': None, 'Headline': 'Impovement for all test', 'Identifier': '23269', 'Last Modified': datetime.date(2010, 10, 25), 'Priority': 'Low', 'Project': 'MY_PROJECT', 'Reference': 'MY_PROJECT at 1.7beta2@20101006.0', 'Resolved Date': None, 'Severity': 'improvement', 'State': 'A', 'Submitter': 'Somebody'}, ..... } _backlog_database() compute the tuple backlog_tables , csv_backlog_table: In fact csv_backlog_table is the same as backlog_tables but instead of having the query dictionnaries it holds only the number of query which I use to create a CSV file and a graph over time range. _backlog_database() is as follow: def _backlog_database(table=None, periods=None): """Internal function. Re-arrange database table according to a time period. Only monthly management is computed in this version. @param table the database of the list of defects. Each defect is a dictionnary with fixed keys. @param periods the intervals list of months and the first element is the starting date and the the last element is the ending date in string format. @return (periods_tables, csv_table), a tuple of periodic dictionnary table and the same keys dictionnary with defect numbers associated values. """ if periods is None: raise ValueError('Time interval could not be empty!') periods_tables = {} csv_table = {} interval_table = [] for interval in periods: split_date = interval.split('-') for row in table: if not len(split_date) == 3: limit_date = _first_next_month_day(year=int(split_date[0]), month=int(split_date[1]), day=1) if row['Date'] < limit_date: if not row['Resolved Date']: if row['State'] == 'K': if row['Last Modified'] >= limit_date: interval_table.append(row) elif row['State'] == 'D': if row['Duplicate Date'] >= limit_date: interval_table.append(row) # New, Assigned, Opened, Postponed, Forwarded, cases. else: interval_table.append(row) else: if row['Resolved Date'] >= limit_date: interval_table.append(row) periods_tables[interval] = interval_table csv_table[interval] = str(len(interval_table)) interval_table = [] return periods_tables, csv_table This is not the whole function I reduce it on normal case but it shows what I am doing. In fact I choose to have both dictionnaries to debug my function and analyse what's going on. When everything will be fine I will need only the csv table (with number per period) to create the graphs. That's why I was asking for length computing. Honnestly, the actual queries number is 500 (bug id) but It could be more in other project. I was ambitious when I sais 1000 to 100000 dictionnaries elements but for the whole list of products we have internally It could be 50000. Regards Karim > >> >> Karim >> _______________________________________________ >> 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 From tsartsaris at gmail.com Fri Apr 1 21:49:00 2011 From: tsartsaris at gmail.com (Sotiris Tsartsaris) Date: Fri, 1 Apr 2011 22:49:00 +0300 Subject: [Tutor] PyVISA In-Reply-To: References: <70adf37c-d18a-404b-8127-6c870508d196@a17g2000yqn.googlegroups.com> <002501cbf090$9f9a7d90$decf78b0$@com> Message-ID: 2011/4/1 Alan Gauld > > "Mark R Rivet" wrote > > > Well I tried the setup file and here is what I get: >> C:\Users\Rivetmr\PyVisa_1.3\PyVISA-1.3>Python setup.py install >> Traceback (most recent call last): >> File "setup.py", line 60, in >> home_dir = os.environ['HOME'] >> > > Windows doesn't by default define a HOME environment variable. > Are you sure your module is not Unix specific? > IDLE 1.2 >>> import os >>> os.environ '.......... 'HOME': 'C:\\Documents and Settings\\Administrator', ...............} this is not home? I am geting exactly the same error IDLE 1.2 ==== No Subprocess ==== >>> removing 'build' (and everything under it) Traceback (most recent call last): File "C:\Python25\Lib\PyVISA-1.3\setup.py", line 60, in home_dir = os.environ['HOME'] File "C:\Python25\lib\os.py", line 429, in __getitem__ return self.data[key.upper()] KeyError: 'HOME' -- Tsartsaris Sotirios -------------- next part -------------- An HTML attachment was scrubbed... URL: From knacktus at googlemail.com Sat Apr 2 06:38:57 2011 From: knacktus at googlemail.com (Knacktus) Date: Sat, 02 Apr 2011 06:38:57 +0200 Subject: [Tutor] Meta language and code generation In-Reply-To: <4D961FD0.1000000@free.fr> References: <4D9606AC.3020909@free.fr> <4D961975.7070102@googlemail.com> <4D961FD0.1000000@free.fr> Message-ID: <4D96A861.7000302@googlemail.com> Am 01.04.2011 20:56, schrieb Karim: > On 04/01/2011 08:29 PM, Knacktus wrote: >> Am 01.04.2011 19:09, schrieb Karim: >>> >>> Hello All, >>> >>> I would to ask you if somebody has experience or can give direction in a >>> new project I have. >>> I have a meta language description (in xml) from which I should generate >>> code on different >>> languages. In my case, lisp and tcl. >> >> You need to provide more information of your description to get some >> specific hints. The other day a had a xml file containing a business >> object model with hierarchy and relations. Then I wrote a code >> generator to build a module with Python classes for each business >> item. The code generator created properties for lazily resolving >> relations modelled via ids in the database and stuff like that. This >> was very straightforeward using a simple print statements like the >> following: >> >> print "class %s(object):\n" % class_name >> print " def __init__(self, %s)" % constr_arg >> ... >> >> Cheers, >> >> Jan > > > In fact in xml I have something like that: > > A metafunction in fact kind of > > > x > y > > > > I have to generate the call_back_do_stuff_function(x,y) in lisp and tcl > according to a catalog of specs > of what this function must do generically. > > I can do prints for each metafunctio I read but my concern is is there > std libs to help to have good design > and methodology. Is it interesting to use command module of something > like that, is interesting to use > a parser like pylex or pyparsing? I have 50 metafunctions in catalog for > now. > > In fact, my point is to have a great extensive design methodology. > Strategy pattern would suit? > Other patterns? std modules? No ideas about patterns or standarad lib modules from my side, but a short description of how I would do it: Create an abstraction for the catalogue. That's as far as I can see the hardest part. Here you have to decide if and how to split the things your functions have to do into reusable chunks. Then create code generators for these chunks (using print statements). You can name these functions and store the references in dicts like catalog_comp_name_to_tcl_gen. If you get new functions that need new building blocks you can write new generator functions and extend your dictionaries. The generation of your tcl and lisp "functions-frames" should be straigt forward. You need to link the parameters to the building block generator functions you've created before. When you're done with that, you can improve the design step by step. Too me, this approach works better than thinking to much about design in advance, as often you don't see what you really need unless you've started to code. HTH, Jan > > Lots of question here! > > Regards > Karim > > >> >>> >>> Any idea in term of design, examples, links will be appreciated! >>> >>> Kind Regards >>> Karim >>> _______________________________________________ >>> 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 > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From knacktus at googlemail.com Sat Apr 2 07:00:13 2011 From: knacktus at googlemail.com (Knacktus) Date: Sat, 02 Apr 2011 07:00:13 +0200 Subject: [Tutor] counting a list of elements In-Reply-To: <4D962807.5050101@free.fr> References: <4D960887.3030102@free.fr> <4D961C6A.5060509@googlemail.com> <4D962807.5050101@free.fr> Message-ID: <4D96AD5D.9000602@googlemail.com> Am 01.04.2011 21:31, schrieb Karim: > On 04/01/2011 08:41 PM, Knacktus wrote: >> Am 01.04.2011 19:16, schrieb Karim: >>> >>> >>> Hello, >>> >>> I would like to get advice on the best practice to count elements in a >>> list (built from scractch). >>> The number of elements is in the range 1e3 and 1e6. >>> >>> 1) I could create a generator and set a counter (i +=1) in the loop. >>> >>> 2) or simply len(mylist). >>> >>> I don't need the content of the list, indeed, in term of memory I don't >>> want to wast it. But I suppose len() is optimized too (C impementation). >>> >>> If you have some thought to share don't hesitate. >> >> Just a general suggestion: Provide code examples. I know most of the >> times you don't have code examples yet as you're thinking of how to >> solve your problems. But if you post one of the possible solutions the >> experienced guys here will very likely direct you in the proper >> direction. But without code it's hard to understand what you're after. >> >> Cheers, >> >> Jan >> > > Thank you all for you answers to clarified I built a collection of > dictionnaries which represent database query on a bug tracking system: > > backlog_tables , csv_backlog_table = _backlog_database(table=table, > periods=intervals_list) > > backlog_tables is a dictionnary of bug info dictionnaries. The keys of > backlog_tables is a time intervall (YEAR-MONTH) as shown below: > > backlog_tables= {'2011-01-01': [{'Assigned Date': datetime.date(2010, > 10, 25), > 'Category': 'Customer_claim', > 'Date': datetime.date(2010, 10, 22), > 'Duplicate Date': None, > 'Fixed Reference': None, > 'Headline': 'Impovement for all test', > 'Identifier': '23269', > 'Last Modified': datetime.date(2010, 10, 25), > 'Priority': 'Low', > 'Project': 'MY_PROJECT', > 'Reference': 'MY_PROJECT at 1.7beta2@20101006.0', > 'Resolved Date': None, > 'Severity': 'improvement', > 'State': 'A', > 'Submitter': 'Somebody'}, > ..... > } > > _backlog_database() compute the tuple backlog_tables , csv_backlog_table: > In fact csv_backlog_table is the same as backlog_tables but instead of > having > the query dictionnaries it holds only the number of query which I use to > create > a CSV file and a graph over time range. > > _backlog_database() is as follow: > > def _backlog_database(table=None, periods=None): > """Internal function. Re-arrange database table > according to a time period. Only monthly management > is computed in this version. > > @param table the database of the list of defects. Each defect is a > dictionnary with fixed keys. > @param periods the intervals list of months and the first element is the > starting date and the > the last element is the ending date in string format. > @return (periods_tables, csv_table), a tuple of periodic dictionnary > table and > the same keys dictionnary with defect numbers associated values. > """ > if periods is None: > raise ValueError('Time interval could not be empty!') > > periods_tables = {} > csv_table = {} > > interval_table = [] > > for interval in periods: > split_date = interval.split('-') > for row in table: > if not len(split_date) == 3: > limit_date = _first_next_month_day(year=int(split_date[0]), > month=int(split_date[1]), day=1) > if row['Date'] < limit_date: > if not row['Resolved Date']: > if row['State'] == 'K': > if row['Last Modified'] >= limit_date: > interval_table.append(row) > elif row['State'] == 'D': > if row['Duplicate Date'] >= limit_date: > interval_table.append(row) > # New, Assigned, Opened, Postponed, Forwarded, cases. > else: > interval_table.append(row) > else: > if row['Resolved Date'] >= limit_date: > interval_table.append(row) > > periods_tables[interval] = interval_table > csv_table[interval] = str(len(interval_table)) > > interval_table = [] > > return periods_tables, csv_table > > > This is not the whole function I reduce it on normal case but it shows > what I am doing. > In fact I choose to have both dictionnaries to debug my function and > analyse what's going > on. When everything will be fine I will need only the csv table (with > number per period) to create the graphs. > That's why I was asking for length computing. Honnestly, the actual > queries number is 500 (bug id) but It could be more > in other project. I was ambitious when I sais 1000 to 100000 > dictionnaries elements but for the whole > list of products we have internally It could be 50000. I see some similarity with my coding style (doing things "by the way"), which might not be so good ;-). With this background information I would keep the responsibilities seperated. Your _backlog_database() function is supposed to do one thing: Return a dictionary which holds the interval and a list of result dicts. You could call this dict interval_to_result_tables (to indicate that the values are lists). That's all your function should do. Then you want to print a report. This piece of functionality needs to know how long the lists for each dictionary entry are. Then this print_report function should be responsible to get the information it needs by creating it itself or calling another function, which has the purpose to create the information. Latter would be a bit too much, as the length would be simply be: number_of_tables = len(interval_to_result_tables[interval]) I hope I understood your goals correctly and could help a bit, Jan > > Regards > Karim > >> >>> >>> Karim >>> _______________________________________________ >>> 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 > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From contact at jaimegago.com Sat Apr 2 07:10:47 2011 From: contact at jaimegago.com (Jaime Gago) Date: Fri, 1 Apr 2011 22:10:47 -0700 Subject: [Tutor] Finding prime numbers script runs much faster when run via bash shell than idle Message-ID: Hello there, Totally new to python with some *nix scripting knowledge. I wrote a simple piece of code as an exercise to an online -free- class that finds prime numbers. When I run it via IDLE it's taking way more time than if I run it via a (bash) shell (on Os X 10.6) while doing $>python -d mypp.py I'm really curious from a performance perspective as to what could cause such a noticeable difference. Thank you very much! Here is the code ------- #Finding the 1000th Prime number # # ### STATE VARIABLES INITIALIZATION ### tested_number = 3 testing_against = 3 prime_counter = 1 ### Starting the loop ## ### Number of prime numbers we want to find ## while(prime_counter < 1000): ### Testing if there is remainder of the division by the testing_against var while ((tested_number%testing_against != 0) and (testing_against < tested_number)): testing_against=testing_against + 1 if (tested_number != testing_against): x = 1 else: prime_counter = prime_counter + 1 print prime_counter, 'found so far' ## Incrementing the tested number by 2 so we only test odd numbers tested_number = tested_number + 2 ## Reinitialization of the testing_against var to reenter the second loop in the required var state testing_against = 3 ## Printing the prime number print (tested_number - 2), 'is the 1000th prime number' ------ From karim.liateni at free.fr Sat Apr 2 08:08:44 2011 From: karim.liateni at free.fr (Karim) Date: Sat, 02 Apr 2011 08:08:44 +0200 Subject: [Tutor] Meta language and code generation In-Reply-To: <4D96A861.7000302@googlemail.com> References: <4D9606AC.3020909@free.fr> <4D961975.7070102@googlemail.com> <4D961FD0.1000000@free.fr> <4D96A861.7000302@googlemail.com> Message-ID: <4D96BD6C.60500@free.fr> On 04/02/2011 06:38 AM, Knacktus wrote: > Am 01.04.2011 20:56, schrieb Karim: >> On 04/01/2011 08:29 PM, Knacktus wrote: >>> Am 01.04.2011 19:09, schrieb Karim: >>>> >>>> Hello All, >>>> >>>> I would to ask you if somebody has experience or can give direction >>>> in a >>>> new project I have. >>>> I have a meta language description (in xml) from which I should >>>> generate >>>> code on different >>>> languages. In my case, lisp and tcl. >>> >>> You need to provide more information of your description to get some >>> specific hints. The other day a had a xml file containing a business >>> object model with hierarchy and relations. Then I wrote a code >>> generator to build a module with Python classes for each business >>> item. The code generator created properties for lazily resolving >>> relations modelled via ids in the database and stuff like that. This >>> was very straightforeward using a simple print statements like the >>> following: >>> >>> print "class %s(object):\n" % class_name >>> print " def __init__(self, %s)" % constr_arg >>> ... >>> >>> Cheers, >>> >>> Jan >> >> >> In fact in xml I have something like that: >> >> A metafunction in fact kind of >> >> >> x >> y >> >> >> >> I have to generate the call_back_do_stuff_function(x,y) in lisp and tcl >> according to a catalog of specs >> of what this function must do generically. >> >> I can do prints for each metafunctio I read but my concern is is there >> std libs to help to have good design >> and methodology. Is it interesting to use command module of something >> like that, is interesting to use >> a parser like pylex or pyparsing? I have 50 metafunctions in catalog for >> now. >> >> In fact, my point is to have a great extensive design methodology. >> Strategy pattern would suit? >> Other patterns? std modules? > > > No ideas about patterns or standarad lib modules from my side, but a > short description of how I would do it: > > Create an abstraction for the catalogue. That's as far as I can see > the hardest part. Here you have to decide if and how to split the > things your functions have to do into reusable chunks. Then create > code generators for these chunks (using print statements). You can > name these functions and store the references in dicts like > catalog_comp_name_to_tcl_gen. If you get new functions that need new > building blocks you can write new generator functions and extend your > dictionaries. > > The generation of your tcl and lisp "functions-frames" should be > straigt forward. You need to link the parameters to the building block > generator functions you've created before. > > When you're done with that, you can improve the design step by step. > Too me, this approach works better than thinking to much about design > in advance, as often you don't see what you really need unless you've > started to code. > > HTH, > > Jan > Thank you very much Jan! I have a direction. I see the the light now ;o). Karim > > >> >> Lots of question here! >> >> Regards >> Karim >> >> >>> >>>> >>>> Any idea in term of design, examples, links will be appreciated! >>>> >>>> Kind Regards >>>> Karim >>>> _______________________________________________ >>>> 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 >> >> _______________________________________________ >> 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 From karim.liateni at free.fr Sat Apr 2 08:30:20 2011 From: karim.liateni at free.fr (Karim) Date: Sat, 02 Apr 2011 08:30:20 +0200 Subject: [Tutor] counting a list of elements In-Reply-To: <4D96AD5D.9000602@googlemail.com> References: <4D960887.3030102@free.fr> <4D961C6A.5060509@googlemail.com> <4D962807.5050101@free.fr> <4D96AD5D.9000602@googlemail.com> Message-ID: <4D96C27C.2090005@free.fr> On 04/02/2011 07:00 AM, Knacktus wrote: > Am 01.04.2011 21:31, schrieb Karim: >> On 04/01/2011 08:41 PM, Knacktus wrote: >>> Am 01.04.2011 19:16, schrieb Karim: >>>> >>>> >>>> Hello, >>>> >>>> I would like to get advice on the best practice to count elements in a >>>> list (built from scractch). >>>> The number of elements is in the range 1e3 and 1e6. >>>> >>>> 1) I could create a generator and set a counter (i +=1) in the loop. >>>> >>>> 2) or simply len(mylist). >>>> >>>> I don't need the content of the list, indeed, in term of memory I >>>> don't >>>> want to wast it. But I suppose len() is optimized too (C >>>> impementation). >>>> >>>> If you have some thought to share don't hesitate. >>> >>> Just a general suggestion: Provide code examples. I know most of the >>> times you don't have code examples yet as you're thinking of how to >>> solve your problems. But if you post one of the possible solutions the >>> experienced guys here will very likely direct you in the proper >>> direction. But without code it's hard to understand what you're after. >>> >>> Cheers, >>> >>> Jan >>> >> >> Thank you all for you answers to clarified I built a collection of >> dictionnaries which represent database query on a bug tracking system: >> >> backlog_tables , csv_backlog_table = _backlog_database(table=table, >> periods=intervals_list) >> >> backlog_tables is a dictionnary of bug info dictionnaries. The keys of >> backlog_tables is a time intervall (YEAR-MONTH) as shown below: >> >> backlog_tables= {'2011-01-01': [{'Assigned Date': datetime.date(2010, >> 10, 25), >> 'Category': 'Customer_claim', >> 'Date': datetime.date(2010, 10, 22), >> 'Duplicate Date': None, >> 'Fixed Reference': None, >> 'Headline': 'Impovement for all test', >> 'Identifier': '23269', >> 'Last Modified': datetime.date(2010, 10, 25), >> 'Priority': 'Low', >> 'Project': 'MY_PROJECT', >> 'Reference': 'MY_PROJECT at 1.7beta2@20101006.0', >> 'Resolved Date': None, >> 'Severity': 'improvement', >> 'State': 'A', >> 'Submitter': 'Somebody'}, >> ..... >> } >> >> _backlog_database() compute the tuple backlog_tables , >> csv_backlog_table: >> In fact csv_backlog_table is the same as backlog_tables but instead of >> having >> the query dictionnaries it holds only the number of query which I use to >> create >> a CSV file and a graph over time range. >> >> _backlog_database() is as follow: >> >> def _backlog_database(table=None, periods=None): >> """Internal function. Re-arrange database table >> according to a time period. Only monthly management >> is computed in this version. >> >> @param table the database of the list of defects. Each defect is a >> dictionnary with fixed keys. >> @param periods the intervals list of months and the first element is the >> starting date and the >> the last element is the ending date in string format. >> @return (periods_tables, csv_table), a tuple of periodic dictionnary >> table and >> the same keys dictionnary with defect numbers associated values. >> """ >> if periods is None: >> raise ValueError('Time interval could not be empty!') >> >> periods_tables = {} >> csv_table = {} >> >> interval_table = [] >> >> for interval in periods: >> split_date = interval.split('-') >> for row in table: >> if not len(split_date) == 3: >> limit_date = _first_next_month_day(year=int(split_date[0]), >> month=int(split_date[1]), day=1) >> if row['Date'] < limit_date: >> if not row['Resolved Date']: >> if row['State'] == 'K': >> if row['Last Modified'] >= limit_date: >> interval_table.append(row) >> elif row['State'] == 'D': >> if row['Duplicate Date'] >= limit_date: >> interval_table.append(row) >> # New, Assigned, Opened, Postponed, Forwarded, cases. >> else: >> interval_table.append(row) >> else: >> if row['Resolved Date'] >= limit_date: >> interval_table.append(row) >> >> periods_tables[interval] = interval_table >> csv_table[interval] = str(len(interval_table)) >> >> interval_table = [] >> >> return periods_tables, csv_table >> >> >> This is not the whole function I reduce it on normal case but it shows >> what I am doing. >> In fact I choose to have both dictionnaries to debug my function and >> analyse what's going >> on. When everything will be fine I will need only the csv table (with >> number per period) to create the graphs. >> That's why I was asking for length computing. Honnestly, the actual >> queries number is 500 (bug id) but It could be more >> in other project. I was ambitious when I sais 1000 to 100000 >> dictionnaries elements but for the whole >> list of products we have internally It could be 50000. > > I see some similarity with my coding style (doing things "by the > way"), which might not be so good ;-). > > With this background information I would keep the responsibilities > seperated. Your _backlog_database() function is supposed to do one > thing: Return a dictionary which holds the interval and a list of > result dicts. You could call this dict interval_to_result_tables (to > indicate that the values are lists). That's all your function should do. > > Then you want to print a report. This piece of functionality needs to > know how long the lists for each dictionary entry are. Then this > print_report function should be responsible to get the information it > needs by creating it itself or calling another function, which has the > purpose to create the information. Latter would be a bit too much, as > the length would be simply be: > > number_of_tables = len(interval_to_result_tables[interval]) > > I hope I understood your goals correctly and could help a bit, > > Jan > One more time thank you Jan! It 's true I coded it very fast and I forget about design... With your answer it opens my mind about separate tasks distinctively. My concern when doing this was compute the length during creation of lists, dicts or after to optimize memory and time. But it ended due to time constraint (demo to do) I coded it coarse like a brute ;o) Regards Karim > > > >> >> Regards >> Karim >> >>> >>>> >>>> Karim >>>> _______________________________________________ >>>> 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 >> >> _______________________________________________ >> 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 From karim.liateni at free.fr Sat Apr 2 08:50:30 2011 From: karim.liateni at free.fr (Karim) Date: Sat, 02 Apr 2011 08:50:30 +0200 Subject: [Tutor] Finding prime numbers script runs much faster when run via bash shell than idle In-Reply-To: References: Message-ID: <4D96C736.5040905@free.fr> On 04/02/2011 07:10 AM, Jaime Gago wrote: > Hello there, > Totally new to python with some *nix scripting knowledge. > > I wrote a simple piece of code as an exercise to an online -free- class that finds prime numbers. When I run it via IDLE it's taking way more time than if I run it via a (bash) shell (on Os X 10.6) while doing $>python -d mypp.py > > I'm really curious from a performance perspective as to what could cause such a noticeable difference. > > Thank you very much! > > Here is the code > > ------- > #Finding the 1000th Prime number > # > # > ### STATE VARIABLES INITIALIZATION ### > > tested_number = 3 > testing_against = 3 > prime_counter = 1 > > ### Starting the loop ## > > ### Number of prime numbers we want to find ## > while(prime_counter< 1000): > ### Testing if there is remainder of the division by the testing_against var > while ((tested_number%testing_against != 0) and (testing_against< tested_number)): > testing_against=testing_against + 1 > if (tested_number != testing_against): > x = 1 > else: > prime_counter = prime_counter + 1 > print prime_counter, 'found so far' > ## Incrementing the tested number by 2 so we only test odd numbers > tested_number = tested_number + 2 > ## Reinitialization of the testing_against var to reenter the second loop in the required var state > testing_against = 3 > ## Printing the prime number > print (tested_number - 2), 'is the 1000th prime number' > ------ > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Just a advice for readibility: testing_against += 1 prime_counter = prime_counter + 1 instead of: testing_against=testing_against + 1 prime_counter += 1 And IDLE add a layer due to the interactive feature to display result. It is python interpreter plus Tk layer. Just a thought nothing truly precise. Regards Karim From karim.liateni at free.fr Sat Apr 2 08:50:47 2011 From: karim.liateni at free.fr (Karim) Date: Sat, 02 Apr 2011 08:50:47 +0200 Subject: [Tutor] Finding prime numbers script runs much faster when run via bash shell than idle In-Reply-To: References: Message-ID: <4D96C747.2080508@free.fr> On 04/02/2011 07:10 AM, Jaime Gago wrote: > Hello there, > Totally new to python with some *nix scripting knowledge. > > I wrote a simple piece of code as an exercise to an online -free- class that finds prime numbers. When I run it via IDLE it's taking way more time than if I run it via a (bash) shell (on Os X 10.6) while doing $>python -d mypp.py > > I'm really curious from a performance perspective as to what could cause such a noticeable difference. > > Thank you very much! > > Here is the code > > ------- > #Finding the 1000th Prime number > # > # > ### STATE VARIABLES INITIALIZATION ### > > tested_number = 3 > testing_against = 3 > prime_counter = 1 > > ### Starting the loop ## > > ### Number of prime numbers we want to find ## > while(prime_counter< 1000): > ### Testing if there is remainder of the division by the testing_against var > while ((tested_number%testing_against != 0) and (testing_against< tested_number)): > testing_against=testing_against + 1 > if (tested_number != testing_against): > x = 1 > else: > prime_counter = prime_counter + 1 > print prime_counter, 'found so far' > ## Incrementing the tested number by 2 so we only test odd numbers > tested_number = tested_number + 2 > ## Reinitialization of the testing_against var to reenter the second loop in the required var state > testing_against = 3 > ## Printing the prime number > print (tested_number - 2), 'is the 1000th prime number' > ------ > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Just a advice for readibility: testing_against += 1 prime_counter = prime_counter + 1 instead of: testing_against=testing_against + 1 prime_counter += 1 And IDLE adds a layer due to the interactive feature to display result. It is python interpreter plus Tk layer. Just a thought nothing truly precise. Regards Karim From __peter__ at web.de Sat Apr 2 09:04:46 2011 From: __peter__ at web.de (Peter Otten) Date: Sat, 02 Apr 2011 09:04:46 +0200 Subject: [Tutor] Finding prime numbers script runs much faster when run via bash shell than idle References: Message-ID: Jaime Gago wrote: > I wrote a simple piece of code as an exercise to an online -free- class > that finds prime numbers. When I run it via IDLE it's taking way more time > than if I run it via a (bash) shell (on Os X 10.6) while doing $>python -d > mypp.py > > I'm really curious from a performance perspective as to what could cause > such a noticeable difference. Displaying text in Idle's Python Shell window has significant overhead If you remove the line > print prime_counter, 'found so far' from your script it should take roughly the same time to run via bash and in Idle. From alan.gauld at btinternet.com Sat Apr 2 10:05:14 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 2 Apr 2011 09:05:14 +0100 Subject: [Tutor] Finding prime numbers script runs much faster when run viabash shell than idle References: Message-ID: "Jaime Gago" wrote > When I run it via IDLE it's taking way more time than > if I run it via a (bash) shell (on Os X 10.6) while > doing $>python -d mypp.py > > I'm really curious from a performance perspective > as to what could cause such a noticeable difference. IDLE is a development environment. As such it adds lots of extra hooks and debugging things to the execution environment. (For example it traps things like Ctrl C) In addition, being a GUI written in Tkinter, it has a slower output mechanism so print statements will be slower. IDLE is not intended to be used to run code except during development, it has ot been built for speed but for debugging. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From danielramso_12 at hotmail.com Sat Apr 2 18:19:02 2011 From: danielramso_12 at hotmail.com (=?iso-8859-1?B?SVNBQUMgUmFt7XJleiBTb2xhbm8=?=) Date: Sat, 2 Apr 2011 10:19:02 -0600 Subject: [Tutor] HELP Message-ID: Hi... My name is Isaac, I need some help to programm in python, I know some things that are really basic like lists and recursivity and with that we shoul create an GPS with a global variable, but what I'm trying to do is to make a function that could call the global variable can I do something like that... or maybe a function like this: def function(Word): Word = Word Word= [Word] print (Word) and the problem is that if I ejecute that in the shell later I'm not able to call >>> Word because it returns me an error!!! THANKS 4 THE HELP -------------- next part -------------- An HTML attachment was scrubbed... URL: From danielramso_12 at hotmail.com Sat Apr 2 18:24:11 2011 From: danielramso_12 at hotmail.com (=?iso-8859-1?B?SVNBQUMgUmFt7XJleiBTb2xhbm8=?=) Date: Sat, 2 Apr 2011 10:24:11 -0600 Subject: [Tutor] FW: HELP In-Reply-To: References: Message-ID: Hi... My name is Isaac, I need some help to programm in python, I know some things that are really basic like lists and recursivity and with that we shoul create an GPS with a global variable, but what I'm trying to do is to make a function that could call the global variable can I do something like that... or maybe a function like this: def function(Word): Word = Word Word= [Word] print (Word) and the problem is that if I ejecute that in the shell later I'm not able to call >>> Word because it returns me an error!!! THANKS 4 THE HELP -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Sat Apr 2 18:36:44 2011 From: wprins at gmail.com (Walter Prins) Date: Sat, 2 Apr 2011 17:36:44 +0100 Subject: [Tutor] HELP In-Reply-To: References: Message-ID: 2011/4/2 ISAAC Ram?rez Solano > > Hi... My name is Isaac, I need some help to programm in python, I know some > things that are really basic like lists and recursivity and with that we > shoul create an GPS with a global variable, but what I'm trying to do is to > make a function that could call the global variable > > Read this page: http://www.saltycrane.com/blog/2008/01/python-variable-scope-notes/ Then come back if you have further questions. Regards Walter. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Apr 2 19:55:23 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 2 Apr 2011 18:55:23 +0100 Subject: [Tutor] HELP References: Message-ID: "ISAAC Ram?rez Solano" wrote > Hi... My name is Isaac, I need some help to program in python, > I know some things that are really basic like lists and recursivity I'm not sure what you mean by recursivity, but I'm betting its not what I mean by that term! :-) > with that we should create an GPS with a global variable, I'm also not sure what you mean by GPS - to me that means Global Positioning Satellite but I suspect you mean something different? > what I'm trying to do is to make a function that could call > the global variable can I do something like that... Yes and any Python tutorial will explain how. You can try the Modules and Functions topic in my tutorial if you are not already reading another one. [ If your first language is Spanish or Portuguese you may prefer the translations in those languages better. (But they are only available for Python v2) ] > def function(Word): Word = Word Word= [Word] print (Word) Thats not legal python, it may just be a formatting error. Lets assume so, it would then look like: def function(Word): Word = Word Word= [Word] print (Word) That creates a list containing the parameter passed in and then prints it. It then throws it away. > if I execute that in the shell later I'm not able to call >>> Word because it returns me an error!!! That would depend on whether you created Word before you called the function. I suspect you are confused about Python variables, Python scope, and Python functions. Read about those topics and then come back with any further questions. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From contact at jaimegago.com Sat Apr 2 20:17:54 2011 From: contact at jaimegago.com (Jaime Gago) Date: Sat, 2 Apr 2011 11:17:54 -0700 Subject: [Tutor] Finding prime numbers script runs much faster when run viabash shell than idle In-Reply-To: References: Message-ID: Ok I understand now, thank you very much! On Apr 2, 2011, at 1:05 AM, Alan Gauld wrote: > "Jaime Gago" wrote >> When I run it via IDLE it's taking way more time than if I run it via a (bash) shell (on Os X 10.6) while doing $>python -d mypp.py >> I'm really curious from a performance perspective as to what could cause such a noticeable difference. > > IDLE is a development environment. As such it adds lots of extra hooks and debugging things to the execution environment. (For example it traps things like Ctrl C) In addition, being a GUI written in Tkinter, it has a slower output mechanism > so print statements will be slower. > > IDLE is not intended to be used to run code except during development, it has ot been built for speed but for debugging. > > HTH, > > -- > Alan Gauld > 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 mat.korycinski at gmail.com Sun Apr 3 00:17:55 2011 From: mat.korycinski at gmail.com (=?ISO-8859-2?Q?Mateusz_Koryci=F1ski?=) Date: Sun, 3 Apr 2011 00:17:55 +0200 Subject: [Tutor] 'for' iteration stop problem Message-ID: Hi, My problem is simple for sure, but unfortunately I'm a bit beginner and I've stucked in it. I hope it is not a problem since as I understand this mailing list is for beginners. I have some problem with 'for' loop in algorithm. Code and description for this problem could be find here: http://stackoverflow.com/questions/5520145/how-to-stop-iteration-when-if-statement-is-true I will be very thankful! Cheers, Mateusz -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Apr 3 00:45:49 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 2 Apr 2011 23:45:49 +0100 Subject: [Tutor] 'for' iteration stop problem References: Message-ID: "Mateusz Korycinski" wrote > My problem is simple for sure, but unfortunately I'm a bit beginner > and I've > stucked in it. I hope it is not a problem since as I understand this > mailing > list is for beginners. No problem, we try to answer questions such as this here. > I have some problem with 'for' loop in algorithm. > Code and description for this problem could be find here: > http://stackoverflow.com/questions/5520145/how-to-stop-iteration-when-if-statement-is-true There are several ways to get out of a loop, the most common are: a) To exit a single level of loop use break for n in range(500): if n == 200: break else; pass b) To break out of a set of nested loops such as you have then use break combined with a sentinal and check the sentinal at each level: exitLoop = False for x in range(20): if exitLoop : break for y in range(50): if exitLoop: break for z in range(500): if z == 200: exitLoop = True break c) Use an exception: class ExitLoopException(Exception): pass try: for x in range(20): for y in range(50): for z in range(500): if z == 200: raise ExitLoopException except ExitLoopException: pass There are other ways but those should cover most eventualities. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From waynejwerner at gmail.com Sun Apr 3 01:38:12 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Sat, 2 Apr 2011 18:38:12 -0500 Subject: [Tutor] 'for' iteration stop problem In-Reply-To: References: Message-ID: On Sat, Apr 2, 2011 at 5:45 PM, Alan Gauld wrote: > > There are other ways but those should cover most eventualities. I find that my preferred way when the loops are nested is to move the loops into a function and then return: def do_something(collection, collection2): for x in collection: for y in collection 2: if someCase(x,y): return It seems (at least to me) a little nicer than sentinel values or throwing an exception. Just my $.02 -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sun Apr 3 02:59:08 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 03 Apr 2011 10:59:08 +1000 Subject: [Tutor] 'for' iteration stop problem In-Reply-To: References: Message-ID: <4D97C65C.6070002@pearwood.info> Mateusz Koryci?ski wrote: > I have some problem with 'for' loop in algorithm. > Code and description for this problem could be find here: > http://stackoverflow.com/questions/5520145/how-to-stop-iteration-when-if-statement-is-true Other people have answered your question about exiting nested loops, but that's not your real problem. Your real problem is that the piece of code shown is unreadable and unmaintainable! (1) Python has functions: please use them to break your code into small, easily understandable pieces. (2) You have a *mess* of unreadable variable names. You have: w.steps w.x w.y w.world data.c data.n data.e data.s data.w data.cc (yes, you have data.c AND data.cc!!!) plus loop variables z i j and r, and z is never used! How is anyone supposed to understand what this does? Even if you solve this problem *today*, in a week you will have forgotten what the code does and you won't understand it. (3) w.steps is never used except to needlessly(?) repeat the same calculations over and over again. (4) w.x and w.y at least seem to be fairly obvious, although the names are terrible. (5) What are w.world and all the data.* variables? Are they "north", "south", "east", "west"? (6) You give an example of some output, but you don't show the *input* that is used to generate that data, so it is meaningless. (7) You seem to be re-writing the data in place. That's *usually* a mistake (not always, but, say, 95% of the time). It will help if you can describe what problem you are trying to solve. Not the algorithm you have already chosen, but the actual problem -- what to you hope to do? There is probably a much better way. But for now, let me see if I can help refactor the code. You have: for z in range(w.steps): for i in range(1,w.x-1): for j in range(1,w.y-1): print (i, j) for r in data.c: if w.world[i][j] in r: print r ind = data.c.index(r) print ind if w.world[i-1][j] in data.n[ind]: if w.world[i][j+1] in data.e[ind]: if w.world[i+1][j] in data.s[ind]: if w.world[i][j-1] in data.w[ind]: w.world[i][j] = data.cc[ind] * make it a function that takes meaningfully named arguments, not just global variables; * throw away the top level loop, because z never gets used -- you're just needlessly repeating the same calculation w.steps times; * use helper functions to make your code more readable and to allow for future changes to the data structure; * comment your code! def get_neighbours(data, i, j): """Return the four nearest neighbours of data[i,j]. Returns the north, south, east, west neighbours in that order: [ [ ............. ] [ ... . n . ... ] [ ... w X e ... ] [ ... . s . ... ] [ ............. ] ] """ return data[i-1][j], data[i+1][j], data[i][j+1], data[i][j-1] def match_item(item, values): """Given a list of lists "values", match item against the items in the sublists, returning the index of the first matching value found. ("values" is a terrible name, but since I don't know what the problem you are solving is, I can't give it a more meaningful name.) >>> match_item(42, [[1, 2, 3], [11, 23, 37, 42, 55], [100, 200]]) (1, 3) """ for i, sublist in enumerate(values): if item in sublist: return (i, sublist.index(item)) # If we never match at all, it is an error. raise ValueError('item not in values') def iterate_data(data, values, north, south, east, west): """Iterate over data, doing something to it, I don't know what. data is a 2D array of numbers. values is a list of lists. I don't know why. north, south, east, west are four lists of numbers. They must all have the same number of items. """ assert len(north) == len(south) == len(east) == len(west) directions = (north, south, east, west) # Sorry, that is a poor, undescriptive name. # Skip the first and last row and column. for i in range(1, num_rows-1): for j in range(1, num_cols-1): cell = data[i][j] # Find a match with values (whatever that is!) x,y = match_item(cell, values) # Now compare that cell's neighbours. neighbours = get_neighbours(data, i, j) if any(a in b[y] for (a,b) in zip(neighbours, directions)): print "Matched neighbour (now what?)" I hope this helps. -- Steven From mat.korycinski at gmail.com Sun Apr 3 12:47:51 2011 From: mat.korycinski at gmail.com (=?ISO-8859-2?Q?Mateusz_Koryci=F1ski?=) Date: Sun, 3 Apr 2011 12:47:51 +0200 Subject: [Tutor] Tutor Digest, Vol 86, Issue 12 In-Reply-To: References: Message-ID: Hi, Thanks for all yout responses! I will answer below each one (I hope it wouldn't be a problem). > > > Message: 1 > Date: Sat, 2 Apr 2011 23:45:49 +0100 > From: "Alan Gauld" > To: tutor at python.org > Subject: Re: [Tutor] 'for' iteration stop problem > Message-ID: > Content-Type: text/plain; format=flowed; charset="iso-8859-1"; > reply-type=original > > > "Mateusz Korycinski" wrote > > > My problem is simple for sure, but unfortunately I'm a bit beginner > > and I've > > stucked in it. I hope it is not a problem since as I understand this > > mailing > > list is for beginners. > > No problem, we try to answer questions such as this here. > > > I have some problem with 'for' loop in algorithm. > > Code and description for this problem could be find here: > > > http://stackoverflow.com/questions/5520145/how-to-stop-iteration-when-if-statement-is-true > > There are several ways to get out of a loop, the most common are: > > a) To exit a single level of loop use break > > > for n in range(500): > if n == 200: break > else; pass > > b) To break out of a set of nested loops such as you have then > use break combined with a sentinal and check the sentinal at > each level: > > exitLoop = False > for x in range(20): > if exitLoop : break > for y in range(50): > if exitLoop: break > for z in range(500): > if z == 200: > exitLoop = True > break > > c) Use an exception: > > class ExitLoopException(Exception): pass > > try: > for x in range(20): > for y in range(50): > for z in range(500): > if z == 200: > raise ExitLoopException > except ExitLoopException: pass > > > There are other ways but those should cover most eventualities. > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > > Thanks for advices, I will try to use it that way, but first I must test it on small examples to get better know how it is working. > > ------------------------------ > > Message: 2 > Date: Sat, 2 Apr 2011 18:38:12 -0500 > From: Wayne Werner > To: Alan Gauld > Cc: tutor at python.org > Subject: Re: [Tutor] 'for' iteration stop problem > Message-ID: > > Content-Type: text/plain; charset="iso-8859-1" > > On Sat, Apr 2, 2011 at 5:45 PM, Alan Gauld >wrote: > > > > > There are other ways but those should cover most eventualities. > > > I find that my preferred way when the loops are nested is to move the loops > into a function and then return: > > def do_something(collection, collection2): > for x in collection: > for y in collection 2: > if someCase(x,y): > return > > It seems (at least to me) a little nicer than sentinel values or throwing > an > exception. > > Just my $.02 > -Wayne > I've tried it that way, but I haven't succed. Perhaps I'm doing sth wrong, I will check one more time. Hi, I will answer your questions below ech one. > Message: 3 > Date: Sun, 03 Apr 2011 10:59:08 +1000 > From: Steven D'Aprano > To: tutor at python.org > Subject: Re: [Tutor] 'for' iteration stop problem > Message-ID: <4D97C65C.6070002 at pearwood.info> > Content-Type: text/plain; charset=UTF-8; format=flowed > > Mateusz Koryci?ski wrote: > > I have some problem with 'for' loop in algorithm. > > Code and description for this problem could be find here: > > > http://stackoverflow.com/questions/5520145/how-to-stop-iteration-when-if-statement-is-true > > Other people have answered your question about exiting nested loops, but > that's not your real problem. Your real problem is that the piece of > code shown is unreadable and unmaintainable! > > (1) Python has functions: please use them to break your code into small, > easily understandable pieces. > > (2) You have a *mess* of unreadable variable names. You have: > > w.steps w.x w.y w.world data.c data.n data.e data.s data.w data.cc > > (yes, you have data.c AND data.cc!!!) plus loop variables z i j and r, > and z is never used! How is anyone supposed to understand what this > does? Even if you solve this problem *today*, in a week you will have > forgotten what the code does and you won't understand it. > > It's an objects from another classes. Variable z is used because there is a need to provide number of steps to execute by user. Variable c mean central cell in array whe are considering right now, other one is neighbours but cc, cc means new state (couse basing on central cell and its neighbors we want to change value to cc). > (3) w.steps is never used except to needlessly(?) repeat the same > calculations over and over again. > Described above. > (4) w.x and w.y at least seem to be fairly obvious, although the names > are terrible. > x - row numbers provided by user and in other class, which creates array (from NumPy). y - the same but cols > > (5) What are w.world and all the data.* variables? Are they "north", > "south", "east", "west"? > w.World is a NumPy 2D array, c is central cell, next four is neighbours, 'cc' is value which we want to place in array instead of 'c'. > > (6) You give an example of some output, but you don't show the *input* > that is used to generate that data, so it is meaningless. > The input is 2D array, and list of rules, where each rule looks like this: [ [ [2] [3] [4,5] [6] [7] [8] ] [ [9] [13] [14,15] [16] [17,19] [18] ] ] >From this I'm creating separate lists for each position so for example: data.c = [ [2],[9] ] data.e = [ [4,5],[14,15] ] > > (7) You seem to be re-writing the data in place. That's *usually* a > mistake (not always, but, say, 95% of the time). > > It will help if you can describe what problem you are trying to solve. > Not the algorithm you have already chosen, but the actual problem -- > what to you hope to do? There is probably a much better way. > The problem is self-replicating loop - Perrier's Loop (Langton's Loop modification). It has a rule list, which is parsed from file by function obtained from Golly's source code (GPL License). As a parsing result I have sth like described above, where the order is: C1,N,E,S,W,C2 C1 - present cell state (int) N - north neigbour E - east neigbour S - south neigbour W - west neigbour C2 - state value to change So result of this algorithm should be changing value from central cell (C1) into new value (C2), but only if central cell state is equal to 1st value from rule and neighbours values are equal to relevant values from rule list. The format description could be find here: http://code.google.com/p/ruletablerepository/wiki/TheFormat > > But for now, let me see if I can help refactor the code. You have: > > for z in range(w.steps): > for i in range(1,w.x-1): > for j in range(1,w.y-1): > print (i, j) > for r in data.c: > if w.world[i][j] in r: > print r > ind = data.c.index(r) > print ind > if w.world[i-1][j] in data.n[ind]: > if w.world[i][j+1] in data.e[ind]: > if w.world[i+1][j] in data.s[ind]: > if w.world[i][j-1] in data.w[ind]: > w.world[i][j] = data.cc[ind] > > > > * make it a function that takes meaningfully named arguments, not just > global variables; > > * throw away the top level loop, because z never gets used -- you're > just needlessly repeating the same calculation w.steps times; > > * use helper functions to make your code more readable and to allow for > future changes to the data structure; > > * comment your code! > > > > def get_neighbours(data, i, j): > """Return the four nearest neighbours of data[i,j]. > Returns the north, south, east, west neighbours in that order: > > [ [ ............. ] > [ ... . n . ... ] > [ ... w X e ... ] > [ ... . s . ... ] > [ ............. ] ] > > """ > return data[i-1][j], data[i+1][j], data[i][j+1], data[i][j-1] > > > > def match_item(item, values): > """Given a list of lists "values", match item against the items > in the sublists, returning the index of the first matching value > found. > > ("values" is a terrible name, but since I don't know what the > problem you are solving is, I can't give it a more meaningful > name.) > > >>> match_item(42, [[1, 2, 3], [11, 23, 37, 42, 55], [100, 200]]) > (1, 3) > > """ > for i, sublist in enumerate(values): > if item in sublist: > return (i, sublist.index(item)) > # If we never match at all, it is an error. > raise ValueError('item not in values') > > > > def iterate_data(data, values, north, south, east, west): > """Iterate over data, doing something to it, I don't know what. > > data is a 2D array of numbers. > values is a list of lists. I don't know why. > north, south, east, west are four lists of numbers. They must > all have the same number of items. > """ > assert len(north) == len(south) == len(east) == len(west) > directions = (north, south, east, west) > # Sorry, that is a poor, undescriptive name. > > # Skip the first and last row and column. > for i in range(1, num_rows-1): > for j in range(1, num_cols-1): > cell = data[i][j] > # Find a match with values (whatever that is!) > x,y = match_item(cell, values) > # Now compare that cell's neighbours. > neighbours = get_neighbours(data, i, j) > if any(a in b[y] for (a,b) in zip(neighbours, directions)): > print "Matched neighbour (now what?)" > > > > > I hope this helps. > > > > > -- > Steven > > I hope that answer is good enough. ;) Cheers, Mateusz -------------- next part -------------- An HTML attachment was scrubbed... URL: From andres at chandia.net Sun Apr 3 14:17:21 2011 From: andres at chandia.net (=?iso-8859-1?Q?=22Andr=E9s_Chand=EDa=22?=) Date: Sun, 3 Apr 2011 14:17:21 +0200 Subject: [Tutor] Regex question In-Reply-To: <4D934BDD.6020404@alchemy.com> References: <9f91f88168c63ea117a66e3717b9f734.squirrel@mail.chandia.net> <4D934BDD.6020404@alchemy.com> Message-ID: I continue working with RegExp, but I have reached a point for wich I can't find documentation, maybe there is no possible way to do it, any way I throw the question: This is my code: ??? contents = re.sub(r'?', "A", contents) ??? contents = re.sub(r'?', "a", contents) ??? contents = re.sub(r'?', "E", contents) ??? contents = re.sub(r'?', "e", contents) ??? contents = re.sub(r'?', "I", contents) ??? contents = re.sub(r'?', "i", contents) ??? contents = re.sub(r'?', "O", contents) ??? contents = re.sub(r'?', "o", contents) ??? contents = re.sub(r'?', "U", contents) ??? contents = re.sub(r'?', "u", contents) It is clear that I need to convert any accented vowel into the same not accented vowel, The qestion is : is there a way to say that whenever you find an accented character this one has to change into a non accented character, but not every character, it must be only this vowels and accented this way, because at the language I am working with, there are letters like ?, and ? that should remain the same. thanks you all. _______________________ ????????????andr?s chand?a P No imprima innecesariamente. ?Cuide el medio ambiente! From hugo.yoshi at gmail.com Sun Apr 3 15:03:30 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Sun, 3 Apr 2011 15:03:30 +0200 Subject: [Tutor] Regex question In-Reply-To: References: <9f91f88168c63ea117a66e3717b9f734.squirrel@mail.chandia.net> <4D934BDD.6020404@alchemy.com> Message-ID: 2011/4/3 "Andr?s Chand?a" : > > > I continue working with RegExp, but I have reached a point for wich I can't find > documentation, maybe there is no possible way to do it, any way I throw the question: > > This is my code: > > ??? contents = re.sub(r'?', > "A", contents) > ??? contents = re.sub(r'?', "a", > contents) > ??? contents = re.sub(r'?', "E", contents) > ??? contents = re.sub(r'?', "e", contents) > ??? contents = re.sub(r'?', "I", contents) > ??? contents = re.sub(r'?', "i", contents) > ??? contents = re.sub(r'?', "O", contents) > ??? contents = re.sub(r'?', "o", contents) > ??? contents = re.sub(r'?', "U", contents) > ??? contents = re.sub(r'?', "u", contents) > > It is > clear that I need to convert any accented vowel into the same not accented vowel, > The > qestion is : is there a way to say that whenever you find an accented character this > one > has to change into a non accented character, but not every character, it must be only > this vowels and accented this way, because at the language I am working with, there are > letters > like ?, and ? that should remain the same. > Okay, first thing, forget about regexes for this problem.They're too complicated and not suited to it. Encoding issues make this a somewhat complicated problem. In Unicode, There's two ways to encode most accented characters. For example, the character "?" can be encoded both by U+0106, "LATIN CAPITAL LETTER C WITH ACUTE", and a combination of U+0043 and U+0301, being simply 'C' and the 'COMBINING ACUTE ACCENT', respectively. You must remove both forms to be sure every accented character is gone from your string. using unicode.translate, you can craft a translation table to translate the accented characters to their non-accented counterparts. The combining characters can simply be removed by mapping them to None. HTH, Hugo From ranjand2005 at gmail.com Sun Apr 3 16:14:01 2011 From: ranjand2005 at gmail.com (ranjan das) Date: Sun, 3 Apr 2011 19:44:01 +0530 Subject: [Tutor] sorting based on elements which are nested in a list Message-ID: I have a list which I want to sort based on ('a','b','c') first and then based on (1,2,3) How do i do these using itemgetter() since the list is nested A=[('k3', ['b', 3]), ('k2', ['a', 1]), ('k1', ['a', 3]), ('k4', ['c', 2])] The solution I am looking for is A_sorted=[ ('k2', ['a', 1]), ('k1', ['a', 3]), ('k3', ['b', 3]) ('k4', ['c', 2])] Please suggest Regards, ranjan -- -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Sun Apr 3 16:20:12 2011 From: __peter__ at web.de (Peter Otten) Date: Sun, 03 Apr 2011 16:20:12 +0200 Subject: [Tutor] Regex question References: <9f91f88168c63ea117a66e3717b9f734.squirrel@mail.chandia.net> <4D934BDD.6020404@alchemy.com> Message-ID: Hugo Arts wrote: > 2011/4/3 "Andr?s Chand?a" : >> >> >> I continue working with RegExp, but I have reached a point for wich I >> can't find documentation, maybe there is no possible way to do it, any >> way I throw the question: >> >> This is my code: >> >> contents = re.sub(r'?', >> "A", contents) >> contents = re.sub(r'?', "a", >> contents) >> contents = re.sub(r'?', "E", contents) >> contents = re.sub(r'?', "e", contents) >> contents = re.sub(r'?', "I", contents) >> contents = re.sub(r'?', "i", contents) >> contents = re.sub(r'?', "O", contents) >> contents = re.sub(r'?', "o", contents) >> contents = re.sub(r'?', "U", contents) >> contents = re.sub(r'?', "u", contents) >> >> It is >> clear that I need to convert any accented vowel into the same not >> accented vowel, The >> qestion is : is there a way to say that whenever you find an accented >> character this one >> has to change into a non accented character, but not every character, it >> must be only this vowels and accented this way, because at the language I >> am working with, there are letters >> like ?, and ? that should remain the same. >> > > Okay, first thing, forget about regexes for this problem.They're too > complicated and not suited to it. > > Encoding issues make this a somewhat complicated problem. In Unicode, > There's two ways to encode most accented characters. For example, the > character "?" can be encoded both by U+0106, "LATIN CAPITAL LETTER C > WITH ACUTE", and a combination of U+0043 and U+0301, being simply 'C' > and the 'COMBINING ACUTE ACCENT', respectively. You must remove both > forms to be sure every accented character is gone from your string. > > using unicode.translate, you can craft a translation table to > translate the accented characters to their non-accented counterparts. > The combining characters can simply be removed by mapping them to > None. If you go that road you might be interested in Fredrik Lundh's article at http://effbot.org/zone/unicode-convert.htm The class presented there is a bit tricky, but for your purpose it might be sufficient to subclass it: >>> KEEP_CHARS = set(ord(c) for c in u"??") >>> class Map(unaccented_map): ... def __missing__(self, key): ... if key in KEEP_CHARS: ... self[key] = key ... return key ... return unaccented_map.__missing__(self, key) ... >>> print u"???".translate(Map()) ao? From lie.1296 at gmail.com Sun Apr 3 16:55:43 2011 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 04 Apr 2011 00:55:43 +1000 Subject: [Tutor] sorting based on elements which are nested in a list In-Reply-To: References: Message-ID: On 04/04/11 00:14, ranjan das wrote: > > I have a list which I want to sort based on ('a','b','c') first and then > based on (1,2,3) > > How do i do these using itemgetter() since the list is nested > > A=[('k3', ['b', 3]), ('k2', ['a', 1]), ('k1', ['a', 3]), ('k4', ['c', 2])] > > The solution I am looking for is > > A_sorted=[ ('k2', ['a', 1]), ('k1', ['a', 3]), ('k3', ['b', 3]) ('k4', > ['c', 2])] itemgetter() is only a convenience function, you can make your own function, like this: A_sorted = sorted(A, key=lambda i: (i[1][0], i[1][1])) or in your particular case, since list is compared in lexicographical order, this would actually work: A_sorted = sorted(A, key=itemgetter(1)) From markrivet at gsoftcon.com Sun Apr 3 22:40:24 2011 From: markrivet at gsoftcon.com (markrivet at gsoftcon.com) Date: Sun, 3 Apr 2011 16:40:24 -0400 (EDT) Subject: [Tutor] Prologix GPIB to USB converter Message-ID: <1301863224.23037191@192.168.4.58> Hello everyone. Is there any code examples out there to on how to use the prologix GPIB to USB converter? Mark R Rivet, Genesis Software Consulting ASCT(Computer Technologies), BSIT/SE(Software Engineering) Electrical Engineering Technician Member IEEE, Computer Society Do or do not; there is no try. From wprins at gmail.com Sun Apr 3 23:34:39 2011 From: wprins at gmail.com (Walter Prins) Date: Sun, 3 Apr 2011 22:34:39 +0100 Subject: [Tutor] Tutor Digest, Vol 86, Issue 12 In-Reply-To: References: Message-ID: Hello, 2011/4/3 Mateusz Koryci?ski > > (2) You have a *mess* of unreadable variable names. You have: >> >> w.steps w.x w.y w.world data.c data.n data.e data.s data.w data.cc >> >> (yes, you have data.c AND data.cc!!!) plus loop variables z i j and r, >> and z is never used! How is anyone supposed to understand what this >> does? Even if you solve this problem *today*, in a week you will have >> forgotten what the code does and you won't understand it. >> >> > It's an objects from another classes. Variable z is used because there is a > need to provide number of steps to execute by user. Variable c mean central > cell in array whe are considering right now, other one is neighbours but cc, > cc means new state (couse basing on central cell and its neighbors we want > to change value to cc). > I think the point that was being made was that all this (and the other explanations you gave) should be in or circumscribed by your source code, and that you should try to use longer/more meaningful variable names. It wasn't specifically a request for you to explain all of these things here on the email list, although that might be helpful going forward. Nevertheless you still need to make these things part of and as obvious as possible from reading your source code. It should always be the definitive reference. IMHO source which has to be substantially explained outside of itself should be improved/clarified/documented/commented inside the source until external explanations are largely unneccesary and the code is as far as practicable self-documenting. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Apr 3 23:39:14 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 3 Apr 2011 22:39:14 +0100 Subject: [Tutor] Prologix GPIB to USB converter References: <1301863224.23037191@192.168.4.58> Message-ID: wrote in message news:1301863224.23037191 at 192.168.4.58... > Hello everyone. Is there any code examples out there to > on how to use the prologix GPIB to USB converter? Googling prologix gpib to usb converter python code Got me Resources for GPIB Controllers || Prologix, LLC Prologix GPIB Configurator - Configuration utility for Prologix GPIB-USB controller by John Miles. ... The following sample programs demonstrate how to programmatically send and ... C/C++ sample ? Binary transfer sample in Python. ... As the first hit. I didn't visit but it sounds promising. There were another 3 or 4 tyhat looked like they might have code. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Sun Apr 3 23:46:12 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 04 Apr 2011 07:46:12 +1000 Subject: [Tutor] Prologix GPIB to USB converter In-Reply-To: <1301863224.23037191@192.168.4.58> References: <1301863224.23037191@192.168.4.58> Message-ID: <4D98EAA4.1070600@pearwood.info> markrivet at gsoftcon.com wrote: > Hello everyone. Is there any code examples out there to on how to use the prologix GPIB to USB converter? Probably. What does this have to do with learning Python? This is not a general "ask any computer-related question" list. It's not even a general "ask anything related to Python" list. This is specifically for learning the programming language Python, aimed at beginners. In any case, Google is your friend. Have you tried googling for "prologix GPIB to USB converter +python"? -- Steven From ryan.strunk at gmail.com Mon Apr 4 03:55:25 2011 From: ryan.strunk at gmail.com (Ryan Strunk) Date: Sun, 3 Apr 2011 20:55:25 -0500 Subject: [Tutor] Passing a Variable Message-ID: <001601cbf26b$5e6179a0$1b246ce0$@gmail.com> Hi list, I am in the midst of trying to code a game based entirely on audio cues, and I've run into a bit of a snag when trying to monitor certain variables. I'll lay out the framework of what I'm going for in the hope that it makes sense when written down. In a standard video game I could have a health bar go from normal to yellow to red as it diminishes. In audio, though, I don't have that luxury. As a result, I have conceptualized a system whereby a player hears a sound every so often if a particular stat drops into the caution range. If the player drops into the danger range, the sound loops continuously. I also wanted to make sure that if the player dropped from caution to danger, there wasn't a big, awkward pause in the sound loop and that the player would know immediately that his stat had dropped (see first and second if checks in the check method). The problem: My existing methods directly update stats. For example: the player class has a self.health stat which is directly affected by other methods. This has caused no problem up until now. When I pass self.health to the code I will paste below, however, the Statistic class does not receive health, but rather health's value. I understand that python passes variables by value and not by reference, and this has not been a problem up until now. Now that I am trying to design a class which explicitly checks a specific variable, though, I can't fathom a way to do it unless I pass a direct reference, and I'm not sure that can be done. I need to figure out a way for the below code to check the value of the health variable and act on it. This way, if player's self.health changes, the static class will take note of that and respond accordingly. It occurred to me to make Statistic a child of int, but I'm told that's more trouble than I probably want to deal with. Any suggestions/advice anyone has would be greatly appreciated. Best, Ryan import sound_lib from game_utils import delay #this encapsulates threading.Timer's assignment and start method class Statistic(object): def __init__(self, stat=None, sound=None, low=None, mid=None, high=None): self.stat = stat self.sound = sound self.low = low self.mid = mid self.high = high self.status = 'safe' self.auto_check_timer = None def auto_check(self): if self.stat > self.high: self.status = 'safe' return if self.mid <= self.stat <= self.high: self.status = 'caution' self.sound.play(True) self.auto_check_timer = delay(self.sound.bytes_to_seconds(len(self.sound))*2, self.auto_check) return if self.low <= self.stat < self.mid: self.status = 'danger' self.sound.play(True) self.auto_check_timer = delay(self.sound.bytes_to_seconds(len(self.sound)), self.auto_check) def check(self): if self.status = 'caution' and self.low <= self.stat < self.mid: #This will set the program to start a constant alarm when the stat level has dropped below caution self.auto_check_timer.cancel() if self.sound.is_playing: #to assist in setting up the caution to danger transition #a standard playing sound will have a timer running alongside it, so skip the next guard and return if self.auto_check_timer.is_alive() == False: #guard to make sure program doesn't catch every playing sound, should prevent repeated checks from recalling auto_check sound_duration = self.sound.bytes_to_seconds(len(self.sound)) - self.sound.bytes_to_seconds(self.sound.position) self.auto_check_timer = delay(sound_duration, self.auto_check) return if self.auto_check_timer == False: #if the timer has never been called, call auto_check self.auto_check() return if self.auto_check_timer.is_alive == True: #there's already a timer running. return return #If it gets this far, it's because the timer already ran, the player is 'safe', and another check is being performed self.auto_check() From david.crisp at gmail.com Mon Apr 4 05:09:35 2011 From: david.crisp at gmail.com (David Crisp) Date: Mon, 4 Apr 2011 13:09:35 +1000 Subject: [Tutor] Converting a numpy matrix to a numpy array In-Reply-To: References: Message-ID: On Fri, Apr 1, 2011 at 2:04 AM, Peter Otten <__peter__ at web.de> wrote: > David Crisp wrote: > >> Hello, >> >> I have a very simple question / problem I need answered. ?The problem >> is imnot entirely sure of the correct terminology and langauge to use >> to describe it. ?(One of the reasons im using this miling list) >> >> I have a 2d matrix representing the X the Y and the Z value of a >> point. ?I wish to convert that matrix to an array. ? ?What is a good >> way of doing so? >> >> Eg: >> Matrix >> 012345 >> 0xooooo >> 1xooooo >> 2oxxxxx >> 3oooooo >> 4ooooox >> 5ooooox >> >> >> I want to convert that to a 2d array which looks like: >> 0,0,x >> 0,1,o >> 0,2,o >> 0,3,o >> 0,4,o >> 0,5,o >> ....... >> 5,4,o >> 5,5,o >> >> I am pretty sure it is simple. ?I'm just having a brain fade. > > Using basic numpy: > >>>> import numpy as np >>>> a = np.array(list("xoo" > ... ? ? ? ? ? ? ? ? ? "oxx" > ... ? ? ? ? ? ? ? ? ? "oxo")).reshape(3,3) >>>> a > array([['x', 'o', 'o'], > ? ? ? ['o', 'x', 'x'], > ? ? ? ['o', 'x', 'o']], > ? ? ?dtype='|S1') >>>> np.array([np.arange(9)//3, np.arange(9)%3, a.flatten()]).transpose() > array([['0', '0', 'x'], > ? ? ? ['0', '1', 'o'], > ? ? ? ['0', '2', 'o'], > ? ? ? ['1', '0', 'o'], > ? ? ? ['1', '1', 'x'], > ? ? ? ['1', '2', 'x'], > ? ? ? ['2', '0', 'o'], > ? ? ? ['2', '1', 'x'], > ? ? ? ['2', '2', 'o']], > ? ? ?dtype='|S8') >>>> np.array([np.arange(9)//3, np.arange(9)%3, > (a=="x").flatten()]).transpose() > array([[0, 0, 1], > ? ? ? [0, 1, 0], > ? ? ? [0, 2, 0], > ? ? ? [1, 0, 0], > ? ? ? [1, 1, 1], > ? ? ? [1, 2, 1], > ? ? ? [2, 0, 0], > ? ? ? [2, 1, 1], > ? ? ? [2, 2, 0]]) >>>> np.array([np.arange(9)//3, np.arange(9)%3, a.flatten()], > dtype=object).transpose() > array([[0, 0, x], > ? ? ? [0, 1, o], > ? ? ? [0, 2, o], > ? ? ? [1, 0, o], > ? ? ? [1, 1, x], > ? ? ? [1, 2, x], > ? ? ? [2, 0, o], > ? ? ? [2, 1, x], > ? ? ? [2, 2, o]], dtype=object) > > If that's not good enough you may also ask on the numpy mailing list. Thanks Peter, That appears to do what I want, in a way. How does this work if you have a matrix which is of variable size? For instance, some of my data will create a 10 by 10 matrix but some will create a 40 by 40 matrix, Or for that matter any size. I notice your example specifically states there will be 9 outputs ( tupples? ) what if I want to say "just create as many tuples as you need to use to transpose the data" Regards, David From steve at pearwood.info Mon Apr 4 05:44:43 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 4 Apr 2011 13:44:43 +1000 Subject: [Tutor] Passing a Variable In-Reply-To: <001601cbf26b$5e6179a0$1b246ce0$@gmail.com> References: <001601cbf26b$5e6179a0$1b246ce0$@gmail.com> Message-ID: <20110404034443.GA19169@cybersource.com.au> On Sun, Apr 03, 2011 at 08:55:25PM -0500, Ryan Strunk wrote: > I understand that python passes variables by value and not by reference You understand wrongly. Python is neither pass-by-value nor pass-by-reference. I've written thousands of words on this topic before, so excuse me if I'm a little terse. Rather than write it all out again, I'll just point you at this post: http://mail.python.org/pipermail/tutor/2010-December/080505.html You might also like to read this: http://effbot.org/zone/call-by-object.htm > and > this has not been a problem up until now. Now that I am trying to design a > class which explicitly checks a specific variable, though, I can't fathom a > way to do it unless I pass a direct reference, and I'm not sure that can be > done. One standard way to do this is to have your statistic class have a player attribute, and then have it check the player.health attribute. class Statistic(object): # Check statistics of a player. def __init__(self, player): self.player = player def check_health(self): if self.player.health < 0: print "Bam, you're dead!" An alternative is to have the player object check its own health, calling some appropriate notification object. This could be a global variable, or an attribute of the player (that way each player could have their own notification user-interface). notifier = Notify(sound='on', health_bar='off') # whatever... class Player(object): def __init__(self): self.health = 100 def check_health(self): if self.health < 0: notifier.announce_dead(self) elif self.health < 10: notifer.announce_critical(self) else: notifier.announce_normal(self) Or any of many variations on these. -- Steven From bgailer at gmail.com Mon Apr 4 05:49:03 2011 From: bgailer at gmail.com (bob gailer) Date: Sun, 03 Apr 2011 23:49:03 -0400 Subject: [Tutor] Passing a Variable In-Reply-To: <001601cbf26b$5e6179a0$1b246ce0$@gmail.com> References: <001601cbf26b$5e6179a0$1b246ce0$@gmail.com> Message-ID: <4D993FAF.8070602@gmail.com> On 4/3/2011 9:55 PM, Ryan Strunk wrote: > Hi list, Hi I've read your code. Frankly I don't understand your problem. I also don't see any occurrence of "health". Could you point to a specific line of code, explain what you want and what you are getting. Also your description of the program and the program itself is kinda overwhelming, and so much of that information is not relevant to your question. That makes it hard to understand the question. How about posting the smallest possible piece of code that exemplifies the problem? Python does not "pass by value". It passes a reference to the argument. In essence: def foo(a): pass b = somePythonObject # b is now a reference to somePythonObject foo(b) In calling the function Python "binds" local name a to somePythonObject a is now another reference to somePythonObject > I am in the midst of trying to code a game based entirely on audio cues, and > I've run into a bit of a snag when trying to monitor certain variables. I'll > lay out the framework of what I'm going for in the hope that it makes sense > when written down. > In a standard video game I could have a health bar go from normal to yellow > to red as it diminishes. In audio, though, I don't have that luxury. As a > result, I have conceptualized a system whereby a player hears a sound every > so often if a particular stat drops into the caution range. If the player > drops into the danger range, the sound loops continuously. I also wanted to > make sure that if the player dropped from caution to danger, there wasn't a > big, awkward pause in the sound loop and that the player would know > immediately that his stat had dropped (see first and second if checks in the > check method). > The problem: > My existing methods directly update stats. For example: the player class has > a self.health stat which is directly affected by other methods. This has > caused no problem up until now. When I pass self.health to the code I will > paste below, however, the Statistic class does not receive health, but > rather health's value. > I understand that python passes variables by value and not by reference, and > this has not been a problem up until now. Now that I am trying to design a > class which explicitly checks a specific variable, though, I can't fathom a > way to do it unless I pass a direct reference, and I'm not sure that can be > done. I need to figure out a way for the below code to check the value of > the health variable and act on it. This way, if player's self.health > changes, the static class will take note of that and respond accordingly. > It occurred to me to make Statistic a child of int, but I'm told that's more > trouble than I probably want to deal with. > Any suggestions/advice anyone has would be greatly appreciated. > > Best, > Ryan > > import sound_lib > from game_utils import delay > #this encapsulates threading.Timer's assignment and start method > > class Statistic(object): > > def __init__(self, stat=None, sound=None, low=None, mid=None, > high=None): > self.stat = stat > self.sound = sound > self.low = low > self.mid = mid > self.high = high > self.status = 'safe' > self.auto_check_timer = None > > def auto_check(self): > if self.stat> self.high: > self.status = 'safe' > return > if self.mid<= self.stat<= self.high: > self.status = 'caution' > self.sound.play(True) > self.auto_check_timer = > delay(self.sound.bytes_to_seconds(len(self.sound))*2, self.auto_check) > return > if self.low<= self.stat< self.mid: > self.status = 'danger' > self.sound.play(True) > self.auto_check_timer = > delay(self.sound.bytes_to_seconds(len(self.sound)), self.auto_check) You can simplify the above logic: if self.stat > self.high: self.status = 'safe' elif self.stat >= self.mid: self.status = 'caution' self.sound.play(True) self.auto_check_timer = delay(self.sound.bytes_to_seconds(len(self.sound))*2, self.auto_check) elif self.stat >= self.low: self.status = 'danger' self.sound.play(True) self.auto_check_timer = delay(self.sound.bytes_to_seconds(len(self.sound)), self.auto_check) > def check(self): > if self.status = 'caution' and self.low<= self.stat< self.mid: > #This will set the program to start a constant alarm when the > stat level has dropped below caution > self.auto_check_timer.cancel() > if self.sound.is_playing: > #to assist in setting up the caution to danger transition > #a standard playing sound will have a timer running alongside > it, so skip the next guard and return > if self.auto_check_timer.is_alive() == False: > #guard to make sure program doesn't catch every playing > sound, should prevent repeated checks from recalling auto_check > sound_duration = > self.sound.bytes_to_seconds(len(self.sound)) - > self.sound.bytes_to_seconds(self.sound.position) > self.auto_check_timer = delay(sound_duration, > self.auto_check) > return > if self.auto_check_timer == False: > #if the timer has never been called, call auto_check > self.auto_check() > return > if self.auto_check_timer.is_alive == True: > #there's already a timer running. return > return > #If it gets this far, it's because the timer already ran, the player > is 'safe', and another check is being performed > self.auto_check() > Also note if self.auto_check_timer == False: can be simplified to if not self.auto_check_timer: and if self.auto_check_timer.is_alive == True: to if self.auto_check_timer.is_alive: also it is better to eliminte the returns and use elif as I did furhter above -- Bob Gailer 919-636-4239 Chapel Hill NC From tcl76 at hotmail.com Mon Apr 4 05:58:54 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Mon, 4 Apr 2011 03:58:54 +0000 Subject: [Tutor] Calling another script Message-ID: hi, i want to read from a file which will indicate which operation to execute. so i'm using configparser module. i want one.py to read a configuration file and executes two.py and three.py. however, it only executes two.py and not three.py codes. pls help advise. thanks tcl +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ one.py: import ConfigParser config = ConfigParser.ConfigParser() config.read("configuration.ini") operation=config.get("config", "operation") if int(operation)== 0: import two import three else: print "Default" two.py: print "executing script number 2" three.py: print "executing script number 3" -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: configuration.ini Type: application/octet-stream Size: 24 bytes Desc: not available URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: one.py URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: two.py URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: three.py URL: From bgailer at gmail.com Mon Apr 4 06:29:19 2011 From: bgailer at gmail.com (bob gailer) Date: Mon, 04 Apr 2011 00:29:19 -0400 Subject: [Tutor] Calling another script In-Reply-To: References: Message-ID: <4D99491F.20707@gmail.com> On 4/3/2011 11:58 PM, tee chwee liong wrote: > hi, > > i want to read from a file which will indicate which operation to > execute. so i'm using configparser module. i want one.py to read a > configuration file and executes two.py and three.py. however, it only > executes two.py and not three.py codes. pls help advise. I see no reason for the problem you report. I tested a brief version: import two import three and it worked as expected. The only reason I can think of for it not working is that you had already imported three.py. Importing again will NOT re-execute the module! > > thanks > tcl > > +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ > > *_one.py:_* > import ConfigParser > config = ConfigParser.ConfigParser() > config.read("configuration.ini") > operation=config.get("config", "operation") > if int(operation)== 0: > import two > import three > else: > print "Default" > > *_two.py:_* > print "executing script number 2" > > *_three.py:_* > print "executing script number 3" > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From douqilong at gmail.com Mon Apr 4 06:52:47 2011 From: douqilong at gmail.com (Kane Dou) Date: Mon, 4 Apr 2011 12:52:47 +0800 Subject: [Tutor] Converting a numpy matrix to a numpy array In-Reply-To: References: Message-ID: <20110404045246.GA6244@kdblue.com> This may work: from pprint import pprint plan = """xooooo xooooo oxxxxx oooooo ooooox ooooox """ width = plan.index("\n") height = plan.count("\n") a = [[w, h] for h in xrange(height) for w in xrange(width)] for (xy, c) in zip(a, plan.replace("\n", "")): xy.append(c) pprint(a) |46>%run test.py [[0, 0, 'x'], [1, 0, 'o'], [2, 0, 'o'], [3, 0, 'o'], [4, 0, 'o'], [5, 0, 'o'], [0, 1, 'x'], [1, 1, 'o'], [2, 1, 'o'], [3, 1, 'o'], [4, 1, 'o'], [5, 1, 'o'], [0, 2, 'o'], [1, 2, 'x'], [2, 2, 'x'], [3, 2, 'x'], [4, 2, 'x'], [5, 2, 'x'], [0, 3, 'o'], [1, 3, 'o'], [2, 3, 'o'], [3, 3, 'o'], [4, 3, 'o'], [5, 3, 'o'], [0, 4, 'o'], [1, 4, 'o'], [2, 4, 'o'], [3, 4, 'o'], [4, 4, 'o'], [5, 4, 'x'], [0, 5, 'o'], [1, 5, 'o'], [2, 5, 'o'], [3, 5, 'o'], [4, 5, 'o'], [5, 5, 'x']] * David Crisp [2011-04-04 13:09:35 +1000]: > On Fri, Apr 1, 2011 at 2:04 AM, Peter Otten <__peter__ at web.de> wrote: > > David Crisp wrote: > > > >> Hello, > >> > >> I have a very simple question / problem I need answered. ?The problem > >> is imnot entirely sure of the correct terminology and langauge to use > >> to describe it. ?(One of the reasons im using this miling list) > >> > >> I have a 2d matrix representing the X the Y and the Z value of a > >> point. ?I wish to convert that matrix to an array. ? ?What is a good > >> way of doing so? > >> > >> Eg: > >> Matrix > >> 012345 > >> 0xooooo > >> 1xooooo > >> 2oxxxxx > >> 3oooooo > >> 4ooooox > >> 5ooooox > >> > >> > >> I want to convert that to a 2d array which looks like: > >> 0,0,x > >> 0,1,o > >> 0,2,o > >> 0,3,o > >> 0,4,o > >> 0,5,o > >> ....... > >> 5,4,o > >> 5,5,o > >> > >> I am pretty sure it is simple. ?I'm just having a brain fade. > > > > Using basic numpy: > > > >>>> import numpy as np > >>>> a = np.array(list("xoo" > > ... ? ? ? ? ? ? ? ? ? "oxx" > > ... ? ? ? ? ? ? ? ? ? "oxo")).reshape(3,3) > >>>> a > > array([['x', 'o', 'o'], > > ? ? ? ['o', 'x', 'x'], > > ? ? ? ['o', 'x', 'o']], > > ? ? ?dtype='|S1') > >>>> np.array([np.arange(9)//3, np.arange(9)%3, a.flatten()]).transpose() > > array([['0', '0', 'x'], > > ? ? ? ['0', '1', 'o'], > > ? ? ? ['0', '2', 'o'], > > ? ? ? ['1', '0', 'o'], > > ? ? ? ['1', '1', 'x'], > > ? ? ? ['1', '2', 'x'], > > ? ? ? ['2', '0', 'o'], > > ? ? ? ['2', '1', 'x'], > > ? ? ? ['2', '2', 'o']], > > ? ? ?dtype='|S8') > >>>> np.array([np.arange(9)//3, np.arange(9)%3, > > (a=="x").flatten()]).transpose() > > array([[0, 0, 1], > > ? ? ? [0, 1, 0], > > ? ? ? [0, 2, 0], > > ? ? ? [1, 0, 0], > > ? ? ? [1, 1, 1], > > ? ? ? [1, 2, 1], > > ? ? ? [2, 0, 0], > > ? ? ? [2, 1, 1], > > ? ? ? [2, 2, 0]]) > >>>> np.array([np.arange(9)//3, np.arange(9)%3, a.flatten()], > > dtype=object).transpose() > > array([[0, 0, x], > > ? ? ? [0, 1, o], > > ? ? ? [0, 2, o], > > ? ? ? [1, 0, o], > > ? ? ? [1, 1, x], > > ? ? ? [1, 2, x], > > ? ? ? [2, 0, o], > > ? ? ? [2, 1, x], > > ? ? ? [2, 2, o]], dtype=object) > > > > If that's not good enough you may also ask on the numpy mailing list. > > Thanks Peter, > > That appears to do what I want, in a way. How does this work if you > have a matrix which is of variable size? For instance, some of my > data will create a 10 by 10 matrix but some will create a 40 by 40 > matrix, Or for that matter any size. I notice your example > specifically states there will be 9 outputs ( tupples? ) what if I > want to say "just create as many tuples as you need to use to > transpose the data" > > Regards, > David > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From tcl76 at hotmail.com Mon Apr 4 07:10:50 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Mon, 4 Apr 2011 05:10:50 +0000 Subject: [Tutor] Calling another script In-Reply-To: <4D99491F.20707@gmail.com> References: , <4D99491F.20707@gmail.com> Message-ID: hi, i opened a cmd DOS prompt to execute one.py. it works to execute codes from two.py and three.py. yes, you are fight it will not re-execute the module. is there a way to do it? i want after the python script finishes execution will return the control to the DOS prompt instead of leaving as >>>. i tried putting sys.exit(). thanks cltee Date: Mon, 4 Apr 2011 00:29:19 -0400 From: bgailer at gmail.com To: tutor at python.org Subject: Re: [Tutor] Calling another script On 4/3/2011 11:58 PM, tee chwee liong wrote: hi, i want to read from a file which will indicate which operation to execute. so i'm using configparser module. i want one.py to read a configuration file and executes two.py and three.py. however, it only executes two.py and not three.py codes. pls help advise. I see no reason for the problem you report. I tested a brief version: import two import three and it worked as expected. The only reason I can think of for it not working is that you had already imported three.py. Importing again will NOT re-execute the module! thanks tcl +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ one.py: import ConfigParser config = ConfigParser.ConfigParser() config.read("configuration.ini") operation=config.get("config", "operation") if int(operation)== 0: import two import three else: print "Default" two.py: print "executing script number 2" three.py: print "executing script number 3" _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -- 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 tcl76 at hotmail.com Mon Apr 4 07:19:36 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Mon, 4 Apr 2011 05:19:36 +0000 Subject: [Tutor] Calling another script In-Reply-To: References: , , <4D99491F.20707@gmail.com>, Message-ID: hi, thanks everyone. i tried sys.exit() inside one.py and it works to return to DOS prompt. thanks tcl From: tcl76 at hotmail.com To: bgailer at gmail.com; tutor at python.org Date: Mon, 4 Apr 2011 05:10:50 +0000 Subject: Re: [Tutor] Calling another script hi, i opened a cmd DOS prompt to execute one.py. it works to execute codes from two.py and three.py. yes, you are fight it will not re-execute the module. is there a way to do it? i want after the python script finishes execution will return the control to the DOS prompt instead of leaving as >>>. i tried putting sys.exit(). thanks cltee Date: Mon, 4 Apr 2011 00:29:19 -0400 From: bgailer at gmail.com To: tutor at python.org Subject: Re: [Tutor] Calling another script On 4/3/2011 11:58 PM, tee chwee liong wrote: hi, i want to read from a file which will indicate which operation to execute. so i'm using configparser module. i want one.py to read a configuration file and executes two.py and three.py. however, it only executes two.py and not three.py codes. pls help advise. I see no reason for the problem you report. I tested a brief version: import two import three and it worked as expected. The only reason I can think of for it not working is that you had already imported three.py. Importing again will NOT re-execute the module! thanks tcl +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ one.py: import ConfigParser config = ConfigParser.ConfigParser() config.read("configuration.ini") operation=config.get("config", "operation") if int(operation)== 0: import two import three else: print "Default" two.py: print "executing script number 2" three.py: print "executing script number 3" _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -- 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 _______________________________________________ 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 ryan.strunk at gmail.com Mon Apr 4 07:27:53 2011 From: ryan.strunk at gmail.com (Ryan Strunk) Date: Mon, 4 Apr 2011 00:27:53 -0500 Subject: [Tutor] Passing a Variable In-Reply-To: <4D993FAF.8070602@gmail.com> References: <001601cbf26b$5e6179a0$1b246ce0$@gmail.com> <4D993FAF.8070602@gmail.com> Message-ID: <002601cbf289$0cc32cb0$26498610$@gmail.com> > I've read your code. Frankly I don't understand your problem. I also don't see any occurrence of "health". There isn't a reference to health here. My goal is to have this code act as a checker for health, fatigue, time_remaining, or any other sort of statistic you'd like to throw into it. My problem is that when I try: instance = Statistic(stat=health, sound=spam, low=1, mid=15, high=30) health can change elsewhere in the program, but the instance of statistic class won't automatically see it. > Also your description of the program and the program itself is kinda overwhelming, and so much of that information is not relevant to your question. That makes it hard to understand the question. My apologies if this came across as verbose. I'm a newbie at all things python, so I'm still learning everything from code to conventions. > You can simplify the above logic: Thank you for that. I will happily accept style suggestions whenever I can get them. From __peter__ at web.de Mon Apr 4 09:37:00 2011 From: __peter__ at web.de (Peter Otten) Date: Mon, 04 Apr 2011 09:37 +0200 Subject: [Tutor] Converting a numpy matrix to a numpy array References: Message-ID: David Crisp wrote: >>>>> np.array([np.arange(9)//3, np.arange(9)%3, a.flatten()], >> dtype=object).transpose() >> array([[0, 0, x], >> [0, 1, o], >> [0, 2, o], >> [1, 0, o], >> [1, 1, x], >> [1, 2, x], >> [2, 0, o], >> [2, 1, x], >> [2, 2, o]], dtype=object) >> >> If that's not good enough you may also ask on the numpy mailing list. > > Thanks Peter, > > That appears to do what I want, in a way. How does this work if you > have a matrix which is of variable size? For instance, some of my > data will create a 10 by 10 matrix but some will create a 40 by 40 > matrix, Or for that matter any size. I notice your example > specifically states there will be 9 outputs ( tupples? ) what if I > want to say "just create as many tuples as you need to use to > transpose the data" You can find out the size of the matrix with the shape attribute: >>> a array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> a.shape (3, 4) Use that to calculate the values needed to replace the constants in my previous post. Try to make do without the spoiler below! >>> def process(a, dtype=object): ... x, y = a.shape ... n = x*y ... return np.array([np.arange(n)//y, np.arange(n)%y, a.flatten()], dtype=dtype).transpose() ... >>> a = np.arange(12).reshape(3, 4) >>> a array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> process(a, int) array([[ 0, 0, 0], [ 0, 1, 1], [ 0, 2, 2], [ 0, 3, 3], [ 1, 0, 4], [ 1, 1, 5], [ 1, 2, 6], [ 1, 3, 7], [ 2, 0, 8], [ 2, 1, 9], [ 2, 2, 10], [ 2, 3, 11]]) >>> b = np.array(list( ... "xoo" ... "oxx" ... "oxo")).reshape(3, 3) >>> process(b, object) array([[0, 0, x], [0, 1, o], [0, 2, o], [1, 0, o], [1, 1, x], [1, 2, x], [2, 0, o], [2, 1, x], [2, 2, o]], dtype=object) From easywebs4u at gmail.com Mon Apr 4 10:34:49 2011 From: easywebs4u at gmail.com (Greg Richards) Date: Mon, 4 Apr 2011 03:34:49 -0500 Subject: [Tutor] (no subject) Message-ID: http%3A%2F%2Fminilien%2Ecom%2F%3FZuctsogCRp From alan.gauld at btinternet.com Mon Apr 4 10:14:27 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 4 Apr 2011 09:14:27 +0100 Subject: [Tutor] Calling another script Message-ID: "tee chwee liong" wrote > i want one.py to read a configuration file and > executes two.py and three.py. > > if int(operation)== 0: > import two > else: > print "Default" > > two.py: > print "executing script number 2" > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > importing a module is not intended as a mechanism to execute code, that should be considered a side-effect or an initialisation feature. importing makes code available for use. Put the code in the modules into functions, then import all the modules at the start of your program. Then execute the functions within your if/else logic. import two,three operation = read_from_config_file(filename) if operation == 0: two.doTwo() three.doThree() else: print "invalid operation" That wil, be a more reliable and flexible approach. In fact you could put all the operations in one module... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Mon Apr 4 10:46:01 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 4 Apr 2011 18:46:01 +1000 Subject: [Tutor] Calling another script In-Reply-To: References: <4D99491F.20707@gmail.com> Message-ID: <20110404084601.GB19169@cybersource.com.au> On Mon, Apr 04, 2011 at 05:10:50AM +0000, tee chwee liong wrote: > > hi, > > i opened a cmd DOS prompt to execute one.py. it works to execute codes from two.py and three.py. yes, you are fight it will not re-execute the module. > is there a way to do it? i want after the python script finishes execution will return the control to the DOS prompt instead of leaving as >>>. > i tried putting sys.exit(). Do not confuse importing a script with running a script. The usual way to run a script is to write it with a main() function, and then call that: # === myscript.py === print("Set up code goes here...") # this only gets executed once, the FIRST time you import the module def main(): print("Running script now!") if __name__ == '__main__': # We've been called from the shell. main() In your other script, you do this: # === Master script that calls myscript === if __name__ == '__main__': # Running as a script ourselves. import myscript myscript.main() -- Steven From andreengels at gmail.com Mon Apr 4 12:09:29 2011 From: andreengels at gmail.com (Andre Engels) Date: Mon, 4 Apr 2011 12:09:29 +0200 Subject: [Tutor] Passing a Variable In-Reply-To: <002601cbf289$0cc32cb0$26498610$@gmail.com> References: <001601cbf26b$5e6179a0$1b246ce0$@gmail.com> <4D993FAF.8070602@gmail.com> <002601cbf289$0cc32cb0$26498610$@gmail.com> Message-ID: On Mon, Apr 4, 2011 at 7:27 AM, Ryan Strunk wrote: >> I've read your code. Frankly I don't understand your problem. I also don't > see any occurrence of "health". > There isn't a reference to health here. My goal is to have this code act as > a checker for health, fatigue, time_remaining, or any other sort of > statistic you'd like to throw into it. My problem is that when I try: > instance = Statistic(stat=health, sound=spam, low=1, mid=15, high=30) > health can change elsewhere in the program, but the instance of statistic > class won't automatically see it. My proposal would be to wrap the stats in an object: Class stat: __init__(self, name, value) self.type = name self.value = value Then in the player object change the initialisation health = startvalue to health = stat("health", startvalue) and change every other reference to health to a reference to health.value. Then you can use the current code if you replace self.stat outside the __init__ by self.stat.value You could even consider merging the stats and Statistics classes. ====== Another possibility would be to use a getter method and the fact that methods are objects: In the player object add: def get_health(self): return self.health change the call to: instance = Statistic(stat=get_health, sound=spam, low=1, mid=15, high=30) and replace self.stat by self.stat() everywhere in the Statistics code -- Andr? Engels, andreengels at gmail.com From alan.gauld at btinternet.com Mon Apr 4 10:14:27 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 4 Apr 2011 09:14:27 +0100 Subject: [Tutor] Calling another script References: Message-ID: "tee chwee liong" wrote > i want one.py to read a configuration file and > executes two.py and three.py. > > if int(operation)== 0: > import two > else: > print "Default" > > two.py: > print "executing script number 2" > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > importing a module is not intended as a mechanism to execute code, that should be considered a side-effect or an initialisation feature. importing makes code available for use. Put the code in the modules into functions, then import all the modules at the start of your program. Then execute the functions within your if/else logic. import two,three operation = read_from_config_file(filename) if operation == 0: two.doTwo() three.doThree() else: print "invalid operation" That wil, be a more reliable and flexible approach. In fact you could put all the operations in one module... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From tcl76 at hotmail.com Mon Apr 4 14:45:40 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Mon, 4 Apr 2011 12:45:40 +0000 Subject: [Tutor] Calling another script In-Reply-To: References: , Message-ID: thanks all for your advice. -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Mon Apr 4 15:27:38 2011 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 04 Apr 2011 23:27:38 +1000 Subject: [Tutor] Passing a Variable In-Reply-To: <001601cbf26b$5e6179a0$1b246ce0$@gmail.com> References: <001601cbf26b$5e6179a0$1b246ce0$@gmail.com> Message-ID: On 04/04/11 11:55, Ryan Strunk wrote: > Hi list, > > I am in the midst of trying to code a game based entirely on audio cues, and > I've run into a bit of a snag when trying to monitor certain variables. I'll > lay out the framework of what I'm going for in the hope that it makes sense > when written down. > In a standard video game I could have a health bar go from normal to yellow > to red as it diminishes. In audio, though, I don't have that luxury. As a > result, I have conceptualized a system whereby a player hears a sound every > so often if a particular stat drops into the caution range. If the player > drops into the danger range, the sound loops continuously. I also wanted to > make sure that if the player dropped from caution to danger, there wasn't a > big, awkward pause in the sound loop and that the player would know > immediately that his stat had dropped (see first and second if checks in the > check method). > The problem: > My existing methods directly update stats. For example: the player class has > a self.health stat which is directly affected by other methods. This has > caused no problem up until now. When I pass self.health to the code I will > paste below, however, the Statistic class does not receive health, but > rather health's value. > I understand that python passes variables by value and not by reference, and > this has not been a problem up until now. Now that I am trying to design a > class which explicitly checks a specific variable, though, I can't fathom a > way to do it unless I pass a direct reference, and I'm not sure that can be > done. I need to figure out a way for the below code to check the value of > the health variable and act on it. This way, if player's self.health > changes, the static class will take note of that and respond accordingly. > It occurred to me to make Statistic a child of int, but I'm told that's more > trouble than I probably want to deal with. > Any suggestions/advice anyone has would be greatly appreciated. Rather than having Statistic polling the Player's health, I suggest that the Player object should call a method in Statistic class when its health changes, and then the Statistic class can see if the value change is relevant or not (e.g. whether to start playing audio, or not). Since you said that you modified self.health directly, in some other languages this might cause you problems. But behold, this is python, you can easily turn your attribute into property: class Player(object): def __init__(self): self.stat = Statistic() self._health = 100 @property def health(self): return self._health @health.setter def health(self, value): self.stat.health_changed(self, value) self._health = value class Statistic(object): def __init__(...): ... def health_changed(self, player, value): if value < player.health: play_once('taking damage') elif value > player.health: play_once('getting healed') if value < self.low: self.status = 'danger' play_repeat('danger') elif value < self.mid: self.status = 'warning' play_repeat('warning') else: self.status = 'safe' play_stop() > Best, > Ryan > > import sound_lib > from game_utils import delay > #this encapsulates threading.Timer's assignment and start method > > class Statistic(object): > > def __init__(self, stat=None, sound=None, low=None, mid=None, > high=None): > self.stat = stat > self.sound = sound > self.low = low > self.mid = mid > self.high = high > self.status = 'safe' > self.auto_check_timer = None > > def auto_check(self): > if self.stat > self.high: > self.status = 'safe' > return > if self.mid <= self.stat <= self.high: > self.status = 'caution' > self.sound.play(True) > self.auto_check_timer = > delay(self.sound.bytes_to_seconds(len(self.sound))*2, self.auto_check) > return > if self.low <= self.stat < self.mid: > self.status = 'danger' > self.sound.play(True) > self.auto_check_timer = > delay(self.sound.bytes_to_seconds(len(self.sound)), self.auto_check) > > def check(self): > if self.status = 'caution' and self.low <= self.stat < self.mid: > #This will set the program to start a constant alarm when the > stat level has dropped below caution > self.auto_check_timer.cancel() > if self.sound.is_playing: > #to assist in setting up the caution to danger transition > #a standard playing sound will have a timer running alongside > it, so skip the next guard and return > if self.auto_check_timer.is_alive() == False: > #guard to make sure program doesn't catch every playing > sound, should prevent repeated checks from recalling auto_check > sound_duration = > self.sound.bytes_to_seconds(len(self.sound)) - > self.sound.bytes_to_seconds(self.sound.position) > self.auto_check_timer = delay(sound_duration, > self.auto_check) > return > if self.auto_check_timer == False: > #if the timer has never been called, call auto_check > self.auto_check() > return > if self.auto_check_timer.is_alive == True: > #there's already a timer running. return > return > #If it gets this far, it's because the timer already ran, the player > is 'safe', and another check is being performed > self.auto_check() > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From coolankur2006 at gmail.com Mon Apr 4 18:12:26 2011 From: coolankur2006 at gmail.com (ANKUR AGGARWAL) Date: Mon, 4 Apr 2011 21:42:26 +0530 Subject: [Tutor] Recommendations required Message-ID: Hey I am reading pygame module and experimenting with it in small codes too . I want your help. I want you to recommend the games ,beginner of this module should try to develop as a practice or so. Thanks Ankur Aggarwal -------------- next part -------------- An HTML attachment was scrubbed... URL: From jigenbakuda at yahoo.com Mon Apr 4 19:43:22 2011 From: jigenbakuda at yahoo.com (michael scott) Date: Mon, 4 Apr 2011 10:43:22 -0700 (PDT) Subject: [Tutor] Recommendations required In-Reply-To: References: Message-ID: <319845.68025.qm@web130220.mail.mud.yahoo.com> Hello Ankur, Well as a beginner myself I suggest that you check out these games and modify them or create new versions of them (with additional functionality). There are lots of stock answers, but in general old arcade games from the 70's are great places to start. They are simple enough and you should understand enough about them to know the various things you will need to implement. Heavily coded games http://inventwithpython.com/blog/category/code-comments/ I asked the same question a while back and I'm sure you will get similar answers to what I got. Although If you have not done most of the tutorials on the pygame site itself, even these heavily coded source codes may be too complex for you too handle. The pygame tutorials http://pygame.org/wiki/tutorials Good luck and I hope you create fun games for others to play. ---- What is it about you... that intrigues me so? ________________________________ From: ANKUR AGGARWAL To: pygame-users at seul.org; tutor at python.org Sent: Mon, April 4, 2011 12:12:26 PM Subject: [Tutor] Recommendations required Hey I am reading pygame module and experimenting with it in small codes too . I want your help. I want you to recommend the games ,beginner of this module should try to develop as a practice or so. Thanks Ankur Aggarwal -------------- next part -------------- An HTML attachment was scrubbed... URL: From cbc at unc.edu Tue Apr 5 00:27:32 2011 From: cbc at unc.edu (Chris Calloway) Date: Mon, 04 Apr 2011 18:27:32 -0400 Subject: [Tutor] Toronto PyCamp 2011 Message-ID: <4D9A45D4.9070805@unc.edu> The University of Toronto Department of Physics brings PyCamp to Toronto on Monday, June 27 through Thursday, June 30, 2011. Register today at http://trizpug.org/boot-camp/torpy11/ For beginners, this ultra-low-cost Python Boot Camp makes you productive so you can get your work done quickly. PyCamp emphasizes the features which make Python a simpler and more efficient language. Following along with example Python PushUps? speeds your learning process. Become a self-sufficient Python developer in just four days at PyCamp! PyCamp is conducted on the campus of the University of Toronto in a state of the art high technology classroom. -- Sincerely, Chris Calloway http://nccoos.org/Members/cbc office: 3313 Venable Hall phone: (919) 599-3530 mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599 From jdeltoro1973 at gmail.com Tue Apr 5 23:03:21 2011 From: jdeltoro1973 at gmail.com (Juan Jose Del Toro) Date: Tue, 5 Apr 2011 16:03:21 -0500 Subject: [Tutor] Release of Mapoteca-0.1 Message-ID: Dear List; Today we finally released our Python scripts for creating a catalog of geographic information, these scripts walk through directories looking for geographic information in the form of shp, tif, bil and img and using the GDAL bindings extracting its extent, geometry, number of elements, projection, dbf description, user, date last modification, path, etc and writes it into an csv file. We release these scripts as an open source project, and it is intended to work with the FWTools installation (only was tested in FWTools 2.4.7) The scripts can be found in http://sourceforge.net/projects/mapoteca/ -- ?Saludos! / Greetings! Juan Jos? Del Toro M. jdeltoro1973 at gmail.com Guadalajara, Jalisco MEXICO -------------- next part -------------- An HTML attachment was scrubbed... URL: From jigenbakuda at yahoo.com Wed Apr 6 03:59:17 2011 From: jigenbakuda at yahoo.com (michael scott) Date: Tue, 5 Apr 2011 18:59:17 -0700 (PDT) Subject: [Tutor] (sqlite3) Testing if a table has been created. Message-ID: <319878.23447.qm@web130203.mail.mud.yahoo.com> Hello guys, Since sqlite gives an error if you try to create a table that's already there, how do I test if a table is already present? for example in def database(info): import sqlite3 connection = sqlite3.connect("test.db") cursor = connection.cursor() if table not in test.db: #with this being my test that I'm not sure how to implement cursor.execute(""" CREATE TABLE stuff (id INTEGER PRIMARY KEY, name TEXT)""") cursor.execute("""INSERT INTO stuff VALUES (null, ?)""",(info)) cursor.commit() cursor.close() connection.close() How would I properly test if table not in test.db: ? Is it something as simple as having a method of cursor check it for me, or should I just create my table in the beginning of my code(outside of this function) and leave it out of the function all together, so I can just have my function focusing on inserting data? Uhm, in the immediate example I'm using, this is a function, thats inside of a function used by a tkinter button, a save button if you will. So I want it to save whatever is in the entry widget to the database. Keeping this in mind, am I going about it the wrong way? Should I be trying to save a different way? ---- What is it about you... that intrigues me so? -------------- next part -------------- An HTML attachment was scrubbed... URL: From rhelmer at rhelmer.org Wed Apr 6 04:19:11 2011 From: rhelmer at rhelmer.org (Robert Helmer) Date: Tue, 5 Apr 2011 19:19:11 -0700 Subject: [Tutor] (sqlite3) Testing if a table has been created. In-Reply-To: <319878.23447.qm@web130203.mail.mud.yahoo.com> References: <319878.23447.qm@web130203.mail.mud.yahoo.com> Message-ID: On Tue, Apr 5, 2011 at 6:59 PM, michael scott wrote: > Hello guys, > > Since sqlite gives an error if you try to create a table that's already > there, how do I test if a table is already present? > > > for example in > > def database(info): > import sqlite3 > > connection = sqlite3.connect("test.db") > cursor = connection.cursor() > if table not in test.db: #with this being my test that I'm not sure how > to implement See http://www.sqlite.org/faq.html#q7 For example: select * from sqlite_master where name='test'; Alternatively, if the only purpose in checking to see if the table exists is so that it can be created, you can simple do: create table if not exists test (...); From lachlan.00 at gmail.com Wed Apr 6 07:10:35 2011 From: lachlan.00 at gmail.com (Lachlan d) Date: Wed, 6 Apr 2011 15:10:35 +1000 Subject: [Tutor] Rhythmbox python plugin to capture middle click event Message-ID: I've been working on some python rhythmbox plugins for the past few months and now i've decided to try writing my own. I've been able to get actions working correctly in my other plugin. (http://launchpad.net/rb-fileorganizer) but that uses buttons and a gui i built rather than mouse clicks. What i'm trying to create is a plugin that will perform and action every time the middle mouse button is clicked in rhythmbox. I haven't been able to find any solid information about doing this on the net. The plugin will load but i don't think anything in capture_click is correct. Any help getting this to just print the test message in the console would be greatly appreciated! Here's my code that i've written up so far: class middleclick(rb.Plugin): def __init__(self): rb.Plugin.__init__(self) # Rhythmbox standard Activate method def activate(self, shell): self.shell = shell self.capture_click(shell) # Rhythmbox standard Deactivate method def deactivate(self, shell): self.shell = None # Run test_plugin for middle click def capture_click(self, shell): self.action = gtk.Action('MiddleClick', _('Middle Click'), _('Action on Middle Click'), gtk.gdk.BUTTON_PRESS_MASK) self.action.connect('activate', self.test_plugin, shell) self.action_group = gtk.ActionGroup('OnClickActions') self.action_group.add_action(self.action) uim = shell.get_ui_manager() uim.insert_action_group(self.action_group, 0) uim.ensure_update() def test_plugin(self, shell): if event.button == 2: print 'THIS IS AN EVENT' else print 'WRONG EVENT' From thegreentealeaf at gmail.com Wed Apr 6 10:27:27 2011 From: thegreentealeaf at gmail.com (The Green Tea Leaf) Date: Wed, 6 Apr 2011 10:27:27 +0200 Subject: [Tutor] Showing/hiding widgets in Tkinter Message-ID: Hi all, I'm trying to learn a bit about how to show/hide objects using the available layout managers and have no problems using Pack or Grid but when I try to use Place then I'm missing something My test code looks like this from Tkinter import * def toggle(): if mylabel.visible: mylabel.place_forget() else: mylabel.place() mylabel.visible = not mylabel.visible root = Tk() mylabel = Label(text="Example") mylabel.visible = True mylabel.place(x=20,y=50) btnToggle = Button(text="Toggle nr two",command=toggle) btnToggle.place(x=70,y=150) root.mainloop() According to the documentation I've read I should be able to use 'place()' after having used 'place_forget()' to show the label at the same place. What happens is on the first click the label disappears, but when I click again it stays invisible (and yes, the else statement is executed). If I change the else-statement to 'mylabel.place(x=70,y=150)' Any idea what I'm missing? -- The Green Tea Leaf?? thegreentealeaf at gmail.com?? thegreentealeaf.blogspot.com From mast.ratna at gmail.com Wed Apr 6 11:34:46 2011 From: mast.ratna at gmail.com (Ratna Banjara) Date: Wed, 6 Apr 2011 15:19:46 +0545 Subject: [Tutor] GUI IDLE for UBUNTU 10 Message-ID: As i know python comes as default in ubuntu and can be accessed from terminal. But i found difficulty to write programs in editor and run from terminal. I need GUI Before this i used to run in windows with python IDLE which makes easy to write python codes and run using Run command or pressing F5. Now i want to ask if there is python GUI IDLE equivalent in Ubuntu. Please help. -- Regards, Ratna P Banjara -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Wed Apr 6 12:35:55 2011 From: __peter__ at web.de (Peter Otten) Date: Wed, 06 Apr 2011 12:35:55 +0200 Subject: [Tutor] Showing/hiding widgets in Tkinter References: Message-ID: The Green Tea Leaf wrote: > Hi all, > > I'm trying to learn a bit about how to show/hide objects using the > available layout managers and have no problems using Pack or Grid but > when I try to use Place then I'm missing something > > My test code looks like this > > from Tkinter import * > > def toggle(): > if mylabel.visible: > mylabel.place_forget() > else: > mylabel.place() > mylabel.visible = not mylabel.visible > > root = Tk() > > mylabel = Label(text="Example") > mylabel.visible = True > mylabel.place(x=20,y=50) > > btnToggle = Button(text="Toggle nr two",command=toggle) > btnToggle.place(x=70,y=150) > > root.mainloop() > > According to the documentation I've read I should be able to use > 'place()' after having used 'place_forget()' to show the label at the > same place. Where did you read that? I only found """ If the configuration of a window has been retrieved with place info, that configuration can be restored later by first using place forget to erase any existing information for the window and then invoking place configure with the saved information. """ at http://www.tcl.tk/man/tcl8.5/TkCmd/place.htm which implies that tk does not store the placement information automatically. Assuming that Python's Tkinter behaves the same way you can write def toggle(): if mylabel.visible: mylabel.pi = mylabel.place_info() mylabel.place_forget() else: mylabel.place(mylabel.pi) mylabel.visible = not mylabel.visible > What happens is on the first click the label disappears, but when I > click again it stays invisible (and yes, the else statement is > executed). If I change the else-statement to > 'mylabel.place(x=70,y=150)' > > Any idea what I'm missing? From kb1pkl at aim.com Wed Apr 6 12:40:04 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Wed, 06 Apr 2011 06:40:04 -0400 Subject: [Tutor] GUI IDLE for UBUNTU 10 In-Reply-To: References: Message-ID: <4D9C4304.5070809@aim.com> On 04/06/2011 05:34 AM, Ratna Banjara wrote: > Before this i used to run in windows with python IDLE which makes easy to > write python codes and run using Run command or pressing F5. > > Now i want to ask if there is python GUI IDLE equivalent in Ubuntu. Please > help. At the terminal, sudo apt-get install idle. When you need software, search in Synaptic (Package Manager) or google first, it's usually very accessible! -- Corey Richardson From andres at chandia.net Wed Apr 6 12:43:56 2011 From: andres at chandia.net (=?iso-8859-1?Q?=22Andr=E9s_Chand=EDa=22?=) Date: Wed, 6 Apr 2011 12:43:56 +0200 Subject: [Tutor] GUI IDLE for UBUNTU 10 In-Reply-To: References: Message-ID: <00c34903d50664219a1eb84a75727725.squirrel@mail.chandia.net> Actually the default text editor in Ubuntu, "gedit" has a plugin named Python console, that you can activate at "edit > preferences" menu, then at the menu "view > inferior subwindow" (F9) you can activate it, maybe the menu names are not exact, because I'm translating from catalan. Good luck! On Wed, April 6, 2011 11:34, Ratna Banjara wrote: As i know python comes as default in ubuntu and can be accessed from terminal. But i found difficulty to write programs in editor and run from terminal. I need GUI Before this i used to run in windows with python IDLE which makes easy to write python codes and run using Run command or pressing F5. Now i want to ask if there is python GUI IDLE equivalent in Ubuntu. Please help. -- Regards, Ratna P Banjara _______________________ ????????????andr?s chand?a P No imprima innecesariamente. ?Cuide el medio ambiente! -------------- next part -------------- An HTML attachment was scrubbed... URL: From andres at chandia.net Wed Apr 6 12:48:09 2011 From: andres at chandia.net (=?iso-8859-1?Q?=22Andr=E9s_Chand=EDa=22?=) Date: Wed, 6 Apr 2011 12:48:09 +0200 Subject: [Tutor] GUI IDLE for UBUNTU 10 In-Reply-To: <00c34903d50664219a1eb84a75727725.squirrel@mail.chandia.net> References: <00c34903d50664219a1eb84a75727725.squirrel@mail.chandia.net> Message-ID: <000de8c47d68951ad1d13aac1c037d8d.squirrel@mail.chandia.net> Sorry, the command is Crtl+F9, not only F9 On Wed, April 6, 2011 12:43, "Andr?s Chand?a" wrote: Actually the default text editor in Ubuntu, "gedit" has a plugin named Python console, that you can activate at "edit > preferences" menu, then at the menu "view > inferior subwindow" (F9) you can activate it, maybe the menu names are not exact, because I'm translating from catalan. Good luck! On Wed, April 6, 2011 11:34, Ratna Banjara wrote: As i know python comes as default in ubuntu and can be accessed from terminal. But i found difficulty to write programs in editor and run from terminal. I need GUI Before this i used to run in windows with python IDLE which makes easy to write python codes and run using Run command or pressing F5. Now i want to ask if there is python GUI IDLE equivalent in Ubuntu. Please help. -- Regards, Ratna P Banjara _______________________ andr?s chand?a P No imprima innecesariamente. ?Cuide el medio ambiente! _______________________ ????????????andr?s chand?a P No imprima innecesariamente. ?Cuide el medio ambiente! -------------- next part -------------- An HTML attachment was scrubbed... URL: From thegreentealeaf at gmail.com Wed Apr 6 13:26:51 2011 From: thegreentealeaf at gmail.com (The Green Tea Leaf) Date: Wed, 6 Apr 2011 13:26:51 +0200 Subject: [Tutor] Showing/hiding widgets in Tkinter In-Reply-To: References: Message-ID: >> According to the documentation I've read I should be able to use >> 'place()' after having used 'place_forget()' to show the label at the >> same place. > > Where did you read that? I only found > > """ > If the configuration of a window has been retrieved with place info, that > configuration can be restored later by first using place forget to erase any > existing information for the window and then invoking place configure with > the saved information. > """ > > at http://www.tcl.tk/man/tcl8.5/TkCmd/place.htm The docs I've found are rather sketchy on almost everything, but I - perhaps wrongly - interpreted the text at http://books.google.com/books?id=JnR9hQA3SncC&lpg=PA445&ots=Jb1TEw-42A&dq=tkinter%20place_forget&pg=PA445#v=onepage&q=place_forget&f=false to mean that I would be able to do this. An alternative way of interpreting this (and other texts) is that I should be able to show it again by using the place command with the same parameters ... but that doesn't work either. > which implies that tk does not store the placement information > automatically. Assuming that Python's Tkinter behaves the same way you can > write > > def toggle(): > ? ?if mylabel.visible: > ? ? ? ?mylabel.pi = mylabel.place_info() > ? ? ? ?mylabel.place_forget() > ? ?else: > ? ? ? ?mylabel.place(mylabel.pi) > ? ?mylabel.visible = not mylabel.visible Unfortunately, it doesn't work. I can see the label flashing when I press the button but it's not visible unless I press the button again. -- The Green Tea Leaf?? thegreentealeaf at gmail.com?? thegreentealeaf.blogspot.com From joel.goldstick at gmail.com Wed Apr 6 14:30:17 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 6 Apr 2011 08:30:17 -0400 Subject: [Tutor] (sqlite3) Testing if a table has been created. In-Reply-To: <319878.23447.qm@web130203.mail.mud.yahoo.com> References: <319878.23447.qm@web130203.mail.mud.yahoo.com> Message-ID: On Tue, Apr 5, 2011 at 9:59 PM, michael scott wrote: > Hello guys, > > Since sqlite gives an error if you try to create a table that's already > there, how do I test if a table is already present? > > > for example in > > def database(info): > import sqlite3 > > connection = sqlite3.connect("test.db") > cursor = connection.cursor() > if table not in test.db: #with this being my test that I'm not sure how > to implement > cursor.execute(""" CREATE TABLE stuff (id INTEGER PRIMARY KEY, name > TEXT)""") > cursor.execute("""INSERT INTO stuff VALUES (null, ?)""",(info)) > cursor.commit() > cursor.close() > connection.close() > > > How would I properly test if table not in test.db: ? Is it something as > simple as having a method of cursor check it for me, or should I just create > my table in the beginning of my code(outside of this function) and leave it > out of the function all together, so I can just have my function focusing on > inserting data? > > Uhm, in the immediate example I'm using, this is a function, thats inside > of a function used by a tkinter button, a save button if you will. So I want > it to save whatever is in the entry widget to the database. Keeping this in > mind, am I going about it the wrong way? Should I be trying to save a > different way? > > > > > > > ---- > What is it about you... that intrigues me so? > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > Is this really a python tutor question? Oh, well, try this: http://lmgtfy.com/?q=sqlite+test+if+table+exists -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Wed Apr 6 15:35:55 2011 From: __peter__ at web.de (Peter Otten) Date: Wed, 06 Apr 2011 15:35:55 +0200 Subject: [Tutor] Showing/hiding widgets in Tkinter References: Message-ID: The Green Tea Leaf wrote: > > which implies that tk does not store the placement information > > automatically. Assuming that Python's Tkinter behaves the same way you can > > write > > > > def toggle(): > > if mylabel.visible: > > mylabel.pi = mylabel.place_info() > > mylabel.place_forget() > > else: > > mylabel.place(mylabel.pi) > > mylabel.visible = not mylabel.visible > > Unfortunately, it doesn't work. I can see the label flashing when I > press the button but it's not visible unless I press the button again. I don't understand that sentence. If you press the button the label should disappear. When you press it again it should become visible again. I added some noise to your initial script and saved the placement state: import sys import Tkinter as tk def toggle(): if mylabel.visible: btnToggle["text"] = "Show Example" print "Now you don't" mylabel.place_forget() else: mylabel.place(mylabel.pi) print "Now you see it" btnToggle["text"] = "Hide Example" mylabel.visible = not mylabel.visible root = tk.Tk() print "TkVersion", tk.TkVersion print "TclVersion", tk.TclVersion print "Python version", sys.version_info mylabel = tk.Label(text="Example") mylabel.visible = True mylabel.place(x=20, y=50) mylabel.pi = mylabel.place_info() btnToggle = tk.Button(text="Hide Example", command=toggle) btnToggle.place(x=70, y=150) root.mainloop() That does what it's expected to do over here. From jigenbakuda at yahoo.com Wed Apr 6 16:06:58 2011 From: jigenbakuda at yahoo.com (michael scott) Date: Wed, 6 Apr 2011 07:06:58 -0700 (PDT) Subject: [Tutor] (sqlite3) Testing if a table has been created. Message-ID: <420951.30542.qm@web130222.mail.mud.yahoo.com> ________________________________ From: Joel Goldstick To: michael scott Cc: tutor at python.org Sent: Wed, April 6, 2011 8:30:17 AM Subject: Re: [Tutor] (sqlite3) Testing if a table has been created. On Tue, Apr 5, 2011 at 9:59 PM, michael scott wrote: Hello guys, > >Since sqlite gives an error if you try to create a table that's already there, >how do I test if a table is already present? > > >for example in > >def database(info): > import sqlite3 > > connection = sqlite3.connect("test.db") > cursor = connection.cursor() > if table not in test.db: #with this being my test that I'm not sure how to >implement > cursor.execute(""" CREATE TABLE stuff (id INTEGER PRIMARY KEY, name >TEXT)""") > cursor.execute("""INSERT INTO stuff VALUES (null, ?)""",(info)) > cursor.commit() > cursor.close() > connection.close() > > >How would I properly test if table not in test.db: ? Is it something as simple >as having a method of cursor check it for me, or should I just create my table >in the beginning of my code(outside of this function) and leave it out of the >function all together, so I can just have my function focusing on inserting >data? > >Uhm, in the immediate example I'm using, this is a function, thats inside of a >function used by a tkinter button, a save button if you will. So I want it to >save whatever is in the entry widget to the database. Keeping this in mind, am I >going about it the wrong way? Should I be trying to save a different way? > > > > > > >---- >What is it about you... that intrigues me so? > > >_______________________________________________ >Tutor maillist - Tutor at python.org >To unsubscribe or change subscription options: >http://mail.python.org/mailman/listinfo/tutor > > Is this really a python tutor question? Oh, well, try this: http://lmgtfy.com/?q=sqlite+test+if+table+exists -- Joel Goldstick My apologies, I was not aware that there were questions I could and could not ask. I understand now that this is an unnacceptible question. But could you tell me why? Was it too simple in nature? Too difficult? Did I violate some rule in my question formatting? This was not homework or anything like that. I went back to the tutor website to make sure I did not blatantly break one of the rules. I only found this regarding participation. About Tutor English (USA) This list is for folks who want to ask questions regarding how to learn computer programming with the Python language. Python (http://www.python.org/) is a programming language which many feel is a good first language, because it makes it easy to express the fundamental concepts of programming such as data structures and algorithms with a syntax which many find easy to read and write. Folks interested in learning about programming with Python are encouraged to join, as are folks interested in helping others learn. While the list is called tutor, anyone, whether novice or expert, can answer questions. If individuals wish to start off-line conversations about a particular concept and become one-on-one tutor/tutee, that's fine. If either party wants to summarize what they learned for others to benefit, that's fine too. There is a searchable interface to archived Tutor messages on Activestate's web site and another one at Gmane. There are many on-line resources that can help you get started with Python. See the Beginners Guide for a list of some good ones. To see the collection of prior postings to the list, visit the Tutor Archives. So that I can avoid posting questions that don't belong on the tutor list, or so I can have a clearer picture of what a python tutor question is, could someone please help me? -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreengels at gmail.com Wed Apr 6 16:19:53 2011 From: andreengels at gmail.com (Andre Engels) Date: Wed, 6 Apr 2011 16:19:53 +0200 Subject: [Tutor] (sqlite3) Testing if a table has been created. In-Reply-To: <420951.30542.qm@web130222.mail.mud.yahoo.com> References: <420951.30542.qm@web130222.mail.mud.yahoo.com> Message-ID: On Wed, Apr 6, 2011 at 4:06 PM, michael scott wrote: > Is this really a python tutor question? Oh, well, try this: > http://lmgtfy.com/?q=sqlite+test+if+table+exists > > -- > Joel Goldstick > > > My apologies, I was not aware that there were questions I could and could > not ask. I understand now that this is an unnacceptible question. But could > you tell me why? Was it too simple in nature? Too difficult? Did I violate > some rule in my question formatting? This was not homework or anything like > that. I went back to the tutor website to make sure I did not blatantly > break one of the rules. I only found this regarding participation. > I think Joel's objection is that your question is not really about Python at all, but about SQLite, -- Andr? Engels, andreengels at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From jigenbakuda at yahoo.com Wed Apr 6 16:38:11 2011 From: jigenbakuda at yahoo.com (michael scott) Date: Wed, 6 Apr 2011 07:38:11 -0700 (PDT) Subject: [Tutor] (sqlite3) Testing if a table has been created. In-Reply-To: References: <420951.30542.qm@web130222.mail.mud.yahoo.com> Message-ID: <481554.89046.qm@web130208.mail.mud.yahoo.com> ________________________________ From: Andre Engels To: michael scott Cc: tutor at python.org Sent: Wed, April 6, 2011 10:19:53 AM Subject: Re: [Tutor] (sqlite3) Testing if a table has been created. On Wed, Apr 6, 2011 at 4:06 PM, michael scott wrote: Is this really a python tutor question? Oh, well, try this: http://lmgtfy.com/?q=sqlite+test+if+table+exists > >-- >Joel Goldstick > > >My apologies, I was not aware that there were questions I could and could not >ask. I understand now that this is an unnacceptible question. But could you tell >me why? Was it too simple in nature? Too difficult? Did I violate some rule in >my question formatting? This was not homework or anything like that. I went >back to the tutor website to make sure I did not blatantly break one of the >rules. I only found this regarding participation. > I think Joel's objection is that your question is not really about Python at all, but about SQLite, -- Andr? Engels, andreengels at gmail.com Oh I see. That makes sense. -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Wed Apr 6 17:06:16 2011 From: emile at fenx.com (Emile van Sebille) Date: Wed, 06 Apr 2011 08:06:16 -0700 Subject: [Tutor] Rhythmbox python plugin to capture middle click event In-Reply-To: References: Message-ID: On 4/5/2011 10:10 PM Lachlan d said... > I've been working on some python rhythmbox plugins for the past few > months and now i've decided to try writing my own. You'll get a much better answer if this is asked of other rhythmbox developers. This tutor list in more suited for those just learning to program in python. You can browse at http://osdir.com/ml/rhythmbox-devel/ and subscribe at http://mail.gnome.org/mailman/listinfo/rhythmbox-devel HTH, Emile > I've been able to get actions working correctly in my other plugin. > (http://launchpad.net/rb-fileorganizer) but that uses buttons and a > gui i built rather than mouse clicks. > > What i'm trying to create is a plugin that will perform and action > every time the middle mouse button is clicked in rhythmbox. I haven't > been able to find any solid information about doing this on the net. > > The plugin will load but i don't think anything in capture_click is correct. > Any help getting this to just print the test message in the console > would be greatly appreciated! > > Here's my code that i've written up so far: > > class middleclick(rb.Plugin): > > def __init__(self): > rb.Plugin.__init__(self) > > # Rhythmbox standard Activate method > def activate(self, shell): > self.shell = shell > self.capture_click(shell) > > # Rhythmbox standard Deactivate method > def deactivate(self, shell): > self.shell = None > > # Run test_plugin for middle click > def capture_click(self, shell): > self.action = gtk.Action('MiddleClick', _('Middle Click'), > _('Action on Middle Click'), gtk.gdk.BUTTON_PRESS_MASK) > self.action.connect('activate', self.test_plugin, shell) > self.action_group = gtk.ActionGroup('OnClickActions') > self.action_group.add_action(self.action) > uim = shell.get_ui_manager() > uim.insert_action_group(self.action_group, 0) > uim.ensure_update() > > def test_plugin(self, shell): > if event.button == 2: > print 'THIS IS AN EVENT' > else > print 'WRONG EVENT' > _______________________________________________ > 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 Wed Apr 6 17:58:37 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 6 Apr 2011 11:58:37 -0400 Subject: [Tutor] (sqlite3) Testing if a table has been created. In-Reply-To: <481554.89046.qm@web130208.mail.mud.yahoo.com> References: <420951.30542.qm@web130222.mail.mud.yahoo.com> <481554.89046.qm@web130208.mail.mud.yahoo.com> Message-ID: On Wed, Apr 6, 2011 at 10:38 AM, michael scott wrote: > > > ------------------------------ > *From:* Andre Engels > > *To:* michael scott > *Cc:* tutor at python.org > *Sent:* Wed, April 6, 2011 10:19:53 AM > > *Subject:* Re: [Tutor] (sqlite3) Testing if a table has been created. > > On Wed, Apr 6, 2011 at 4:06 PM, michael scott wrote: > >> Is this really a python tutor question? Oh, well, try this: >> http://lmgtfy.com/?q=sqlite+test+if+table+exists >> >> -- >> Joel Goldstick >> >> >> My apologies, I was not aware that there were questions I could and could >> not ask. I understand now that this is an unnacceptible question. But could >> you tell me why? Was it too simple in nature? Too difficult? Did I violate >> some rule in my question formatting? This was not homework or anything like >> that. I went back to the tutor website to make sure I did not blatantly >> break one of the rules. I only found this regarding participation. >> > > > I think Joel's objection is that your question is not really about Python > at all, but about SQLite, > > -- > Andr? Engels, andreengels at gmail.com > > > > Oh I see. That makes sense. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > My apologies. I was not so nice. I needed coffee! I'm a big reader of this group. I think its great. Sometimes I have answers. And I learn a lot. I was just meaning to point out that its best to have a specific python question and include the code you tried -- including the traceback so people can help you. And, maybe its just me, but if you can do a little research first, it adds to a better discussion. -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From deyungchou at centurylink.net Wed Apr 6 11:03:28 2011 From: deyungchou at centurylink.net (JOHN KELLY) Date: Wed, 6 Apr 2011 05:03:28 -0400 (EDT) Subject: [Tutor] RE Message-ID: <1217308688.563760.1302080608346.JavaMail.root@md29.embarq.synacor.com> I need help. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Apr 6 19:27:05 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 6 Apr 2011 18:27:05 +0100 Subject: [Tutor] (sqlite3) Testing if a table has been created. References: <420951.30542.qm@web130222.mail.mud.yahoo.com> Message-ID: "michael scott" wrote > > Is this really a python tutor question? Oh, well, try this: > > http://lmgtfy.com/?q=sqlite+test+if+table+exists > > My apologies, I was not aware that there were questions I could and > could not > ask. The only issue is whether it is relevant to the group. Python tutor is about teaching people to program in Python. SqlLite is in the grey area of acceprtability because although it is available as part of the Python standard library most questions tend to be about general SQL issues rather than Python. In practice straighforward beginner type questions will be answered here, more SQL specific issues will be redirected to a general SQL site or to the specific database forum. > I can have a clearer picture of what a python tutor question is, > could someone please help me? Mainly if its about the Python programming language or general program design type issues it is appropriate here. If it's about how to use the Python standard library modules (including accessing SqLite from Python) then thats OK too. The more you digress into non standard or non Python issues the less appropriate it is for this list. HTH, Alan G. List moderator From steve at alchemy.com Wed Apr 6 19:28:21 2011 From: steve at alchemy.com (Steve Willoughby) Date: Wed, 06 Apr 2011 10:28:21 -0700 Subject: [Tutor] RE In-Reply-To: <1217308688.563760.1302080608346.JavaMail.root@md29.embarq.synacor.com> References: <1217308688.563760.1302080608346.JavaMail.root@md29.embarq.synacor.com> Message-ID: <4D9CA2B5.8090007@alchemy.com> On 06-Apr-11 02:03, JOHN KELLY wrote: > I need help. Can you be a little more specific? :) -- Steve Willoughby / steve at alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 48A3 2621 E72C 31D9 2928 2E8F 6506 DB29 54F7 0F53 From motoom at xs4all.nl Thu Apr 7 00:56:55 2011 From: motoom at xs4all.nl (Michiel Overtoom) Date: Thu, 07 Apr 2011 00:56:55 +0200 Subject: [Tutor] RE In-Reply-To: <1217308688.563760.1302080608346.JavaMail.root@md29.embarq.synacor.com> References: <1217308688.563760.1302080608346.JavaMail.root@md29.embarq.synacor.com> Message-ID: <4D9CEFB7.1060004@xs4all.nl> On 2011-04-06 11:03, JOHN KELLY wrote: > I need help. In that case, start with http://wiki.python.org/moin/BeginnersGuide -- "Lots of people have brilliant ideas every day, but they often disappear in the cacophony of life that we muddle through." - Evan Jenkins, http://arstechnica.com/author/ohrmazd/ From mast.ratna at gmail.com Thu Apr 7 06:34:13 2011 From: mast.ratna at gmail.com (Ratna Banjara) Date: Thu, 7 Apr 2011 10:19:13 +0545 Subject: [Tutor] Platform Independence in Python Message-ID: Hello all, I was learning GUI in python and found dissimilarities while importing 'tkinter' module. In windows we should write =>import tkinter while in linux, we should write =>import Tkinter Difference is Capital ' T '. Means same code cannot run on both platform , how can we adjust this issue? -- Regards, http://www.rat32.com Ratna P Banjara -------------- next part -------------- An HTML attachment was scrubbed... URL: From ranjithtenz at gmail.com Thu Apr 7 06:39:40 2011 From: ranjithtenz at gmail.com (Ranjith Kumar) Date: Thu, 7 Apr 2011 10:09:40 +0530 Subject: [Tutor] Platform Independence in Python In-Reply-To: References: Message-ID: Hi Ratna, I hope this link will help http://www.java2s.com/Code/Python/GUI-Tk/AlarmDemo.htm On Thu, Apr 7, 2011 at 10:04 AM, Ratna Banjara wrote: > Hello all, > > I was learning GUI in python and found dissimilarities while importing > 'tkinter' module. > In windows we should write > =>import tkinter > > while in linux, we should write > =>import Tkinter > > Difference is Capital ' T '. Means same code cannot run on both platform , > how can we adjust this issue? > > > -- > Regards, > http://www.rat32.com > Ratna P Banjara > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Cheers Ranjith, Research Developer, Sedin Technologies, Chennai http://ranjith10z.wordpress.com http://ranjithtenz.wordpress.com http://railsfactory.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Thu Apr 7 07:15:54 2011 From: steve at alchemy.com (Steve Willoughby) Date: Wed, 06 Apr 2011 22:15:54 -0700 Subject: [Tutor] Platform Independence in Python In-Reply-To: References: Message-ID: <4D9D488A.6090603@alchemy.com> On 06-Apr-11 21:39, Ranjith Kumar wrote: > On Thu, Apr 7, 2011 at 10:04 AM, Ratna Banjara > wrote: > In windows we should write > =>import tkinter > > while in linux, we should write > =>import Tkinter Actually, you should do the same thing on both platforms. Are you running the same code on both platforms? The correct name is "Tkinter" (capital T) for Python 2.x, and "tkinter" (lower-case) for Python 3.x, regardless of platform. -- Steve Willoughby / steve at alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 48A3 2621 E72C 31D9 2928 2E8F 6506 DB29 54F7 0F53 From alan.gauld at btinternet.com Thu Apr 7 10:13:58 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 7 Apr 2011 09:13:58 +0100 Subject: [Tutor] Platform Independence in Python References: Message-ID: "Ratna Banjara" wrote > In windows we should write > =>import tkinter > > while in linux, we should write > =>import Tkinter > The difference is not the Operating System but the Python version. Version 3 has many incompatibilities with version 2. This is one of them so it looks like you have v3 on Windows and v2 on Linux. Either downgrade the Windows version to 2.7 or upgrade Linux to v3. For production code I'd suggest you downgrade Windows to 2.7, v3 is still missing a few important 3rd party libraries HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From thegreentealeaf at gmail.com Thu Apr 7 12:44:27 2011 From: thegreentealeaf at gmail.com (The Green Tea Leaf) Date: Thu, 7 Apr 2011 12:44:27 +0200 Subject: [Tutor] Showing/hiding widgets in Tkinter In-Reply-To: References: Message-ID: On Wed, Apr 6, 2011 at 15:35, Peter Otten <__peter__ at web.de> wrote: >> Unfortunately, it doesn't work. I can see the label flashing when I >> press the button but it's not visible unless I press the button again. > > I don't understand that sentence. If you press the button the label should > disappear. When you press it again it should become visible again. What happened yesterday was (assuming initial state when the label was visible) + I clicked the button + The label disappeared + I clicked the button again + Noting became visible + I clicked the button + Nothing became visible Then, getting a bit frustrated, I started to repeatedly click the button and discovered that I could actually see the label when I the button pressed (that is, I was holding down the mouse button) but not when it was released. > That does what it's expected to do over here. This works just fine today ... (sigh, I hate when things work one day but not an other day) ------------------ I suddenly thought about one thing that I tested and my guess is that the window needs to refresh to show the label that was hidden. I comment out the line btnToggle["text"] = "Hide Example" then I get the same behavior as yesterday. -- The Green Tea Leaf?? thegreentealeaf at gmail.com?? thegreentealeaf.blogspot.com From alan.gauld at btinternet.com Thu Apr 7 19:18:04 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 7 Apr 2011 18:18:04 +0100 Subject: [Tutor] Showing/hiding widgets in Tkinter References: Message-ID: "The Green Tea Leaf" wrote > I suddenly thought about one thing that I tested and my > guess is that the window needs to refresh to show the label Thats a common issue with GUIs. You can force a refresh in Tk with the update() method. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From ben at hetnieuwestemmen.nl Thu Apr 7 23:45:51 2011 From: ben at hetnieuwestemmen.nl (Ben Teeuwen) Date: Thu, 7 Apr 2011 23:45:51 +0200 Subject: [Tutor] installing where does my money go Message-ID: Hi everyone, I'm a total newbie giving his best shot at visualising local educational institution's faculty budget (over 60 million) to stir up some healthy democratic debate, by trying to adapt the code from http://wheredoesmymoneygo.org/getting-started/. Its open source, so I'm trying out how far I'll wind up :). I'm installing the setup below (see http://wheredoesmymoneygo.org/getting-started/). I've got a mac os 10.6.7, python 2.7.1, pip, and the most recent postgres installation. I get stuck at; "Run setup.py to install all required local packages. (Needs more details...)" bteeuwen at Ben-3 ~/Sites/wdmmg]$./setup.py from: can't read /var/mail/setuptools from: can't read /var/mail/wdmmg ./setup.py: line 4: syntax error near unexpected token `newline' ./setup.py: line 4: `setup(' Then I added this to setup.py: #!/usr/bin/python This is where I end: bteeuwen at Ben-3 ~/Sites/wdmmg]$./setup.py /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/distutils/dist.py:266: UserWarning: Unknown distribution option: 'paster_plugins' warnings.warn(msg) usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: setup.py --help [cmd1 cmd2 ...] or: setup.py --help-commands or: setup.py cmd --help Anyone any advice where to look for answers? Thx!! Ben ______________________________________________________________________________ sInstallation and Setup ====================== Steps to set up WDMMG from scratch. May not be comprehensive, please edit. -------------- Install Postgres (or any other sqlalchemy compatible DB) on your machine. Create a new database called 'production', add a superuser: note down the username and password. $ sudo -u postgres createuser -P nameofuser $ sudo -u postgres createdb --owner nameofuser nameofdb -------------- Check out wdmmg from the Mercurial repository. $ hg clone http://knowledgeforge.net/okfn/wdmmg [OUTDATED: For info: This will create a "wdmmg" directory with everything in it. Inside, you will find: - "doc": self-explanatory. - "econdata": source code for some fo our data packages. - "wdmmg": source code for the data store. - "wdmmgrdf": version of the data store with an RDF backend (dormant). - "flash": source code for the dashboard. Inside "wdmmg/wdmmg" you will find a pretty standard Pylons application. Thex main part is a Python package called (you guessed it) "wdmmg". So the actual code is inside "wdmmg/wdmmg".] -------------- Run setup.py to install all required local packages. (Needs more details...) -------------- Install 'wdmmg' using pip. NB {your-pyenv] here means 'the location of your virtualenv if you have one':: $ pip -E {your-pyenv} install -r pip-requirements.txt -------------- Create a config file called development.ini (this has the config options needed to run the site locally): $ paster make-config wdmmg development.ini -------------- Edit development.ini with Solr and SQLAlchemy details for your local machine: solr.url = url of remote Solr script (can be found in .ini files on servers), or just 'stub' if you prefer sqlalchemy.url = postgres://username:password at localhost/production -------------- Sync the database tables and set up the application: $ paster setup-app development.ini -------------- For data store theme: Get main wdmmg theme files from the mercurial repository at:: http://bitbucket.org/okfn/wdmmg-wp-theme And put them at:: wdmmg/public/themes/wdmmg -------------- Install some data (not sure if this really belongs here?) $ chmod a+x install_data.sh $ ./install_data.sh -------------- Run tests, edit anything that is broken:: $ nosetests -------------- Load fixtures so you have some sample data:: $ paster fixtures setup [ Alternatively, if you want the full datasets, run the install_data script (slow):: $ chmod a+x install_data.sh $ ./install_data.sh ] -------------- Finally, run the site from development.ini:: $ paster serve --reload development.ini -------------- Start hacking! Trac repository: http://knowledgeforge.net/okfn/tasks/query?status=assigned&status=new&status=reopened&component=projects.wdmmg&order=priority&col=id&col=summary&col=cc&col=status&col=owner&col=type&col=priority How to Upgrade Production Service ================================= 3 dbs/systems: * data.wheredoesmymoneygo.org - P1 * data.wheredoesmymoneygo.org.2 - P2 * data.staging.wheredoesmymoneygo.org - S1 Suppose P1 = active production, P2 = inactive production * Shut down write to the main system (Hack way: LimitExcept GET in Apache) * Dump active production db and load into inactive production db * Upgrade inactive system and set to use inactive production db * Use it and test it * Switch over from P1 to P2 * In apache move wsgi script to point to the other one and reboot apache2 * If this fails just switch back and you are operational again From emile at fenx.com Fri Apr 8 02:34:47 2011 From: emile at fenx.com (Emile van Sebille) Date: Thu, 07 Apr 2011 17:34:47 -0700 Subject: [Tutor] installing where does my money go In-Reply-To: References: Message-ID: On 4/7/2011 2:45 PM Ben Teeuwen said... > Then I added this to setup.py: > #!/usr/bin/python The normal way to run setup like this is: python setup.py install setup.py typically installs based on the environment your target python version provides. You can have multiple python versions installed on the same machine and can run setup.py from each version. > > This is where I end: > bteeuwen at Ben-3 ~/Sites/wdmmg]$./setup.py > /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/distutils/dist.py:266: UserWarning: Unknown distribution option: 'paster_plugins' > warnings.warn(msg) > usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] --------------------------------^^^^ You're missing the command -- try install hth, Emile > or: setup.py --help [cmd1 cmd2 ...] > or: setup.py --help-commands > or: setup.py cmd --help > > Anyone any advice where to look for answers? Thx!! > From charlze at sohu.com Fri Apr 8 05:58:16 2011 From: charlze at sohu.com (leechau) Date: Fri, 08 Apr 2011 11:58:16 +0800 Subject: [Tutor] How to use a module when only import package Message-ID: <4D9E87D8.7080801@sohu.com> I wrote module1 in package1, and want to use a method named 'method1' in module1, the caller(test.py) is like this: import package1 package1.module1.method1() module1.py is like this: def method1(): print 'method1 run!' The filesystem structure is: test.py package1 |__ __init__.py |__ module1.py When i run test.py, the output is: AttributeError: 'module' object has no attribute 'module1' File "e:\MyDoc\GODU_BVT\test.py", line 2, in package1.module1.method1() If test.py is modified to: import package1.module1 ... then everything goes well. Python documentation said: "Contrarily, when using syntax like import item.subitem.subsubitem, each item except for the last must be a package; the last item can be a module or a package but can?t be a class or function or variable defined in the previous item." Obviously we can import a package besides a module, so i don't know why the "import package1" style does not work. Above codes tested on python 2.6.6, windows xp sp2. Thanks for explanations :) From steve at pearwood.info Fri Apr 8 06:16:01 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 08 Apr 2011 14:16:01 +1000 Subject: [Tutor] How to use a module when only import package In-Reply-To: <4D9E87D8.7080801@sohu.com> References: <4D9E87D8.7080801@sohu.com> Message-ID: <4D9E8C01.6030200@pearwood.info> leechau wrote: > I wrote module1 in package1, and want to use a method named 'method1' in > module1, the caller(test.py) is like this: > > import package1 > package1.module1.method1() [...] > When i run test.py, the output is: > AttributeError: 'module' object has no attribute 'module1' > File "e:\MyDoc\GODU_BVT\test.py", line 2, in > package1.module1.method1() > > If test.py is modified to: > import package1.module1 > ... > then everything goes well. Yes, that is correct, and that is a deliberate design. What if your package had a 1000 sub-modules, each of which were big? You wouldn't want loading the main package to automatically load all 1000 sub-modules, if you only needed 1. You either import the sub-module by hand: import package1.module1 and now you can use package1.module1.method1 (not really a method, actually a function). If you want module1 to automatically be available after importing the package, include one of these in the package1 __init__.py file: import module1 # should work in Python 2 and now package1 will include the module1 in its namespace. -- Steven From brownam at gmail.com Fri Apr 8 03:57:53 2011 From: brownam at gmail.com (Aaron Brown) Date: Thu, 7 Apr 2011 21:57:53 -0400 Subject: [Tutor] Help needed Message-ID: I am in an online python class and am failing badly. I am not sure where the problem is here but any insight would be great. def main(): while (True): allowed = int(input("Please enter minutes allowed between 100 and 700: ")) used = int(input("How many minutes were used: ")) totalOver = used - allowed totalDue = (64.95 + (0.15*totalOver)) if(totalOver > 0): print("You were over your minutes by " + str(totalOver)) else: totalOver = 0 print("You were not over your minutes for the month") print ("Do you want to end program? Enter yes or no:") toEnd = raw_input() if toEnd == "yes": print("MONTHLY USE REPORT") print("Minutes allowed were " + str(allowed)) print("Minutes used were " + str(used)) print("Minutes over were " + str(totalOver)) print("Total due is $ " + str(totalDue(totalOver)) I keep getting a syntax error in a blank line at the bottom. I have tried to end it with main() but it errors on the main as well? Help Please, Aaron Brown -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreengels at gmail.com Fri Apr 8 09:03:33 2011 From: andreengels at gmail.com (Andre Engels) Date: Fri, 8 Apr 2011 09:03:33 +0200 Subject: [Tutor] Help needed In-Reply-To: References: Message-ID: On Fri, Apr 8, 2011 at 3:57 AM, Aaron Brown wrote: > I am in an online python class and am failing badly.? I am not sure where > the problem is here but any insight would be great. > > def main(): > ??? while (True): > ??????? allowed = int(input("Please enter minutes allowed between 100 and > 700: ")) > ??????? used = int(input("How many minutes were used: ")) > ??????? totalOver = used - allowed > ??????? totalDue = (64.95 + (0.15*totalOver)) > ??????? if(totalOver > 0): > ??????????? print("You were over your minutes by " + str(totalOver)) > ??????? else: > ??????????? totalOver = 0 > ??????????? print("You were not over your minutes for the month") > ??????????? print ("Do you want to end program? Enter yes or no:") > ??????????? toEnd = raw_input() > ??????????? if toEnd == "yes": > ??????????????? print("MONTHLY USE REPORT") > ??????????????? print("Minutes allowed were " + str(allowed)) > ??????????????? print("Minutes used were " + str(used)) > ??????????????? print("Minutes over were " + str(totalOver)) > ??????????????? print("Total due is $ " + str(totalDue(totalOver)) > > I keep getting a syntax error in a blank line at the bottom.? I have tried > to end it with main() but it errors on the main as well? If you get a syntax error, the problem almost always is in the line shown or the line directly above it. A blank line at the end is not a syntax error, so in this case it is the line above it: print("Total due is $ " + str(totalDue(totalOver)) This line has three left brackets but only two right brackets. Add one right bracket and your program should run (however, it will not work correctly - in the above line you try to call totalDue, but it is a number, not a function or method). -- Andr? Engels, andreengels at gmail.com From alan.gauld at btinternet.com Fri Apr 8 09:05:26 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 8 Apr 2011 08:05:26 +0100 Subject: [Tutor] Help needed References: Message-ID: "Aaron Brown" wrote >I am in an online python class and am failing badly. I am not sure >where > the problem is here but any insight would be great. When posting always include the full error text since it usually helps locate the precise location more clearly than a verbal description or summary. > def main(): > while (True): How do you intend to exit? I don't see any return or break statements? But thats not the immediate issue.... > allowed = int(input("Please enter minutes allowed between 100 > and > 700: ")) > used = int(input("How many minutes were used: ")) > totalOver = used - allowed > totalDue = (64.95 + (0.15*totalOver)) > if(totalOver > 0): > print("You were over your minutes by " + str(totalOver)) You don;t need to call str() because print can do that for you. All you need is: print("You were over your minutes by ", totalOver) > else: > totalOver = 0 > print("You were not over your minutes for the month") > print ("Do you want to end program? Enter yes or no:") > toEnd = raw_input() Most of the code looks like Python v3 but this line is from Pyhon v2... raw_input has been replaced by input() in v3. However, that should generate a NameError not a SyntaxError. > if toEnd == "yes": > print("MONTHLY USE REPORT") > print("Minutes allowed were " + str(allowed)) > print("Minutes used were " + str(used)) > print("Minutes over were " + str(totalOver)) > print("Total due is $ " + str(totalDue(totalOver)) > > I keep getting a syntax error in a blank line at the bottom. I have > tried > to end it with main() but it errors on the main as well? The only probblem that jumps out at me is the raw_input() but that would not be a syntax error... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From cwitts at compuscan.co.za Fri Apr 8 09:05:35 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Fri, 08 Apr 2011 09:05:35 +0200 Subject: [Tutor] Help needed In-Reply-To: References: Message-ID: <4D9EB3BF.8080502@compuscan.co.za> On 08/04/2011 03:57, Aaron Brown wrote: > I am in an online python class and am failing badly. I am not sure > where the problem is here but any insight would be great. > def main(): > while (True): > allowed = int(input("Please enter minutes allowed between 100 > and 700: ")) > used = int(input("How many minutes were used: ")) > totalOver = used - allowed > totalDue = (64.95 + (0.15*totalOver)) > if(totalOver > 0): > print("You were over your minutes by " + str(totalOver)) > else: > totalOver = 0 > print("You were not over your minutes for the month") > print ("Do you want to end program? Enter yes or no:") > toEnd = raw_input() > if toEnd == "yes": > print("MONTHLY USE REPORT") > print("Minutes allowed were " + str(allowed)) > print("Minutes used were " + str(used)) > print("Minutes over were " + str(totalOver)) > print("Total due is $ " + str(totalDue(totalOver)) > > I keep getting a syntax error in a blank line at the bottom. I have > tried to end it with main() but it errors on the main as well? > Help Please, > Aaron Brown > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Your last line is missing a closing parenthesis resulting in a Syntax Error. -- Kind Regards, Christian Witts From lists at mostrom.pp.se Fri Apr 8 10:54:40 2011 From: lists at mostrom.pp.se (=?iso-8859-1?Q?Jan_Erik_Mostr=F6m?=) Date: Fri, 8 Apr 2011 10:54:40 +0200 Subject: [Tutor] Sound question Message-ID: Hi, A couple of my students need to be able to play sounds, controlling start & stop, play sound from files and if possible generate sinus wave sounds. I looked around and found several packages but they all seem to have some kind platform restrictions. Does anyone have recommendations for what packages to use? I would prefer some cross-platform package for at least Windows and Mac but unix/linux would be a plus. I assume that winsound is the recommended package for Windows only (I'm a Mac person so I don't really know myself) - jem From charlze at sohu.com Fri Apr 8 11:13:47 2011 From: charlze at sohu.com (leechau) Date: Fri, 08 Apr 2011 17:13:47 +0800 Subject: [Tutor] How to use a module when only import package In-Reply-To: References: Message-ID: <4D9ED1CB.80403@sohu.com> Steven wrote: > leechau wrote: >> I wrote module1 in package1, and want to use a method named 'method1' in >> module1, the caller(test.py) is like this: >> >> import package1 >> package1.module1.method1() > [...] >> When i run test.py, the output is: >> AttributeError: 'module' object has no attribute 'module1' >> File "e:\MyDoc\GODU_BVT\test.py", line 2, in >> package1.module1.method1() >> >> If test.py is modified to: >> import package1.module1 >> ... >> then everything goes well. > > Yes, that is correct, and that is a deliberate design. > > What if your package had a 1000 sub-modules, each of which were big? You > wouldn't want loading the main package to automatically load all 1000 > sub-modules, if you only needed 1. > > You either import the sub-module by hand: > > import package1.module1 > > and now you can use package1.module1.method1 (not really a method, > actually a function). If you want module1 to automatically be available > after importing the package, include one of these in the package1 > __init__.py file: > > import module1 # should work in Python 2 > > > and now package1 will include the module1 in its namespace. > > > -- > Steven Thanks for Steven's exellent and patient explanations. How should I do if automatically import a module in Python 3? Thanks again. -- leechau From ajarncolin at gmail.com Fri Apr 8 11:44:56 2011 From: ajarncolin at gmail.com (col speed) Date: Fri, 8 Apr 2011 16:44:56 +0700 Subject: [Tutor] Sound question In-Reply-To: References: Message-ID: On 8 April 2011 15:54, Jan Erik Mostr?m wrote: > Hi, > > A couple of my students need to be able to play sounds, controlling start & > stop, play sound from files and if possible generate sinus wave sounds. > > I looked around and found several packages but they all seem to have some > kind platform restrictions. Does anyone have recommendations for what > packages to use? I would prefer some cross-platform package for at least > Windows and Mac but unix/linux would be a plus. > > I assume that winsound is the recommended package for Windows only (I'm a > Mac person so I don't really know myself) > > - jem > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Personally, I've found pygame great for playing sounds. -- -------------- next part -------------- An HTML attachment was scrubbed... URL: From emmanuel.ruellan at laposte.net Fri Apr 8 12:15:23 2011 From: emmanuel.ruellan at laposte.net (Emmanuel Ruellan) Date: Fri, 8 Apr 2011 12:15:23 +0200 Subject: [Tutor] Sound question In-Reply-To: References: Message-ID: On Fri, Apr 8, 2011 at 10:54 AM, Jan Erik Mostr?m wrote: > > > A couple of my students need to be able to play sounds, controlling start & > stop, play sound from files and if possible generate sinus wave sounds. > I've used Snack to generate sounds on both Windows and Linux. http://www.speech.kth.se/snack/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From ranjithtenz at gmail.com Fri Apr 8 13:52:35 2011 From: ranjithtenz at gmail.com (Ranjith Kumar) Date: Fri, 8 Apr 2011 17:22:35 +0530 Subject: [Tutor] NLP Message-ID: Hi all, Can anyone suggest me any best Natural Language Processing in python other than nltk. -- Cheers, Ranjith Kumar K, Chennai. http://ranjithtenz.wordpress.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From cory at teshera.net Fri Apr 8 20:29:19 2011 From: cory at teshera.net (Cory Teshera-Sterne) Date: Fri, 8 Apr 2011 14:29:19 -0400 Subject: [Tutor] Evaluating program running time? Message-ID: Hi all, I have a small(ish) Python program, and I need to be able to log the running time. This isn't something I've ever really encountered, and I've been led to believe it can be a little hairy. Are there any Python-specific approaches to this? I found the "timeit" module, but that doesn't seem to be quite what I'm looking for. Thanks for any insight, Cory -- Cory Teshera-Sterne Mount Holyoke College, 2010 www.linkedin.com/in/corytesherasterne -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Fri Apr 8 21:49:00 2011 From: bgailer at gmail.com (bob gailer) Date: Fri, 08 Apr 2011 15:49:00 -0400 Subject: [Tutor] Evaluating program running time? In-Reply-To: References: Message-ID: <4D9F66AC.8000104@gmail.com> On 4/8/2011 2:29 PM, Cory Teshera-Sterne wrote: > Hi all, > > I have a small(ish) Python program, and I need to be able to log the > running time. This isn't something I've ever really encountered, and > I've been led to believe it can be a little hairy. Are there any > Python-specific approaches to this? I found the "timeit" module, but > that doesn't seem to be quite what I'm looking for. I like to use the time module import time start = time.time() rest of program print time.time() - start I believe that gives best precisioni on *nix On Windows use time.clock() )instead. -- Bob Gailer 919-636-4239 Chapel Hill NC From ramit.prasad at jpmchase.com Fri Apr 8 22:02:09 2011 From: ramit.prasad at jpmchase.com (Prasad, Ramit) Date: Fri, 8 Apr 2011 16:02:09 -0400 Subject: [Tutor] Evaluating program running time? In-Reply-To: <4D9F66AC.8000104@gmail.com> References: <4D9F66AC.8000104@gmail.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2D95E88935@EMARC112VS01.exchad.jpmchase.net> Odd, my previous email seems to have gotten lost Cory, See: http://stackoverflow.com/questions/156330/get-timer-ticks-in-python It is basically what Bob mentions, but with a few more details / alternatives. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -----Original Message----- From: tutor-bounces+ramit.prasad=jpmchase.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmchase.com at python.org] On Behalf Of bob gailer Sent: Friday, April 08, 2011 2:49 PM To: Cory Teshera-Sterne Cc: tutor at python.org Subject: Re: [Tutor] Evaluating program running time? On 4/8/2011 2:29 PM, Cory Teshera-Sterne wrote: > Hi all, > > I have a small(ish) Python program, and I need to be able to log the > running time. This isn't something I've ever really encountered, and > I've been led to believe it can be a little hairy. Are there any > Python-specific approaches to this? I found the "timeit" module, but > that doesn't seem to be quite what I'm looking for. I like to use the time module import time start = time.time() rest of program print time.time() - start I believe that gives best precisioni on *nix On Windows use time.clock() )instead. -- 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 This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase & Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase & Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities. From ramit.prasad at jpmchase.com Fri Apr 8 21:42:35 2011 From: ramit.prasad at jpmchase.com (Prasad, Ramit) Date: Fri, 8 Apr 2011 15:42:35 -0400 Subject: [Tutor] Evaluating program running time? In-Reply-To: References: Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2D95E888B5@EMARC112VS01.exchad.jpmchase.net> Cory, See: http://stackoverflow.com/questions/156330/get-timer-ticks-in-python Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 From: tutor-bounces+ramit.prasad=jpmchase.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmchase.com at python.org] On Behalf Of Cory Teshera-Sterne Sent: Friday, April 08, 2011 1:29 PM To: tutor at python.org Subject: [Tutor] Evaluating program running time? Hi all, I have a small(ish) Python program, and I need to be able to log the running time. This isn't something I've ever really encountered, and I've been led to believe it can be a little hairy. Are there any Python-specific approaches to this? I found the "timeit" module, but that doesn't seem to be quite what I'm looking for. Thanks for any insight, Cory -- Cory Teshera-Sterne Mount Holyoke College, 2010 www.linkedin.com/in/corytesherasterne This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase & Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase & Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities. -------------- next part -------------- An HTML attachment was scrubbed... URL: From karim.liateni at free.fr Fri Apr 8 23:44:06 2011 From: karim.liateni at free.fr (Karim) Date: Fri, 08 Apr 2011 23:44:06 +0200 Subject: [Tutor] How to use a module when only import package In-Reply-To: <4D9ED1CB.80403@sohu.com> References: <4D9ED1CB.80403@sohu.com> Message-ID: <4D9F81A6.2060604@free.fr> On 04/08/2011 11:13 AM, leechau wrote: > Steven wrote: >> leechau wrote: >>> I wrote module1 in package1, and want to use a method named >>> 'method1' in >>> module1, the caller(test.py) is like this: >>> >>> import package1 >>> package1.module1.method1() >> [...] >>> When i run test.py, the output is: >>> AttributeError: 'module' object has no attribute 'module1' >>> File "e:\MyDoc\GODU_BVT\test.py", line 2, in >>> package1.module1.method1() >>> >>> If test.py is modified to: >>> import package1.module1 >>> ... >>> then everything goes well. >> >> Yes, that is correct, and that is a deliberate design. >> >> What if your package had a 1000 sub-modules, each of which were big? You >> wouldn't want loading the main package to automatically load all 1000 >> sub-modules, if you only needed 1. >> >> You either import the sub-module by hand: >> >> import package1.module1 >> >> and now you can use package1.module1.method1 (not really a method, >> actually a function). If you want module1 to automatically be available >> after importing the package, include one of these in the package1 >> __init__.py file: >> >> import module1 # should work in Python 2 >> >> >> and now package1 will include the module1 in its namespace. >> >> >> -- >> Steven > > Thanks for Steven's exellent and patient explanations. How should I do > if automatically import a module in Python 3? Thanks again. > > -- > leechau > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Hello, Test it simply! You will get answer in 3 seconds. ;o) Regards Karim From alan.gauld at btinternet.com Sat Apr 9 02:12:55 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 9 Apr 2011 01:12:55 +0100 Subject: [Tutor] Sound question References: Message-ID: "Jan Erik Mostr?m" wrote > A couple of my students need to be able to play sounds, ... > > I looked around and found several packages but they all > seem to have some kind platform restrictions. Sound tends to be platform specific but pygame seems to have hidden most of that. Then again it may not offer all the facilities the dedicated packages do, and it may be a bit heavyweight for sound alone. But worth a look see. Personally I've only played with it on Windows but it claims to work across platforms... -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From duretn at bellsouth.net Sat Apr 9 03:25:05 2011 From: duretn at bellsouth.net (Nevins Duret) Date: Fri, 08 Apr 2011 21:25:05 -0400 Subject: [Tutor] Python 3.2 Install Not Responding To Python Command!! Message-ID: <4D9FB571.1060806@bellsouth.net> Hello Everyone, I recently installed python3.2 by building it from source and noticed that it may have not been installed 100% correctly. When I type: python in the Terminal in Ubuntu 10.10 Maverick, I'm noticing that get the error: bash: /usr/bin/python: is a directory However, when I type either: python2.6--then python2.6 launches as before python3.1--then python3.1 launches python3 or python3.2--then python 3.2 launches I just want to be sure that I have python installed correctly. So far, everything seems to work, however I think this maybe leading to some upgrade issues that I am having with my Update Manager. Any help on this would be greatly appreciated. Best Regards, Nevins Duret From nstinemates at gmail.com Sat Apr 9 03:52:27 2011 From: nstinemates at gmail.com (Nick Stinemates) Date: Fri, 8 Apr 2011 18:52:27 -0700 Subject: [Tutor] Sound question In-Reply-To: References: Message-ID: On Fri, Apr 8, 2011 at 5:12 PM, Alan Gauld wrote: > > "Jan Erik Mostr?m" wrote > > A couple of my students need to be able to play sounds, ... >> >> >> I looked around and found several packages but they all >> seem to have some kind platform restrictions. >> > > Sound tends to be platform specific but pygame seems > to have hidden most of that. Then again it may not offer > all the facilities the dedicated packages do, and it may > be a bit heavyweight for sound alone. But worth a look see. > > Personally I've only played with it on Windows but it > claims to work across platforms... > Personally I've only played with it on Linux so it seems we have it covered :) Nick > > -- > Alan Gauld > 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 lie.1296 at gmail.com Sat Apr 9 07:28:47 2011 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 09 Apr 2011 15:28:47 +1000 Subject: [Tutor] Python 3.2 Install Not Responding To Python Command!! In-Reply-To: <4D9FB571.1060806@bellsouth.net> References: <4D9FB571.1060806@bellsouth.net> Message-ID: On 04/09/11 11:25, Nevins Duret wrote: > Hello Everyone, > > I recently installed python3.2 by building it from source and > noticed that it may have not been > installed 100% correctly. This is probably off topic in python tutor mailing list, better asked on the main mailing list or Ubuntu mailing list. However.. > When I type: > > python > > in the Terminal in Ubuntu 10.10 Maverick, I'm noticing that get the error: > > bash: /usr/bin/python: is a directory Yes, your python is not correctly installed, `python` should be a symbolic link to the system's default python version. Try reinstalling all python. What's the output of `whereis python` and `echo $PATH`? > However, when I type either: > > python2.6--then python2.6 launches as before > > python3.1--then python3.1 launches > > python3 or python3.2--then python 3.2 launches > > I just want to be sure that I have python installed correctly. So far, > everything seems to work, however I think this maybe leading to some > upgrade issues that I am having with my Update Manager. > > > Any help on this would be greatly appreciated. > > Best Regards, > > Nevins Duret > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From lie.1296 at gmail.com Sat Apr 9 07:32:50 2011 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 09 Apr 2011 15:32:50 +1000 Subject: [Tutor] Evaluating program running time? In-Reply-To: References: Message-ID: On 04/09/11 04:29, Cory Teshera-Sterne wrote: > Hi all, > > I have a small(ish) Python program, and I need to be able to log the > running time. This isn't something I've ever really encountered, and > I've been led to believe it can be a little hairy. Are there any > Python-specific approaches to this? I found the "timeit" module, but > that doesn't seem to be quite what I'm looking for. > import cProfile ... def main(): ... cProfile.run('main()') From duretn at bellsouth.net Sat Apr 9 18:44:23 2011 From: duretn at bellsouth.net (Nevins Duret) Date: Sat, 09 Apr 2011 12:44:23 -0400 Subject: [Tutor] Python 3.2 Install Not Responding To Python Command!! In-Reply-To: References: Message-ID: <4DA08CE7.3060606@bellsouth.net> Hello Lie Ryan, Thanks so much for your reply. Well when I ran: whereis python I get this: python: /usr/bin/python3.1-config /usr/bin/python2.6-dbg /usr/bin/python3.1 /usr/bin/python2.6-config /usr/bin/python2.7 /usr/bin/python3.1-dbg-config /usr/bin/python2.6-dbg-config /usr/bin/python /usr/bin/python2.7-config /usr/bin/python3.1-dbg /usr/bin/python2.6 /etc/python3.1 /etc/python2.7 /etc/python /etc/python2.6 /usr/lib/python2.5 /usr/lib/python3.1 /usr/lib/python2.7 /usr/lib/python /usr/lib/python2.6 /usr/local/bin/python3.2m-config /usr/local/bin/python3.2 /usr/local/bin/python3.2-config /usr/local/bin/python3.2m /usr/local/lib/python3.1 /usr/local/lib/python2.7 /usr/local/lib/python3.2 /usr/local/lib/python2.6 /usr/include/python2.5 /usr/include/python3.1 /usr/include/python2.6_d /usr/include/python2.7 /usr/include/python3.1_d /usr/include/python2.6 /usr/share/python /opt/py31/bin/python3.1-config /opt/py31/bin/python3.1 /opt/py32/bin/python3.2m-config /opt/py32/bin/python3.2 /opt/py32/bin/python3.2m /opt/ActivePython-3.1/bin/python3.1-config /opt/ActivePython-3.1/bin/python3.1 /opt/ActivePython-3.2/bin/python3.2m-config /opt/ActivePython-3.2/bin/python3.2 /opt/ActivePython-3.2/bin/python3.2-config /opt/ActivePython-3.2/bin/python3.2m /usr/share/man/man1/python.1.gz And, when I run: echo $PATH I get this: /myhome/myname/.local/bin:/opt/ActivePython-3.2/bin:/myhome/myname/Komodo-IDE-6/bin:/myhome/myname/source/arduino-0022:/myhome/myname/qtsdk-2010.05/bin:/usr/bin//tclsh8.4:/usr/bin//tclsh8.5:/myhome/myname/source/Logic1.1.4:/myhome/myname/source/blender-2.56a-beta-linux-glibc27-i686:/myhome/myname/source/processing-1.2.1:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/opt/blender-2.56-beta-linux-glibc27-i686/2.56/python/lib/python3.1 This is the link to the instructions that I followed to install Python3.2 on my system: http://wiki.blender.org/index.php/Dev:2.5/Doc/Building_Blender/Linux/Troubleshooting Compiling with Ubuntu # get required packages for build sudo apt-get install build-essential libncursesw5-dev libreadline5-dev libssl-dev libgdbm-dev libc6-dev libsqlite3-dev tk-dev # get source wget http://www.python.org/ftp/python/3.2/Python-3.2.tgz&& tar -xvf Python-3.2.tgz # make install ./configure make sudo make altinstall # make 3.2 the default python system wide (number 1 at the end stays there) sudo update-alternatives--install /usr/bin/python pythonopt/py32/bin1 # ensure various versions of python play nice with each other sudo update-alternatives--config python Again I really appreciate your help, getting over this hurdle would help me be confident in what goes on under the hood. At this point, it seems that I will need instructions on how to remove python3.2 in order to get a reattempt at installing it properly. Thanks again for all your help. Best Regards, freespark On 04/09/2011 06:00 AM, tutor-request at python.org wrote: > 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: How to use a module when only import package (Karim) > 2. Re: Sound question (Alan Gauld) > 3. Python 3.2 Install Not Responding To Python Command!! > (Nevins Duret) > 4. Re: Sound question (Nick Stinemates) > 5. Re: Python 3.2 Install Not Responding To Python Command!! > (Lie Ryan) > 6. Re: Evaluating program running time? (Lie Ryan) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Fri, 08 Apr 2011 23:44:06 +0200 > From: Karim > To: leechau > Cc: Python Tutor Maillist > Subject: Re: [Tutor] How to use a module when only import package > Message-ID:<4D9F81A6.2060604 at free.fr> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 04/08/2011 11:13 AM, leechau wrote: >> Steven wrote: >>> leechau wrote: >>>> I wrote module1 in package1, and want to use a method named >>>> 'method1' in >>>> module1, the caller(test.py) is like this: >>>> >>>> import package1 >>>> package1.module1.method1() >>> [...] >>>> When i run test.py, the output is: >>>> AttributeError: 'module' object has no attribute 'module1' >>>> File "e:\MyDoc\GODU_BVT\test.py", line 2, in >>>> package1.module1.method1() >>>> >>>> If test.py is modified to: >>>> import package1.module1 >>>> ... >>>> then everything goes well. >>> Yes, that is correct, and that is a deliberate design. >>> >>> What if your package had a 1000 sub-modules, each of which were big? You >>> wouldn't want loading the main package to automatically load all 1000 >>> sub-modules, if you only needed 1. >>> >>> You either import the sub-module by hand: >>> >>> import package1.module1 >>> >>> and now you can use package1.module1.method1 (not really a method, >>> actually a function). If you want module1 to automatically be available >>> after importing the package, include one of these in the package1 >>> __init__.py file: >>> >>> import module1 # should work in Python 2 >>> >>> >>> and now package1 will include the module1 in its namespace. >>> >>> >>> -- >>> Steven >> Thanks for Steven's exellent and patient explanations. How should I do >> if automatically import a module in Python 3? Thanks again. >> >> -- >> leechau >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > Hello, > > Test it simply! > You will get answer in 3 seconds. > > ;o) > Regards > Karim > > > ------------------------------ > > Message: 2 > Date: Sat, 9 Apr 2011 01:12:55 +0100 > From: "Alan Gauld" > To: tutor at python.org > Subject: Re: [Tutor] Sound question > Message-ID: > Content-Type: text/plain; format=flowed; charset="iso-8859-1"; > reply-type=original > > > "Jan Erik Mostr?m" wrote > >> A couple of my students need to be able to play sounds, ... >> >> I looked around and found several packages but they all >> seem to have some kind platform restrictions. > Sound tends to be platform specific but pygame seems > to have hidden most of that. Then again it may not offer > all the facilities the dedicated packages do, and it may > be a bit heavyweight for sound alone. But worth a look see. > > Personally I've only played with it on Windows but it > claims to work across platforms... > -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Sat Apr 9 20:32:45 2011 From: wprins at gmail.com (Walter Prins) Date: Sat, 9 Apr 2011 19:32:45 +0100 Subject: [Tutor] Python 3.2 Install Not Responding To Python Command!! In-Reply-To: <4DA08CE7.3060606@bellsouth.net> References: <4DA08CE7.3060606@bellsouth.net> Message-ID: On 9 April 2011 17:44, Nevins Duret wrote: > Compiling with Ubuntu > > # get required packages for buildsudo apt-get install build-essential libncursesw5-dev libreadline5-dev libssl-dev libgdbm-dev libc6-dev libsqlite3-dev tk-dev > # get sourcewget http://www.python.org/ftp/python/3.2/Python-3.2.tgz && tar -xvf Python-3.2.tgz > # make install > ./configuremakesudo make altinstall > # make 3.2 the default python system wide (number 1 at the end stays there)sudo update-alternatives --install /usr/bin/python python opt/py32/bin 1 > # ensure various versions of python play nice with each othersudo update-alternatives --config python > > > Again I really appreciate your help, getting over this hurdle would help me be confident in what goes on under the hood. > At this point, it seems that I will need instructions on how to remove python3.2 in order to get a reattempt at installing it > properly. > > > OK... It's usually preferable if at all possible to install things using the system's package manager -- is there any particular reason that you must use Python 3.2 and can't install Python 3.1.2, which is available in the repositories? It may be installed by simply doing: sudo apt-get install python3-all As for fixing/undoing any problems in your system -- I'm reluctant to try and fix that via this list and without more information. I'd therefore suggest asking on the Ubuntu community forums programming sub-forum. http://ubuntuforums.org/forumdisplay.php?f=310 Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From duretn at bellsouth.net Sat Apr 9 20:45:14 2011 From: duretn at bellsouth.net (Nevins Duret) Date: Sat, 09 Apr 2011 14:45:14 -0400 Subject: [Tutor] Python 3.2 Install Not Responding To Python Command!! In-Reply-To: References: <4DA08CE7.3060606@bellsouth.net> Message-ID: <4DA0A93A.6080806@bellsouth.net> On 04/09/2011 02:32 PM, Walter Prins wrote: > > > On 9 April 2011 17:44, Nevins Duret > wrote: > > Compiling with Ubuntu > > # get required packages for build > sudo apt-get install build-essential libncursesw5-dev libreadline5-dev libssl-dev libgdbm-dev libc6-dev libsqlite3-dev tk-dev > > # get source > wget http://www.python.org /ftp/python/3.2/Python-3.2.tgz&& tar -xvf Python-3.2.tgz > > # make install > ./configure > make > sudo make altinstall > > # make 3.2 the default python system wide (number 1 at the end stays there) > sudo update-alternatives--install /usr/bin/python pythonopt/py32/bin1 > > # ensure various versions of python play nice with each other > sudo update-alternatives--config python > > > Again I really appreciate your help, getting over this hurdle would help me be confident in what goes on under the hood. > At this point, it seems that I will need instructions on how to remove python3.2 in order to get a reattempt at installing it > properly. > > > > > OK... It's usually preferable if at all possible to install things > using the system's package manager -- is there any particular reason > that you must use Python 3.2 and can't install Python 3.1.2, which is > available in the repositories? It may be installed by simply doing: > > sudo apt-get install python3-all > > As for fixing/undoing any problems in your system -- I'm reluctant to > try and fix that via this list and without more information. I'd > therefore suggest asking on the Ubuntu community forums programming > sub-forum. http://ubuntuforums.org/forumdisplay.php?f=310 > > Walter > > Hello Walter, I can't thank you enough for your help. Yes, I usually use the Synaptic Package Manager, however in this case, Python version 3.2 is not on the Synaptic package Manager. This is why I chose to build it from source. As far as what I think is causing this when I go in the Terminal and type: p me out. sudo update-alternatives --install /usr/bin/python/python3.2 python /opt/py32/bin/python3.2 1 I get this as an error message: update-alternatives: renaming python link from /usr/bin/python to /usr/bin/python/python3.2. update-alternatives: warning: forcing reinstallation of alternative /opt/py32/bin because link group python is broken. update-alternatives: error: unable to make /usr/bin/python/python3.2.dpkg-tmp a symlink to /etc/alternatives/python: No such file or directory I must add that I am running this in the Terminal under the Python-3.2 directory that I uncompressed after I downloaded it. The reason why I'm using this version of Python is because Blender2.5, a 3D animation open source program is built on Python3.2 and requires it if I am to develop it using CMAKE. And, so far, I have blender installed on /opt/py32. I really appreciate your help, and am learning tons by going through this. I understand that posting this question here may not be suitable, but I'm confident someone will be able to help me out. Thanks so much. Best Regards, Nevins Duret -------------- next part -------------- An HTML attachment was scrubbed... URL: From andres at chandia.net Sat Apr 9 21:40:35 2011 From: andres at chandia.net (=?iso-8859-1?Q?=22Andr=E9s_Chand=EDa=22?=) Date: Sat, 9 Apr 2011 21:40:35 +0200 Subject: [Tutor] Cherrypy HtmlArea Message-ID: <9b312d0310d01656b070543dab1b4870.squirrel@mail.chandia.net> I have put a textarea at a web generated by cherrypy, but I would like to add? some user editing tool like HtmlArea, I've been sufing arround but I haven't found clear information. I would appreciate your help! _______________________ ????????????andr?s chand?a P No imprima innecesariamente. ?Cuide el medio ambiente! From andres at chandia.net Sat Apr 9 23:23:04 2011 From: andres at chandia.net (=?iso-8859-1?Q?=22Andr=E9s_Chand=EDa=22?=) Date: Sat, 9 Apr 2011 23:23:04 +0200 Subject: [Tutor] Cherrypy and Iframes (or how to insert a file in a page) Message-ID: the codes return "" file.txt is genereated by a previous python script and I need to display it at the web generated by cherrypy, but it gives me this error: Traceback (most recent call last): File "/usr/lib/pymodules/python2.6/cherrypy/_cprequest.py", line 606, in respond cherrypy.response.body = self.handler() File "/usr/lib/pymodules/python2.6/cherrypy/_cperror.py", line 227, in __call__ raise self NotFound: (404, "The path '/file.txt' was not found.") I tryed changing the path with no success, so I guess is something different Maybe there is another way to do this.... _______________________ ????????????andr?s chand?a P No imprima innecesariamente. ?Cuide el medio ambiente! From tglembo at gmail.com Sun Apr 10 00:12:33 2011 From: tglembo at gmail.com (Tyler Glembo) Date: Sat, 9 Apr 2011 15:12:33 -0700 Subject: [Tutor] Invisible Characters in Fortran/Python Message-ID: Hi All, So I have a ~3000 line fortran code that needs to be updated to run new files by simply updating a few lines in the code (~10 lines). I thought python would be a great way to do so since I know a little python but not fortran. So, my plan was to read in each line, and then at a certain line number, write out the changed code. A short snippet is as follows: dest= open( f1, "w" ) source= open( f2, "r" ) for line in source: if X: dest.write( newline + "\n" ) else: dest.write( line ) dest.close() source.close() The problem I am having is with hidden/invisible character. In the fortran code, there are line indents which are denoted with an invisible character ^I. When I write with python, there is no ^I at the beginning of the line and the fortran code no longer compiles. I know how to put in the invisible line return character (\n), but how can I put in other invisible characters? Thank you kindly, Tyler P.S. In VI when I "set invlist" the hidden character ^I shows up in blue at the beginning of the line in place of 4 red spaces that are normally there. I'm assuming it is like a tab indent, but I don't know what it is. -------------- next part -------------- An HTML attachment was scrubbed... URL: From thudfoo at gmail.com Sun Apr 10 00:48:49 2011 From: thudfoo at gmail.com (xDog Walker) Date: Sat, 9 Apr 2011 15:48:49 -0700 Subject: [Tutor] Invisible Characters in Fortran/Python In-Reply-To: References: Message-ID: <201104091548.49831.thudfoo@gmail.com> On Saturday 2011 April 09 15:12, Tyler Glembo wrote: > Hi All, > So I have a ~3000 line fortran code that needs to be updated to run new > files by simply updating a few lines in the code (~10 lines). I thought > python would be a great way to do so since I know a little python but not > fortran. So, my plan was to read in each line, and then at a certain line > number, write out the changed code. A short snippet is as follows: > > dest= open( f1, "w" ) > source= open( f2, "r" ) > for line in source: > if X: > dest.write( newline + "\n" ) > else: > dest.write( line ) > dest.close() > source.close() > > The problem I am having is with hidden/invisible character. In the fortran > code, there are line indents which are denoted with an invisible character > ^I. When I write with python, there is no ^I at the beginning of the line > and the fortran code no longer compiles. I know how to put in the > invisible line return character (\n), but how can I put in other invisible > characters? > > Thank you kindly, > Tyler > > P.S. In VI when I "set invlist" the hidden character ^I shows up in blue at > the beginning of the line in place of 4 red spaces that are normally there. > I'm assuming it is like a tab indent, but I don't know what it is. It is a tab. -- I have seen the future and I am not in it. From aharrisreid at googlemail.com Sun Apr 10 01:04:15 2011 From: aharrisreid at googlemail.com (Alan Harris-Reid) Date: Sun, 10 Apr 2011 00:04:15 +0100 Subject: [Tutor] Cherrypy and Iframes (or how to insert a file in a, page) In-Reply-To: References: Message-ID: <4DA0E5EF.9020104@googlemail.com> Andreas... > NotFound: (404, "The path '/file.txt' was not found.") This error message often occurs because file.txt is a static file and you have not told CherryPy where to look for static files. From the look of the error I am guessing that file.txt is in your root directory, in which case you need the following in your configuration file. [/] tools.staticdir.root = '/path/to/root/folder' # no trailing backslash tools.staticdir.on = True tools.staticdir.dir = "" # necessary to serve static files in home folder Hope this helps. Alan Harris-Reid From malcolm.newsome at gmail.com Sun Apr 10 01:10:17 2011 From: malcolm.newsome at gmail.com (Malcolm Newsome) Date: Sat, 9 Apr 2011 18:10:17 -0500 Subject: [Tutor] Virtualenv Error Message-ID: <003d01cbf70b$4b7d87d0$e2789770$@gmail.com> Hey All, I installed virtualenv and am getting this error when trying to create one. I'm running Windows 7. Can anyone help?? Thanks! Microsoft Windows [Version 6.1.7601] Copyright (c) 2009 Microsoft Corporation. All rights reserved. C:\Users\Malcolm>virtualenv chipysite New python executable in chipysite\Scripts\python.exe Installing setuptools................done. Complete output from command C:\Users\Malcolm\chipysite\Scr...n.exe C:\Users\Malcolm\chipysite\Scr...pt.py C:\Users\Malcolm\Python26\lib\...ar.gz: Traceback (most recent call last): File "C:\Users\Malcolm\chipysite\Scripts\easy_install-script.py", line 8, in load_entry_point('setuptools==0.6c11', 'console_scripts', 'easy_install')() File "C:\Users\Malcolm\chipysite\lib\site-packages\setuptools-0.6c11-py2.6.egg\pk g_resources.py", line 318, in load_entry_point return get_distribution(dist).load_entry_point(group, name) File "C:\Users\Malcolm\chipysite\lib\site-packages\setuptools-0.6c11-py2.6.egg\pk g_resources.py", line 2221, in load_entry_point return ep.load() File "C:\Users\Malcolm\chipysite\lib\site-packages\setuptools-0.6c11-py2.6.egg\pk g_resources.py", line 1954, in load entry = __import__(self.module_name, globals(),globals(), ['__name__']) File "C:\Users\Malcolm\chipysite\lib\site-packages\setuptools-0.6c11-py2.6.egg\se tuptools\command\easy_install.py", line 21, in File "C:\Users\Malcolm\chipysite\lib\site-packages\setuptools-0.6c11-py2.6.egg\se tuptools\package_index.py", line 2, in File "C:\Users\Malcolm\Python26\lib\urllib2.py", line 92, in import httplib File "C:\Users\Malcolm\Python26\lib\httplib.py", line 70, in import socket File "C:\Users\Malcolm\Python26\lib\socket.py", line 46, in import _socket ImportError: No module named _socket ---------------------------------------- Traceback (most recent call last): File "C:\Users\Malcolm\Python26\Scripts\virtualenv-script.py", line 8, in load_entry_point('virtualenv==1.5.2', 'console_scripts', 'virtualenv')() File "C:\Users\Malcolm\Python26\lib\site-packages\virtualenv-1.5.2-py2.6.egg\virt ualenv.py", line 558, in main prompt=options.prompt) File "C:\Users\Malcolm\Python26\lib\site-packages\virtualenv-1.5.2-py2.6.egg\virt ualenv.py", line 656, in create_environment install_pip(py_executable) File "C:\Users\Malcolm\Python26\lib\site-packages\virtualenv-1.5.2-py2.6.egg\virt ualenv.py", line 415, in install_pip filter_stdout=_filter_setup) File "C:\Users\Malcolm\Python26\lib\site-packages\virtualenv-1.5.2-py2.6.egg\virt ualenv.py", line 624, in call_subprocess % (cmd_desc, proc.returncode)) OSError: Command C:\Users\Malcolm\chipysite\Scr...n.exe C:\Users\Malcolm\chipysite\Scr...pt.py C:\Users\Malcolm\Python26\lib\...ar.gz failed with error code 1 From steve at pearwood.info Sun Apr 10 01:34:34 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 10 Apr 2011 09:34:34 +1000 Subject: [Tutor] Invisible Characters in Fortran/Python In-Reply-To: References: Message-ID: <4DA0ED0A.8010809@pearwood.info> Tyler Glembo wrote: > The problem I am having is with hidden/invisible character. In the fortran > code, there are line indents which are denoted with an invisible character > ^I. When I write with python, there is no ^I at the beginning of the line ^I is a tab character, which you can include in Python strings using \t > and the fortran code no longer compiles. I know how to put in the invisible > line return character (\n), but how can I put in other invisible characters? In byte strings: \a ASCII BEL \b ASCII BACKSPACE \0 ASCII NULL \n linefeed \v vertical tab \t horizontal tab \r carriage return \f formfeed \xDD character with hexadecimal value DD \XDD same as above \0DD character with octal value DD In Unicode strings, all of the above, plus: \uDDDD unicode character with hex value DDDD (four bytes) \UDDDDDDDD unicode character with hex value DDDDDDDD (eight bytes) \N{NAME} unicode character named NAME Note that in Python 3, octal escape sequences no longer use \0 (backslash-zero), but \o (backslash-o). See http://docs.python.org/reference/lexical_analysis.html#strings for more details. -- Steven From rsachdev at usc.edu Sun Apr 10 00:12:33 2011 From: rsachdev at usc.edu (Rohan Sachdeva) Date: Sat, 09 Apr 2011 15:12:33 -0700 Subject: [Tutor] Python 3.2 Install Not Responding To Python Command!! In-Reply-To: <4DA0A93A.6080806@bellsouth.net> References: <4DA08CE7.3060606@bellsouth.net> <4DA0A93A.6080806@bellsouth.net> Message-ID: Just so you know there is a PPA for 3.2 - https://launchpad.net/~irie/+archive/python3.2 Should make things a lot easier. Rohan On Sat, Apr 9, 2011 at 11:45 AM, Nevins Duret wrote: > On 04/09/2011 02:32 PM, Walter Prins wrote: > > > > On 9 April 2011 17:44, Nevins Duret wrote: > >> Compiling with Ubuntu >> >> # get required packages for buildsudo apt-get install build-essential libncursesw5-dev libreadline5-dev libssl-dev libgdbm-dev libc6-dev libsqlite3-dev tk-dev >> # get sourcewget http://www.python.org/ftp/python/3.2/Python-3.2.tgz && tar -xvf Python-3.2.tgz >> # make install >> ./configuremakesudo make altinstall >> # make 3.2 the default python system wide (number 1 at the end stays there)sudo update-alternatives --install /usr/bin/python python opt/py32/bin 1 >> # ensure various versions of python play nice with each othersudo update-alternatives --config python >> >> >> Again I really appreciate your help, getting over this hurdle would help me be confident in what goes on under the hood. >> At this point, it seems that I will need instructions on how to remove python3.2 in order to get a reattempt at installing it >> properly. >> >> >> >> > OK... It's usually preferable if at all possible to install things using > the system's package manager -- is there any particular reason that you must > use Python 3.2 and can't install Python 3.1.2, which is available in the > repositories? It may be installed by simply doing: > > sudo apt-get install python3-all > > As for fixing/undoing any problems in your system -- I'm reluctant to try > and fix that via this list and without more information. I'd therefore > suggest asking on the Ubuntu community forums programming sub-forum. > http://ubuntuforums.org/forumdisplay.php?f=310 > > Walter > > > Hello Walter, > > I can't thank you enough for your help. Yes, I usually use the > Synaptic Package Manager, however in this case, Python version 3.2 is not on > the Synaptic package Manager. This is why I chose to build it from source. > As far as what I think is causing this when I go in the Terminal and type: > p me out. > sudo update-alternatives --install /usr/bin/python/python3.2 python > /opt/py32/bin/python3.2 1 > > I get this as an error message: > > update-alternatives: renaming python link from /usr/bin/python to > /usr/bin/python/python3.2. > update-alternatives: warning: forcing reinstallation of alternative > /opt/py32/bin because link group python is broken. > update-alternatives: error: unable to make > /usr/bin/python/python3.2.dpkg-tmp a symlink to /etc/alternatives/python: No > such file or directory > > I must add that I am running this in the Terminal under the Python-3.2 > directory that I uncompressed after I downloaded it. The reason why I'm > using this version of Python is because Blender2.5, a 3D animation open > source program is built on Python3.2 and requires it if I am to develop it > using CMAKE. And, so far, I have blender installed on /opt/py32. > > I really appreciate your help, and am learning tons by going through > this. I understand that posting this question here may not be suitable, but > I'm confident someone will be able to help me out. > Thanks so much. > > Best Regards, > > Nevins Duret > > _______________________________________________ > 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 duretn at bellsouth.net Sun Apr 10 02:37:27 2011 From: duretn at bellsouth.net (Nevins Duret) Date: Sat, 09 Apr 2011 20:37:27 -0400 Subject: [Tutor] Python 3.2 Install Not Responding To Python Command!! In-Reply-To: References: <4DA08CE7.3060606@bellsouth.net> <4DA0A93A.6080806@bellsouth.net> Message-ID: <4DA0FBC7.8090004@bellsouth.net> On 04/09/2011 06:12 PM, Rohan Sachdeva wrote: > Just so you know there is a PPA for 3.2 - > https://launchpad.net/~irie/+archive/python3.2 > > > Should make things a lot easier. > > Rohan > > On Sat, Apr 9, 2011 at 11:45 AM, Nevins Duret > wrote: > > On 04/09/2011 02:32 PM, Walter Prins wrote: >> >> >> On 9 April 2011 17:44, Nevins Duret > > wrote: >> >> Compiling with Ubuntu >> >> # get required packages for build >> sudo apt-get install build-essential libncursesw5-dev libreadline5-dev libssl-dev libgdbm-dev libc6-dev libsqlite3-dev tk-dev >> >> # get source >> wget http://www.python.org /ftp/python/3.2/Python-3.2.tgz&& tar -xvf Python-3.2.tgz >> >> # make install >> ./configure >> make >> sudo make altinstall >> >> # make 3.2 the default python system wide (number 1 at the end stays there) >> sudo update-alternatives--install /usr/bin/python pythonopt/py32/bin1 >> >> # ensure various versions of python play nice with each other >> sudo update-alternatives--config python >> >> >> Again I really appreciate your help, getting over this hurdle would help me be confident in what goes on under the hood. >> At this point, it seems that I will need instructions on how to remove python3.2 in order to get a reattempt at installing it >> properly. >> >> >> >> >> OK... It's usually preferable if at all possible to install >> things using the system's package manager -- is there any >> particular reason that you must use Python 3.2 and can't install >> Python 3.1.2, which is available in the repositories? It may be >> installed by simply doing: >> >> sudo apt-get install python3-all >> >> As for fixing/undoing any problems in your system -- I'm >> reluctant to try and fix that via this list and without more >> information. I'd therefore suggest asking on the Ubuntu >> community forums programming sub-forum. >> http://ubuntuforums.org/forumdisplay.php?f=310 >> >> Walter >> >> > Hello Walter, > > I can't thank you enough for your help. Yes, I usually use > the Synaptic Package Manager, however in this case, Python version > 3.2 is not on the Synaptic package Manager. This is why I chose > to build it from source. As far as what I think is causing this > when I go in the Terminal and type: > p me out. > sudo update-alternatives --install /usr/bin/python/python3.2 > python /opt/py32/bin/python3.2 1 > > I get this as an error message: > > update-alternatives: renaming python link from /usr/bin/python to > /usr/bin/python/python3.2. > update-alternatives: warning: forcing reinstallation of > alternative /opt/py32/bin because link group python is broken. > update-alternatives: error: unable to make > /usr/bin/python/python3.2.dpkg-tmp a symlink to > /etc/alternatives/python: No such file or directory > > I must add that I am running this in the Terminal under the > Python-3.2 directory that I uncompressed after I downloaded it. > The reason why I'm using this version of Python is because > Blender2.5, a 3D animation open source program is built on > Python3.2 and requires it if I am to develop it using CMAKE. And, > so far, I have blender installed on /opt/py32. > > I really appreciate your help, and am learning tons by going > through this. I understand that posting this question here may > not be suitable, but I'm confident someone will be able to help me > out. > Thanks so much. > > Best Regards, > > Nevins Duret > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > Hello Rohan, With that said, how do I go about adding this link to my list of repositories? Before, I would just have to go to the Update Manager, and then I would just add the link, now, as a result of not being able to launch Update Manager as result of the bad Python3.2 install, I am not able to successfully add the link to my list of repositories. Again, I thank you for your help. Best Regards, Nevins Duret -------------- next part -------------- An HTML attachment was scrubbed... URL: From onyxtic at gmail.com Sun Apr 10 08:42:43 2011 From: onyxtic at gmail.com (Evans Anyokwu) Date: Sun, 10 Apr 2011 07:42:43 +0100 Subject: [Tutor] Cherrypy HtmlArea In-Reply-To: <9b312d0310d01656b070543dab1b4870.squirrel@mail.chandia.net> References: <9b312d0310d01656b070543dab1b4870.squirrel@mail.chandia.net> Message-ID: Hi Andr?s, I'm not sure a lot of people on this list use Cheerypy - I use django myself. I would suggest you check cherrypy website, there's an IRC link at the top of the page. Good luck 2011/4/9 "Andr?s Chand?a" > > > I have put a textarea at a web generated by cherrypy, but I would like to > add some user > editing tool like HtmlArea, I've been sufing arround but I haven't found > clear information. > > I would appreciate your help! > _______________________ > andr?s > chand?a > > P No imprima > innecesariamente. ?Cuide el medio ambiente! > > > _______________________________________________ > 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 andres at chandia.net Sun Apr 10 13:05:19 2011 From: andres at chandia.net (=?iso-8859-1?Q?=22Andr=E9s_Chand=EDa=22?=) Date: Sun, 10 Apr 2011 13:05:19 +0200 Subject: [Tutor] Cherrypy and Iframes (or how to insert a file in a, page) In-Reply-To: <4DA0E5EF.9020104@googlemail.com> References: <4DA0E5EF.9020104@googlemail.com> Message-ID: <9585003668f37094719365f1baeb2d1d.squirrel@mail.chandia.net> Thanks a lot Alan, I'm a complete newbe in cherrypy, actually this is my first cherrypy, so I had to go arround many tries to reach the goal, but your help was valuable and finally this is the config that gave me success: class helloworld(object): ??? indexpage = indexpage() ??? _cp_config = {??? 'tools.staticdir.on': True, ??? ??? ??? 'tools.staticdir.root': '/path/to/root/folder', ??? ??? ??? 'tools.staticdir.dir': '', ??? ??? ??? } On Sun, April 10, 2011 01:04, Alan Harris-Reid wrote: Andreas... > NotFound: (404, "The path '/file.txt' was not found.") This error message often occurs because file.txt is a static file and you have not told CherryPy where to look for static files. >From the look of the error I am guessing that file.txt is in your root directory, in which case you need the following in your configuration file. [/] tools.staticdir.root = '/path/to/root/folder' # no trailing backslash tools.staticdir.on = True tools.staticdir.dir = "" # necessary to serve static files in home folder Hope this helps. Alan Harris-Reid _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor _______________________ ????????????andr?s chand?a P No imprima innecesariamente. ?Cuide el medio ambiente! From andres at chandia.net Sun Apr 10 14:29:12 2011 From: andres at chandia.net (=?iso-8859-1?Q?=22Andr=E9s_Chand=EDa=22?=) Date: Sun, 10 Apr 2011 14:29:12 +0200 Subject: [Tutor] Cherrypy and Wysiwyg editor In-Reply-To: References: <9b312d0310d01656b070543dab1b4870.squirrel@mail.chandia.net> Message-ID: <6c81e4e808e677495827b85895df7edb.squirrel@mail.chandia.net> I have put a textarea at a web generated by cherrypy, but I would like to add? some user editing tool like HtmlArea, I've been sufing arround but I haven't found clear information. I would appreciate your help! _______________________ ????????????andr?s chand?a P No imprima innecesariamente. ?Cuide el medio ambiente! From wprins at gmail.com Sun Apr 10 22:33:19 2011 From: wprins at gmail.com (Walter Prins) Date: Sun, 10 Apr 2011 21:33:19 +0100 Subject: [Tutor] Python 3.2 Install Not Responding To Python Command!! In-Reply-To: <4DA0A93A.6080806@bellsouth.net> References: <4DA08CE7.3060606@bellsouth.net> <4DA0A93A.6080806@bellsouth.net> Message-ID: On 9 April 2011 19:45, Nevins Duret wrote: > I can't thank you enough for your help. Yes, I usually use the Synaptic > Package Manager, however in this case, Python version 3.2 is not on the > Synaptic package Manager. This is why I chose to build it from source. As > far as what I think is causing this when I go in the > No problem. > Terminal and type: > sudo update-alternatives --install /usr/bin/python/python3.2 python > /opt/py32/bin/python3.2 1 > > I get this as an error message: > > update-alternatives: renaming python link from /usr/bin/python to > /usr/bin/python/python3.2. > update-alternatives: warning: forcing reinstallation of alternative > /opt/py32/bin because link group python is broken. > update-alternatives: error: unable to make > /usr/bin/python/python3.2.dpkg-tmp a symlink to /etc/alternatives/python: No > such file or directory > I would expect that "update-alternatives" would have trouble (on the first line) because /usr/bin/python is not a link anymore (but instead a folder) based on your previous posts. So, please go and inspect the /usr/bin/python folder and see what if anything's inside. If it's not empty you need to see what is in fact in it and hopefully get rid of it or move it out of the way. Once it's empty, then just delete the /usr/bin/python folder (you'll have to be root or use "sudo") and afterwards either recreate a link to the default python interpreter and/or try the update-alternatives command again. (To manually restore the default python link, first execute "which python2.6" which should output "/usr/bin/python2.6", then execute "sudo ln -s /usr/bin/python2.6 /usr/bin/python" which should restore the link to the default python. After doing this "update-alternatives" should have less trouble redirecting the /usr/bin/python link. I however want to reiterate that your problems, especially fixing your OS, will be better dealt with on the Ubuntu community forums. Rohan, thanks for posting about that PPA, wasn't aware of it! Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From charlze at sohu.com Mon Apr 11 02:43:25 2011 From: charlze at sohu.com (leechau) Date: Mon, 11 Apr 2011 08:43:25 +0800 Subject: [Tutor] How to design the structure of multi-steps(and substeps) scripts Message-ID: <4DA24EAD.1040602@sohu.com> Hi everybody. I wrote a script to run BVT and it's code structure like this: def step1: local_var1 = ... # some other variable definitions for step1 def substep11: pass def substep12: pass # more substeps def step2: local_var1 = ... # some other variable definitions for step2 def substep21: pass def substep22: pass # more substeps # more steps ... def stepN: #vars and substeps... global_var1 = ... # more global var definitions... if step1.return_success: step2 step3 ... stepN As you see, this script consists of serveral steps(a list of commands), and a step often consists of several substeps. I used to put all the steps in one module, where one step corresponding to one funciton and one substep corresponding to one nested function. It's now a headache to maintain this script because of totally 1000+ lines of code. Meanwhile when I manipulate different projects with this script I need to modify the value of some variables and detailed task logic. Obviously it's a dirty work to modify the source code directly for different projects. So I wonder if I should put different steps in different modules to shorten the length of each module? If I should put the default value of a variable and high level task logic in a abstract class, and define specific value and detailed task logic in concrete subclass? Is there any design patterns available for this kind of multi-steps scripts? Thanks! -- leechau From steve at pearwood.info Mon Apr 11 07:23:59 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 11 Apr 2011 15:23:59 +1000 Subject: [Tutor] How to design the structure of multi-steps(and substeps) scripts In-Reply-To: <4DA24EAD.1040602@sohu.com> References: <4DA24EAD.1040602@sohu.com> Message-ID: <20110411052359.GA19287@ando> On Mon, Apr 11, 2011 at 08:43:25AM +0800, leechau wrote: > Hi everybody. I wrote a script to run BVT and it's code structure like this: What's BVT? > def step1: > local_var1 = ... > # some other variable definitions for step1 > def substep11: > pass > def substep12: > pass > # more substeps [...] > # more steps ... > global_var1 = ... > # more global var definitions... Using global variables is generally considered an anti-pattern and poor design. You should rethink your design and try to avoid globals. > if step1.return_success: > step2 > step3 > ... > stepN This doesn't work with the skeleton you provide. In the skeleton provided, step1 is a function object. Since you never call the function, it doesn't do anything. Likewise, it doesn't have an attribute called "return_success". > As you see, this script consists of serveral steps(a list of commands), > and a step often consists of several substeps. I used to put all the > steps in one module, where one step corresponding to one funciton and > one substep corresponding to one nested function. It's now a headache to > maintain this script because of totally 1000+ lines of code. 1000 lines of code isn't much. If it's a headache, that's more likely due to poor design (globals?) than volume. > Meanwhile > when I manipulate different projects with this script I need to modify > the value of some variables and detailed task logic. Exactly! And now you know why global variables are frowned on. > Obviously it's a > dirty work to modify the source code directly for different projects. So > I wonder if I should put different steps in different modules to shorten > the length of each module? If I should put the default value of a > variable and high level task logic in a abstract class, and define > specific value and detailed task logic in concrete subclass? Is there > any design patterns available for this kind of multi-steps scripts? Except the most trivial scripts, all scripts are multi-step. You should use argument passing instead of globals. Your functions should take arguments, and return results, instead of reading and setting globals. -- Steven From tcl76 at hotmail.com Mon Apr 11 07:46:46 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Mon, 11 Apr 2011 05:46:46 +0000 Subject: [Tutor] Python to XML Message-ID: hi, i just started to learn xml using python and i'm getting error when opening the output xml. it doesnt give error when running. i also tried to use python to output to a text file and it works without any error. Pls advise me how i can rectify the error when opening the output xml. attached is my code, output in text file and output in xml. thanks tcl -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: debug.py URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: out.txt URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: port1.xml Type: application/octet-stream Size: 99 bytes Desc: not available URL: From tcl76 at hotmail.com Mon Apr 11 08:08:39 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Mon, 11 Apr 2011 06:08:39 +0000 Subject: [Tutor] Generating XML using Python Message-ID: hi, i'm using python to generate xml with elementtree api. and i'm getting error when opening the output xml. it doesnt give error when running. i also tried to use python to output to a text file and it works without any error. Pls advise me how i can rectify the error when opening the output xml. attached is my code, output in text file and output in xml. thanks tcl p/s: i sent earlier email but got bounced email so sending out again. -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: debug.py URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: port1.xml Type: application/octet-stream Size: 99 bytes Desc: not available URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: out.txt URL: From __peter__ at web.de Mon Apr 11 09:47:54 2011 From: __peter__ at web.de (Peter Otten) Date: Mon, 11 Apr 2011 09:47:54 +0200 Subject: [Tutor] Generating XML using Python References: Message-ID: tee chwee liong wrote: > i'm using python to generate xml with elementtree api. and i'm getting > error when opening the output xml. it doesnt give error when running. i > also tried to use python to output to a text file and it works without any > error. Pls advise me how i can rectify the error when opening the output > xml. attached is my code, output in text file and output in xml. > title = ET.SubElement(head1, "Target Speed") Did you forget to replace the blank between Target and Speed with an underscore? It looks like ElementTree doesn't validate the Element tag. > p/s: i sent earlier email but got bounced email so sending out again. I see them both. From alan.gauld at btinternet.com Mon Apr 11 09:50:47 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 11 Apr 2011 08:50:47 +0100 Subject: [Tutor] How to design the structure of multi-steps(and substeps)scripts References: <4DA24EAD.1040602@sohu.com> Message-ID: "leechau" wrote > def step1: > local_var1 = ... > # some other variable definitions for step1 > def substep11: > pass > # more substeps > ... > global_var1 = ... > # more global var definitions... > if step1.return_success: > step2 Since this is obviously pseudo code I'll assume the real code has fixed the synrax issues. > steps in one module, where one step corresponding to one funciton > and > one substep corresponding to one nested function. While that may seem logical it does limit reuse of the subfunctions. Do these subfunctions look very similar? Could the be written more generically - perhaps using some parameters to deal with differences? If so take them outside the steps. Then define your steps as tables of functions step1 = [substep1,substep2,substep3] and call using a loop: for step in step1: step() > maintain this script because of totally 1000+ lines of code. Thats getting close to the biggest I like my modules to be but not huge. The size is not the problem - after all thats what search is for in the editor! :-) > when I manipulate different projects with this script I need to > modify > the value of some variables and detailed task logic. Obviously it's > a > dirty work to modify the source code directly for different > projects. If you are reusing then break the modules down to the size of the unit of reuse. So if you only use a single step then make each step a module. BUt if you reuse the entire group then keep it as one. > ....If I should put the default value of a > variable and high level task logic in a abstract class, and define > specific value and detailed task logic in concrete subclass? That would be good to get rid of the globals at least and enable different projects to modify the instance values for their own purposes. > any design patterns available for this kind of multi-steps scripts? I'd definitely consider a data driven approach as suggested above, but a lot depends on how complex the real logic is inside the steps. If it can be simplified to little more than a sequence of substeps and those substeps can be generic then a table driven style will greatly simplify the code. Another pattern that is likely to apply is a state machine, either implemented using state classes or as a table. But without knowlege of the detail of the real code we cannot make definite recommendations. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Apr 11 09:58:34 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 11 Apr 2011 08:58:34 +0100 Subject: [Tutor] Python to XML References: Message-ID: "tee chwee liong" wrote > i just started to learn xml using python and i'm getting > error when opening the output xml. it doesnt give error when > running. Always post full error codes and the asociated source code. For shorty programs like this its more convenient to include the text in the body rather than as attachments. > how i can rectify the error when opening the output xml. > attached is my code, output in text file and output in xml. The error I got from IE was an invalid name and looking at you names it seems that you do indeed have an invalid name in your XML. When I deleted the space chartacter it worked OK. Error messages are there to help you find the error. They are usually accurate. Read them carefully and do as they ask. HTH, -- Alan Gauld 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 tcl76 at hotmail.com Mon Apr 11 10:04:40 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Mon, 11 Apr 2011 08:04:40 +0000 Subject: [Tutor] Generating XML using Python In-Reply-To: References: , Message-ID: hi Peter, thanks for your reply. seems that xml doesnt accept a space in between. anyway, the output generated is: - - 2 3 it overwrites every time the port number is incremented and only capture the last iteration number. how can i modify it to capture all the iteration? for eg: Port 1 Link speed: 2 Target speed: 3 Port 2 Link speed: 2 Target speed: 3 Port 3 Link speed: 2 Target speed: 3 Port 4 Link speed: 2 Target speed: 3 Port 5 Link speed: 2 Target speed: 3 Port 6 Link speed: 2 Target speed: 3 Port 7 Link speed: 2 Target speed: 3 Port 8 Link speed: 2 Target speed: 3 thanks tcl -------------- next part -------------- An HTML attachment was scrubbed... URL: From fal at libero.it Mon Apr 11 10:09:40 2011 From: fal at libero.it (Francesco Loffredo) Date: Mon, 11 Apr 2011 10:09:40 +0200 Subject: [Tutor] Invisible Characters in Fortran/Python In-Reply-To: References: Message-ID: <4DA2B744.8000709@libero.it> On 04/10/2011 0.12, Tyler Glembo wrote: > Hi All, > So I have a ~3000 line fortran code that needs to be updated to run new files by simply updating a few lines in the code (~10 > lines). I thought python would be a great way to do so since I know a little python but not fortran. So, my plan was to read in > each line, and then at a certain line number, write out the changed code. A short snippet is as follows: > > dest= open( f1, "w" ) > source= open( f2, "r" ) > for line in source: > if X: > dest.write( newline + "\n" ) > else: > dest.write( line ) > dest.close() > source.close() > > The problem I am having is with hidden/invisible character. In the fortran code, there are line indents which are denoted with an > invisible character ^I. When I write with python, there is no ^I at the beginning of the line and the fortran code no longer > compiles. I know how to put in the invisible line return character (\n), but how can I put in other invisible characters? I think you could avoid entirely this problem by using the binary option in the open function: dest= open( f1, "wb" ) source= open( f2, "rb" ) This way, each read and each write you perform will take into account all kinds of characters, and so your written lines will be identical to those you read. If the problem was only with the "newline" lines, then Steven's answer has already solved your problem. Hope that helps Francesco ----- Nessun virus nel messaggio. Controllato da AVG - www.avg.com Versione: 10.0.1209 / Database dei virus: 1500/3564 - Data di rilascio: 10/04/2011 From __peter__ at web.de Mon Apr 11 10:39:48 2011 From: __peter__ at web.de (Peter Otten) Date: Mon, 11 Apr 2011 10:39:48 +0200 Subject: [Tutor] Generating XML using Python References: Message-ID: tee chwee liong wrote: > thanks for your reply. seems that xml doesnt accept a space in between. > anyway, the output generated is: > > - > > > - > > > 2 > > 3 > > > > it overwrites every time the port number is incremented and only capture > the last iteration number. how can i modify it to capture all the > iteration? Do you want them all in one file? Move the code to create the root element and the code to write the file out of the loop. Do you want to write multiple files? Use a different name from every file. From tcl76 at hotmail.com Mon Apr 11 10:44:05 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Mon, 11 Apr 2011 08:44:05 +0000 Subject: [Tutor] Generating XML using Python In-Reply-To: References: , , , Message-ID: sorry for lack of details. yes i would like to output in 1 xml file. i would like to generate port 1 and its details (link, speed etc) then move to second port, port 2 and generate its details (link, speed etc) tq > To: tutor at python.org > From: __peter__ at web.de > Date: Mon, 11 Apr 2011 10:39:48 +0200 > Subject: Re: [Tutor] Generating XML using Python > > tee chwee liong wrote: > > > thanks for your reply. seems that xml doesnt accept a space in between. > > anyway, the output generated is: > > > > - > > > > > > - > > > > > > 2 > > > > 3 > > > > > > > > it overwrites every time the port number is incremented and only capture > > the last iteration number. how can i modify it to capture all the > > iteration? > > Do you want them all in one file? Move the code to create the root element > and the code to write the file out of the loop. > > Do you want to write multiple files? Use a different name from every file. > > _______________________________________________ > 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 tcl76 at hotmail.com Mon Apr 11 10:47:40 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Mon, 11 Apr 2011 08:47:40 +0000 Subject: [Tutor] Generating XML using Python In-Reply-To: References: , , , Message-ID: > Do you want them all in one file? Move the code to create the root element > and the code to write the file out of the loop. > > Do you want to write multiple files? Use a different name from every file. > yes i would like to generate 1 xml file by incrementing the port number in the range. i'm confuse why xml is overwritten inside the for loop. i tried to test by writing to a text file, and it works. tq Port 1 Link speed: 2 Target speed: 3 Port 2 Link speed: 2 Target speed: 3 Port 3 Link speed: 2 Target speed: 3 Port 4 Link speed: 2 Target speed: 3 Port 5 Link speed: 2 Target speed: 3 Port 6 Link speed: 2 Target speed: 3 Port 7 Link speed: 2 Target speed: 3 Port 8 Link speed: 2 Target speed: 3 -------------- next part -------------- An HTML attachment was scrubbed... URL: From tcl76 at hotmail.com Mon Apr 11 10:59:01 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Mon, 11 Apr 2011 08:59:01 +0000 Subject: [Tutor] Generating XML using Python In-Reply-To: References: , , , , , , , Message-ID: hi peter, yes it worked after i moved the root outside the for loop. code: import elementtree.ElementTree as ET lspeed=2 tspeed=3 f=open("out.txt", "w") root = ET.Element("Test") for port in range (1,9): print "Port %d" %port #root = ET.Element("Test") f.write("Port %d\n" %port) head1 = ET.SubElement(root, "Default_Config", Port=str(port)) print "Link speed: %d" %lspeed f.write("Link speed: %d\n" %lspeed) title = ET.SubElement(head1, "LINK") title.text = str(lspeed) print "Target speed: %d" %tspeed f.write("Target speed: %d\n" %tspeed) title = ET.SubElement(head1, "Target_Speed") title.text = str(tspeed) tree = ET.ElementTree(root) tree.write("C:\\Python25\\myscript\\cmm\\port1.xml") f.close() output: - - 2 3 - 2 3 - 2 3 - 2 3 - 2 3 - 2 3 - 2 3 - 2 3 -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Mon Apr 11 11:11:02 2011 From: __peter__ at web.de (Peter Otten) Date: Mon, 11 Apr 2011 11:11:02 +0200 Subject: [Tutor] Generating XML using Python References: Message-ID: tee chwee liong wrote: > > sorry for lack of details. yes i would like to output in 1 xml file. > i would like to generate port 1 and its details (link, speed etc) then > move to second port, port 2 and generate its details (link, speed etc) tq As I said, instead of creating a new root on every iteration, create it once before you enter the loop. Then write the tree after the loop has termininated: import xml.etree.ElementTree as ET lspeed=2 tspeed=3 root = ET.Element("Test") for port in range(1,9): head = ET.SubElement(root, "Default_Config", Port=str(port)) title = ET.SubElement(head, "LINK") title.text = str(lspeed) title = ET.SubElement(head, "Target_Speed") tree = ET.ElementTree(root) tree.write("port1.xml") From swimbabe339 at yahoo.com Mon Apr 11 13:01:26 2011 From: swimbabe339 at yahoo.com (Sophie DeNofrio) Date: Mon, 11 Apr 2011 04:01:26 -0700 (PDT) Subject: [Tutor] A Dictionary question Message-ID: <194989.127.qm@web161309.mail.bf1.yahoo.com> Hi Everyone,? I am a super beginner and am little muddled right now. So I apologize for the low level question but I am trying to write a function that will return a dictionary of a given list of strings containing two coordinates separated by a space with the first numbers as a key and the second numbers as its corresponding value. I thought maybe a set might be helpful but that didn't seem to work at all. I am pretty much as confused as they come and any help would be very much appreciated. Thank you so much for your time.? .___. {O,o} /)__) Annie -"-"- -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreengels at gmail.com Mon Apr 11 13:30:11 2011 From: andreengels at gmail.com (Andre Engels) Date: Mon, 11 Apr 2011 13:30:11 +0200 Subject: [Tutor] A Dictionary question In-Reply-To: <194989.127.qm@web161309.mail.bf1.yahoo.com> References: <194989.127.qm@web161309.mail.bf1.yahoo.com> Message-ID: On Mon, Apr 11, 2011 at 1:01 PM, Sophie DeNofrio wrote: > Hi Everyone, > > I am a super beginner and am little muddled right now. So I apologize for > the low level question but I am trying to write a function that will return > a dictionary of a given list of strings containing two coordinates separated > by a space with the first numbers as a key and the second numbers as its > corresponding value. I thought maybe a set might be helpful but that didn't > seem to work at all. I am pretty much as confused as they come and any help > would be very much appreciated. Thank you so much for your time. > def createDictionary(data): result = {} for datapiece in data: # Code here to make coordinate1 and coordinate2 the values you want # Leaving that part to you, but feel free to ask again if you fail result[coordinate1] = coordinate2 return result -- Andr? Engels, andreengels at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Mon Apr 11 13:31:02 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Mon, 11 Apr 2011 06:31:02 -0500 Subject: [Tutor] A Dictionary question In-Reply-To: <194989.127.qm@web161309.mail.bf1.yahoo.com> References: <194989.127.qm@web161309.mail.bf1.yahoo.com> Message-ID: On Mon, Apr 11, 2011 at 6:01 AM, Sophie DeNofrio wrote: > Hi Everyone, > > I am a super beginner and am little muddled right now. So I apologize for > the low level question > That's what this list is for, so you're asking in the right place! > but I am trying to write a function that will return a dictionary of a > given list of strings containing two coordinates separated by a space with > the first numbers as a key and the second numbers as its corresponding > value. I thought maybe a set might be helpful but that didn't seem to work > at all. I am pretty much as confused as they come and any help would be very > much appreciated. Thank you so much for your time. > It's always helpful to give example input and output, as well as show us what you've done so far.It's *also* a good idea to tell us what your end goal is, rather than just "I have this data and I want to manipulate it thus", because oft times it turns out that there are much better ways to accomplish the end goal. Here's what it sounds like you say you want to do: line_xy = ['1 1', '2 2', '3 3', '4 4'] # Coordinates along the line y = x def dictify_list(coords): returnval = {} for pair in coords: x, y = pair.split() returnval[x] = y return returnval dictify_list(line_xy) # produces {'1':'1', '3':'3', '2':'2', '4':'4'} or some equivalent dict - they're non-ordered But I can't think of a time that I would want data collected this way. My guess is that unless you have a super special case, you don't really need the data that way either. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Mon Apr 11 14:09:57 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 11 Apr 2011 22:09:57 +1000 Subject: [Tutor] A Dictionary question In-Reply-To: <194989.127.qm@web161309.mail.bf1.yahoo.com> References: <194989.127.qm@web161309.mail.bf1.yahoo.com> Message-ID: <4DA2EF95.7040505@pearwood.info> Hello Sophie, or do you prefer Annie? Sophie DeNofrio wrote: > Hi Everyone, > I am a super beginner and am little muddled right now. So I apologize > for the low level question but I am trying to write a function that > will return a dictionary of a given list of strings containing two > coordinates separated by a space with the first numbers as a key and > the second numbers as its corresponding value. I thought maybe a set > might be helpful but that didn't seem to work at all. I am pretty > much as confused as they come and any help would be very much > appreciated. Thank you so much for your time. It will help if you give us an example of what your input data is, and what you expect to get for your result. I'm going to try to guess. I think your input data might look like this: data = ["1 2", "4 5", "23 42"] and you want to return a dictionary like: {1: 2, 4: 5, 23: 42} Am I close? This sounds like homework, and our policy is not to solve homework for people, but to guide them into solving it themselves. So here are some hints. Please feel free to show us the code you are using if you have any problems. You will need to have a dict ready to store keys and values in, and then you need to look at each string in the data list one at a time: result = {} # This is an empty dictionary. for s in data: # Process the variable s each time. print(s) Since s is a string that looks like two numbers separated by a space, processing the string needs two tasks: first you have to split the string into the two parts, and then you have to turn each part from a string into an actual number. (Remember that in Python, "42" is not a number, it is just a string that looks like a number.) There are two functions that are useful for that: one is a string method, and one is a proper function. Here are some examples to show them in action: # Splitting a string into two pieces: >>> s = "1234 5678" >>> s.split() ['1234', '5678'] # Converting a string into a proper number: >>> a = "987" >>> int(a) 987 The split method is especially useful when you use assignment to create two variables at once: >>> s = "1234 5678" >>> a, b = s.split() >>> a '1234' >>> b '5678' >>> int(a) 1234 Lastly, do you know how to store objects into a dictionary? You need two pieces, a key and a value: >>> d = {} # Empty dict. >>> key = "dinner" >>> value = "pizza" >>> d[key] = value >>> >>> print "What's for dinner?", d["dinner"] What's for dinner? pizza Only in your case, rather than storing strings in the dict, you want to store numbers created by int(). So now you have to put all the pieces together into one piece of code: (1) Create an empty dict. (2) Loop over the individual strings in the input list. (3) For each string, split it into two pieces. (4) Convert each piece into an int (integer). (5) Store the first piece in the dict as the key, and the second piece as the value. Good luck! -- Steven From swimbabe339 at yahoo.com Mon Apr 11 15:24:42 2011 From: swimbabe339 at yahoo.com (Sophie DeNofrio) Date: Mon, 11 Apr 2011 06:24:42 -0700 (PDT) Subject: [Tutor] A Dictionary question In-Reply-To: <4DA2EF95.7040505@pearwood.info> Message-ID: <912602.73903.qm@web161302.mail.bf1.yahoo.com> Thank you to everyone who helped! Steven D'Aprano I was secretly hoping you'd help. This is a family not personal and 'junk' (this isn't junk obviously. But it falls into that not personal category)?account so you are talking to Annie lol. I guess I should have just signed up using my own email address in retrospect. Thank you for walking me through what I have to do as I want to learn. That dictionary is a much smaller piece to a file reading program. Next time I will attach my code. I totally blanked on how helpful that would be. Thank you for taking time out of your day to explain so fully. :) ?? .___. {O,o} /)__) Annie -"-"- --- On Mon, 4/11/11, Steven D'Aprano wrote: From: Steven D'Aprano Subject: Re: [Tutor] A Dictionary question To: tutor at python.org Date: Monday, April 11, 2011, 8:09 AM Hello Sophie, or do you prefer Annie? Sophie DeNofrio wrote: > Hi Everyone, > I am a super beginner and am little muddled right now. So I apologize > for the low level question but I am trying to write a function that > will return a dictionary of a given list of strings containing two > coordinates separated by a space with the first numbers as a key and > the second numbers as its corresponding value. I thought maybe a set > might be helpful but that didn't seem to work at all. I am pretty > much as confused as they come and any help would be very much > appreciated. Thank you so much for your time. It will help if you give us an example of what your input data is, and what you expect to get for your result. I'm going to try to guess. I think your input data might look like this: data = ["1 2", "4 5", "23 42"] and you want to return a dictionary like: {1: 2, 4: 5, 23: 42} Am I close? This sounds like homework, and our policy is not to solve homework for people, but to guide them into solving it themselves. So here are some hints. Please feel free to show us the code you are using if you have any problems. You will need to have a dict ready to store keys and values in, and then you need to look at each string in the data list one at a time: result = {}? # This is an empty dictionary. for s in data: ? ? # Process the variable s each time. ? ? print(s) Since s is a string that looks like two numbers separated by a space, processing the string needs two tasks: first you have to split the string into the two parts, and then you have to turn each part from a string into an actual number. (Remember that in Python, "42" is not a number, it is just a string that looks like a number.) There are two functions that are useful for that: one is a string method, and one is a proper function. Here are some examples to show them in action: # Splitting a string into two pieces: >>> s = "1234 5678" >>> s.split() ['1234', '5678'] # Converting a string into a proper number: >>> a = "987" >>> int(a) 987 The split method is especially useful when you use assignment to create two variables at once: >>> s = "1234 5678" >>> a, b = s.split() >>> a '1234' >>> b '5678' >>> int(a) 1234 Lastly, do you know how to store objects into a dictionary? You need two pieces, a key and a value: >>> d = {}? # Empty dict. >>> key = "dinner" >>> value = "pizza" >>> d[key] = value >>> >>> print "What's for dinner?", d["dinner"] What's for dinner? pizza Only in your case, rather than storing strings in the dict, you want to store numbers created by int(). So now you have to put all the pieces together into one piece of code: (1) Create an empty dict. (2) Loop over the individual strings in the input list. (3) For each string, split it into two pieces. (4) Convert each piece into an int (integer). (5) Store the first piece in the dict as the key, and the second piece as the value. Good luck! -- 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 msilvers321 at gmail.com Mon Apr 11 15:01:37 2011 From: msilvers321 at gmail.com (Mike Silverson) Date: Mon, 11 Apr 2011 21:01:37 +0800 Subject: [Tutor] Running python on windows Message-ID: Hi, I need to know if there is any way to run a python file without Python installed on the target computer. I am trying to send a program to a friend using windows and he does not have python installed, and does not want to take the time to install it. Is there any way to send him the file (or a group of files) that will run right away? -------------- next part -------------- An HTML attachment was scrubbed... URL: From sunil.techspk at gmail.com Mon Apr 11 19:40:56 2011 From: sunil.techspk at gmail.com (sunil tech) Date: Mon, 11 Apr 2011 23:10:56 +0530 Subject: [Tutor] Converting files Message-ID: Hi all... is there any way to convert any file (eg: document files & image files) to .pdf? if so, kindly share... thank you in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: From karim.liateni at free.fr Mon Apr 11 19:50:34 2011 From: karim.liateni at free.fr (Karim) Date: Mon, 11 Apr 2011 19:50:34 +0200 Subject: [Tutor] Generating XML using Python In-Reply-To: References: , Message-ID: <4DA33F6A.4010504@free.fr> On 04/11/2011 10:04 AM, tee chwee liong wrote: > hi Peter, > > thanks for your reply. seems that xml doesnt accept a space in between. > anyway, the output generated is: > *-* > *-* > > ** *2* > ** *3* > ** > ** > > it overwrites every time the port number is incremented and only > capture the last iteration number. how can i modify it to capture all > the iteration? for eg: > Port 1 > Link speed: 2 > Target speed: 3 > Port 2 > Link speed: 2 > Target speed: 3 > Port 3 > Link speed: 2 > Target speed: 3 > Port 4 > Link speed: 2 > Target speed: 3 > Port 5 > Link speed: 2 > Target speed: 3 > Port 6 > Link speed: 2 > Target speed: 3 > Port 7 > Link speed: 2 > Target speed: 3 > Port 8 > Link speed: 2 > Target speed: 3 > > thanks > tcl > > for config in doctree_instance.iter('Default_ConfigPort'): link = config.find('LINK') target = config.find('Target_Speed') print('Port ', config.attrib['Port']) print('Link speed:', link.text) print('Target speed:', target.text) Regards > > > _______________________________________________ > 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 nick.holley at gmail.com Mon Apr 11 20:20:56 2011 From: nick.holley at gmail.com (Nicholas Holley) Date: Mon, 11 Apr 2011 12:20:56 -0600 Subject: [Tutor] Running python on windows In-Reply-To: References: Message-ID: <20110411122056.0829573e@gmail.com> On Mon, 11 Apr 2011 21:01:37 +0800 Mike Silverson wrote: > Hi, I need to know if there is any way to run a python file without > Python installed on the target computer. I am trying to send a > program to a friend using windows and he does not have python > installed, and does not want to take the time to install it. Is > there any way to send him the file (or a group of files) that will > run right away? http://py2exe.org/ is one such method and will probably be your easiest. From emile at fenx.com Mon Apr 11 20:57:36 2011 From: emile at fenx.com (Emile van Sebille) Date: Mon, 11 Apr 2011 11:57:36 -0700 Subject: [Tutor] Converting files In-Reply-To: References: Message-ID: On 4/11/2011 10:40 AM sunil tech said... > Hi all... > > is there any way to convert any file (eg: document files & image files) > to .pdf? > Look into reportlab. Look at the opensource area: http://www.reportlab.com/software/opensource/ > if so, kindly share... > > thank you in advance. > > > > _______________________________________________ > 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 Mon Apr 11 22:20:44 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 11 Apr 2011 21:20:44 +0100 Subject: [Tutor] Python on TV Message-ID: I've just watched the Channel 5 programme "The Gadget Show" where the presenters set a new Guinness world record for operating the heaviest machine(*) using mind power. The software behind this feat - was written in Python of course! :-) (*)The machine in question was a 50 ton industrial crane... used to move a car from one end of a warehouse to the other. The show should be here - Pause at 1 minute 20 for the Python screnshot: http://fwd.channel5.com/gadget-show/videos/challenge/surprise-special-part-4 Enjoy :-) Alan G. From eire1130 at gmail.com Mon Apr 11 22:27:00 2011 From: eire1130 at gmail.com (James Reynolds) Date: Mon, 11 Apr 2011 16:27:00 -0400 Subject: [Tutor] Running python on windows In-Reply-To: References: Message-ID: I use http://cx-freeze.sourceforge.net/ personally. I found py2exe to be a headache compared to cx. On Mon, Apr 11, 2011 at 9:01 AM, Mike Silverson wrote: > Hi, I need to know if there is any way to run a python file without Python > installed on the target computer. I am trying to send a program to a friend > using windows and he does not have python installed, and does not want to > take the time to install it. Is there any way to send him the file (or a > group of files) that will run right away? > _______________________________________________ > 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 alan.gauld at btinternet.com Mon Apr 11 22:44:28 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 11 Apr 2011 21:44:28 +0100 Subject: [Tutor] Running python on windows References: Message-ID: "Mike Silverson" wrote > installed on the target computer. I am trying to send a program to > a friend > using windows and he does not have python installed, and does not > want to > take the time to install it. Given how quickly Python installs compared to many other apps I can only assume he uses Wordpad as his word processor?! Honestly you could just build an installer that installed Python and your files and I doubt he'd notice the install time as being excessive! However, there is no way to run Python without installing an interpreter. If you don't use a standalone install you need to build the interpreter into an exe and then install a separate python installation for every app he uses. Its mad. Does he refuse to install .Net or Java or the VisualBasic runtime? But if he must there are several options available, the best known is py2exe but there are others out there. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From bteeuwen at gmail.com Mon Apr 11 22:29:33 2011 From: bteeuwen at gmail.com (Ben Teeuwen) Date: Mon, 11 Apr 2011 22:29:33 +0200 Subject: [Tutor] ImportError: No module named wdmmgext.load Message-ID: <25923943-B032-4FB6-A64A-7870E7FD49E7@gmail.com> Hi, Thanks Emile van Sebille for answering my last question. I'm now testing my imported data and I get 21 errors (see attached). The majority sounds like: from wdmmgext.load import uganda ImportError: No module named wdmmgext.load I've searched the files that use this module. Attached is an example file. I see 2 more errors; 1) that the file 'ukgov-finances-cra/cra_2009_db.csv' does not exist. 2) SolrException: HTTP code=404, reason=Not Found Maybe both are due to the wdmmgext.load error, so I'll ignore this for now and first try to find answer to my first question. Thanks in advance for the help! Ben -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: example.txt URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: error.txt URL: From alan.gauld at btinternet.com Mon Apr 11 22:48:18 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 11 Apr 2011 21:48:18 +0100 Subject: [Tutor] Converting files References: Message-ID: "sunil tech" wrote > is there any way to convert any file (eg: document files & image > files) to > .pdf? > > if so, kindly share... Install a PDF print driver and then print the file to that printer. Set it to save as a file. Then if its printable you can get it as a PDF. You can do the same with postscript(and postscript drivers come with most OS). Then send the postscript file to Adobe's web site to get them to generate the PDF from postscript. (You can also download free convertors) Finally, and because this is a Python list, you could use a Python library and generate the file yourself - but while thats ok for your own data its a lot harder for many file types! HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From eire1130 at gmail.com Mon Apr 11 23:01:35 2011 From: eire1130 at gmail.com (James Reynolds) Date: Mon, 11 Apr 2011 17:01:35 -0400 Subject: [Tutor] Running python on windows In-Reply-To: References: Message-ID: At least in my case it was about simplicity. If it was a simple matter of using a base python program, that would be one thing, but the last program i distributed here at work used pygtk as it's GUI (which at the time required four different packages, I believe they have consolidated this down to one, thank god), a month / date arithmetic module a few other modules I can't remember off the top of my head. It doesn't make sense to say, go here, install this, ok, now drop this in this folder, ok now drop this in that folder, ok now open your command prompt and type this string of words. But don't typo while your at it. It took all of five minutes to learn how to use CX enough so I could freeze something and send it around to people here to use. It would have taken 30 minutes to explain how to install each component to people who just want stuff to work. On Mon, Apr 11, 2011 at 4:44 PM, Alan Gauld wrote: > > "Mike Silverson" wrote > > installed on the target computer. I am trying to send a program to a >> friend >> using windows and he does not have python installed, and does not want to >> take the time to install it. >> > > Given how quickly Python installs compared to many other apps I > can only assume he uses Wordpad as his word processor?! Honestly > you could just build an installer that installed Python and your files > and I doubt he'd notice the install time as being excessive! > > However, there is no way to run Python without installing an interpreter. > If you don't use a standalone install you need to build the interpreter > into an exe and then install a separate python installation for every app > he uses. Its mad. Does he refuse to install .Net or Java or the > VisualBasic runtime? > > But if he must there are several options available, the best known > is py2exe but there are others out there. > > -- > Alan Gauld > 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 Mon Apr 11 23:04:43 2011 From: bgailer at gmail.com (bob gailer) Date: Mon, 11 Apr 2011 17:04:43 -0400 Subject: [Tutor] Python on TV In-Reply-To: References: Message-ID: <4DA36CEB.7090507@gmail.com> On 4/11/2011 4:20 PM, Alan Gauld wrote: > I've just watched the Channel 5 programme "The Gadget Show" > where the presenters set a new Guinness world record for operating > the heaviest machine(*) using mind power. The software behind > this feat - was written in Python of course! :-) > > (*)The machine in question was a 50 ton industrial crane... used > to move a car from one end of a warehouse to the other. > > The show should be here - Pause at 1 minute 20 for the > Python screnshot: > > http://fwd.channel5.com/gadget-show/videos/challenge/surprise-special-part-4 > I am told "the video ... cannot be viewed from your currrent country ..." Sigh. -- Bob Gailer 919-636-4239 Chapel Hill NC From scarolan at gmail.com Mon Apr 11 23:05:40 2011 From: scarolan at gmail.com (Sean Carolan) Date: Mon, 11 Apr 2011 16:05:40 -0500 Subject: [Tutor] Import multiple lines of text into a variable Message-ID: I'm not sure how to do this. I'm reading lines in from a text file. When I reach the string "notes:", I want to assign the remainder of the text file to a single variable (line breaks and all): text moretext moretext notes: This is the stuff I want in my variable. And this line should be included too. Also this one. So right now my code looks something like this: for line in open('myfile','r'): if line.startswith('notes'): ## Assign rest of file to variable Is there an easy way to do this? Or do I need to read the entire file as a string first and carve it up from there instead? From onyxtic at gmail.com Mon Apr 11 23:08:35 2011 From: onyxtic at gmail.com (Evans Anyokwu) Date: Mon, 11 Apr 2011 22:08:35 +0100 Subject: [Tutor] Converting files In-Reply-To: References: Message-ID: I use Openoffice and it has an option to export your files to .pdf and lots of other file formats. It's a free download - and has all the usual Office applications... Search for 'OpenOffice' online. On Mon, Apr 11, 2011 at 9:48 PM, Alan Gauld wrote: > > "sunil tech" wrote > > > is there any way to convert any file (eg: document files & image files) to >> .pdf? >> >> if so, kindly share... >> > > Install a PDF print driver and then print the file to that printer. > Set it to save as a file. Then if its printable you can get it as a PDF. > > You can do the same with postscript(and postscript drivers > come with most OS). Then send the postscript file to Adobe's > web site to get them to generate the PDF from postscript. > (You can also download free convertors) > > Finally, and because this is a Python list, you could use a > Python library and generate the file yourself - but while thats > ok for your own data its a lot harder for many file types! > > HTH, > > -- > Alan Gauld > 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 scarolan at gmail.com Mon Apr 11 23:14:26 2011 From: scarolan at gmail.com (Sean Carolan) Date: Mon, 11 Apr 2011 16:14:26 -0500 Subject: [Tutor] Import multiple lines of text into a variable In-Reply-To: References: Message-ID: > So right now my code looks something like this: > > for line in open('myfile','r'): > ?if line.startswith('notes'): > ? ? ?## Assign rest of file to variable > > Is there an easy way to do this? ?Or do I need to read the entire file > as a string first and carve it up from there instead? I ended up doing this, but please reply if you have a more elegant solution: if line.startswith('notes'): break notes = open('myfile','r').read().split(notes:\n')[1] From bgailer at gmail.com Mon Apr 11 23:24:05 2011 From: bgailer at gmail.com (bob gailer) Date: Mon, 11 Apr 2011 17:24:05 -0400 Subject: [Tutor] Import multiple lines of text into a variable In-Reply-To: References: Message-ID: <4DA37175.6000006@gmail.com> On 4/11/2011 5:14 PM, Sean Carolan wrote: >> So right now my code looks something like this: >> >> for line in open('myfile','r'): >> if line.startswith('notes'): >> ## Assign rest of file to variable >> >> Is there an easy way to do this? Or do I need to read the entire file >> as a string first and carve it up from there instead? > I ended up doing this, but please reply if you have a more elegant solution: > > if line.startswith('notes'): > break > notes = open('myfile','r').read().split(notes:\n')[1] Seems like an elegant solution to me, as long as the file fits available memory. There will be 2 copies of the file after the split. Another way: textFile = open('myfile','r') for line in textFile: if line.startswith('notes'): notes = textFile.read() -- Bob Gailer 919-636-4239 Chapel Hill NC From alan.gauld at btinternet.com Mon Apr 11 23:24:32 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Mon, 11 Apr 2011 22:24:32 +0100 (BST) Subject: [Tutor] Running python on windows In-Reply-To: References: Message-ID: <205822.65208.qm@web86702.mail.ird.yahoo.com> > At least in my case it was about simplicity. If it was a simple matter of using > > a base python program, that would be one thing, but the last program i > distributed here at work used pygtk as it's GUI Valid comment although its not much more work to build a custom installer that installs Python plus all the other libs. And checks that they aren't already there first... However due to the incompatibility issues around v3 I'm much less anti-packages than I used to be. But I do think the reluctance to install Python is not a valid reason, it's not much different to installing a JVM for java. > It doesn't make sense to say, go here, install this, ok, now drop > this in this folder, ok now drop this in that folder, ok now open > your command prompt and type this string Agreed, we need to package our apps so the user doesn't need to do this. But that doesn't necessariily mean creating a packed exe. But sadly that usually means using a third party installer, and the best of those are all commercial so it costs $$$. Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Mon Apr 11 23:55:45 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Mon, 11 Apr 2011 16:55:45 -0500 Subject: [Tutor] Running python on windows In-Reply-To: <205822.65208.qm@web86702.mail.ird.yahoo.com> References: <205822.65208.qm@web86702.mail.ird.yahoo.com> Message-ID: On Mon, Apr 11, 2011 at 4:24 PM, ALAN GAULD wrote: > > It doesn't make sense to say, go here, install this, ok, now drop > > this in this folder, ok now drop this in that folder, ok now open > > your command prompt and type this string > > Agreed, we need to package our apps so the user doesn't need to > do this. But that doesn't necessariily mean creating a packed exe. > But sadly that usually means using a third party installer, and the > best of those are all commercial so it costs $$$. > The best, yes, but the likes of InnoSetup or NSIS are free, and fairly reasonable to use. Once I graduate, I suspect it won't be long before I've built a few templates around one or the other specifically designed for Python. I'm not aware if anyone else has done such things. -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From karim.liateni at free.fr Tue Apr 12 02:40:39 2011 From: karim.liateni at free.fr (Karim) Date: Tue, 12 Apr 2011 02:40:39 +0200 Subject: [Tutor] Generating XML using Python In-Reply-To: <4DA33F6A.4010504@free.fr> References: , <4DA33F6A.4010504@free.fr> Message-ID: <4DA39F87.7030300@free.fr> On 04/11/2011 07:50 PM, Karim wrote: > On 04/11/2011 10:04 AM, tee chwee liong wrote: >> hi Peter, >> >> thanks for your reply. seems that xml doesnt accept a space in between. >> anyway, the output generated is: >> *-* >> *-* >> >> ** *2* >> ** *3* >> ** >> ** >> >> it overwrites every time the port number is incremented and only >> capture the last iteration number. how can i modify it to capture all >> the iteration? for eg: >> Port 1 >> Link speed: 2 >> Target speed: 3 >> Port 2 >> Link speed: 2 >> Target speed: 3 >> Port 3 >> Link speed: 2 >> Target speed: 3 >> Port 4 >> Link speed: 2 >> Target speed: 3 >> Port 5 >> Link speed: 2 >> Target speed: 3 >> Port 6 >> Link speed: 2 >> Target speed: 3 >> Port 7 >> Link speed: 2 >> Target speed: 3 >> Port 8 >> Link speed: 2 >> Target speed: 3 >> >> thanks >> tcl >> >> > Sorry for the error, must remove ' Port' in iter() this example use std lib xml.etree.ElementTree doctree_instance obtain through parse() method from ElementTree and it works with infinite tag 'default_Config' list: > for config in doctree_instance.iter('Default_Config'): > link = config.find('LINK') > target = config.find('Target_Speed') > > print('Port ', config.attrib['Port']) > print('Link speed:', link.text) > print('Target speed:', target.text) > > Regards >> >> >> _______________________________________________ >> 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 -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Apr 12 02:41:37 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 12 Apr 2011 01:41:37 +0100 Subject: [Tutor] Import multiple lines of text into a variable References: Message-ID: "Sean Carolan" wrote > I ended up doing this, but please reply if you have a more elegant > solution: > > if line.startswith('notes'): > break > notes = open('myfile','r').read().split(notes:\n')[1] The first two lines are redundant you only need the last one. HTH, Alan G. From scarolan at gmail.com Tue Apr 12 03:27:29 2011 From: scarolan at gmail.com (Sean Carolan) Date: Mon, 11 Apr 2011 20:27:29 -0500 Subject: [Tutor] Import multiple lines of text into a variable In-Reply-To: References: Message-ID: >> if line.startswith('notes'): >> ? break >> notes = open('myfile','r').read().split(notes:\n')[1] > > The first two lines are redundant you only need the last one. I should have clarified, the "if line.startswith" part was used to break out of the previous for loop, which was used to import the other, shorter strings. From tcl76 at hotmail.com Tue Apr 12 08:28:53 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Tue, 12 Apr 2011 06:28:53 +0000 Subject: [Tutor] Generating/Parsing XML Message-ID: hi, i'm a bit stuck here. i have a code dict1.py that writes to an xml and another script parsedict1.py to parse the content of the xml. when i write it to the xml i wrote it as dictionary but since it can't accept dict format i convert it to string. below is output of the parsedict1.py when i print it out. >>>(None, '{1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6}') >>>(None, '{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}') Questions: Why it shows as None and not LINK or Lanestat? How can i modify the code to show LINK or Lanestat? How can i extract the key in the dictionary since there are 2 elements only. for eg: if i print a[1], it will show {1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6}. i want to be able to extract info like this: Link [1] = 1, just like how it is done in dictionary. pls help to advise. thanks tcl p/s: attached code for dict1.py, parsedict1.py, dict1.xml dict1.py code: import elementtree.ElementTree as ET def port_status(): a=1 b=2 c=3 d=4 e=5 f=6 return (a,b,c,d,e,f) call_port=port_status() link_status={1:call_port[0], 2:call_port[1], 3:call_port[2], 4:call_port[3], 5:call_port[4], 6:call_port[5]} lane_status={1:call_port[0]+1, 2:call_port[1]+2, 3:call_port[2]+3, 4:call_port[3]+4, 5:call_port[4]+5, 6:call_port[5]+6} print link_status print lane_status ###write to xml root = ET.Element("Test") head1 = ET.SubElement(root, "Default_Config") title = ET.SubElement(head1, "LINK") title.text = str(link_status) title = ET.SubElement(head1, "Lanestat") title.text = str(lane_status) tree = ET.ElementTree(root) tree.write("C:\\Python25\\myscript\\cmm\\dict1.xml") parsedict1.py code: import elementtree.ElementTree as ET tree = ET.parse("dict1.xml") doc = tree.getroot() for elem in doc.findall('Default_Config/LINK'): #print elem.get('LINK'), elem.text a=elem.get('LINK'), elem.text print a for elem in doc.findall('Default_Config/Lanestat'): #print elem.get('LINK'), elem.text a=elem.get('LINK'), elem.text print a -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: dict1.py URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: dict1.xml Type: text/xml Size: 154 bytes Desc: not available URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: parsedict1.py URL: From alan.gauld at btinternet.com Tue Apr 12 09:27:15 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 12 Apr 2011 08:27:15 +0100 Subject: [Tutor] Import multiple lines of text into a variable References: Message-ID: "Sean Carolan" wrote > > The first two lines are redundant you only need the last one. > > I should have clarified, the "if line.startswith" part was used to > break out of the previous for loop, which was used to import the > other, shorter strings. Thats fair enough if you are doing something with those shorter strings. But if not the whole loop is redundant, you only need the split. Your original post did not mention any processing of the earlier lines. But even if you were you could still use the split() first then process the first element in a loop and assign the second element to your variable: stuff, store = theFile.read().split('notes\n') for line in stuff.split(): # process thing That way there is no need for a break test. HTH., -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From sunil.techspk at gmail.com Tue Apr 12 10:02:14 2011 From: sunil.techspk at gmail.com (sunil tech) Date: Tue, 12 Apr 2011 13:32:14 +0530 Subject: [Tutor] Converting files In-Reply-To: References: Message-ID: thank you for all your valuable suggestions... but i want it to be converted using python code .. On Tue, Apr 12, 2011 at 2:38 AM, Evans Anyokwu wrote: > I use Openoffice and it has an option to export your files to .pdf and lots > of other file formats. > It's a free download - and has all the usual Office applications... > > Search for 'OpenOffice' online. > > > On Mon, Apr 11, 2011 at 9:48 PM, Alan Gauld wrote: > >> >> "sunil tech" wrote >> >> >> is there any way to convert any file (eg: document files & image files) >>> to >>> .pdf? >>> >>> if so, kindly share... >>> >> >> Install a PDF print driver and then print the file to that printer. >> Set it to save as a file. Then if its printable you can get it as a PDF. >> >> You can do the same with postscript(and postscript drivers >> come with most OS). Then send the postscript file to Adobe's >> web site to get them to generate the PDF from postscript. >> (You can also download free convertors) >> >> Finally, and because this is a Python list, you could use a >> Python library and generate the file yourself - but while thats >> ok for your own data its a lot harder for many file types! >> >> HTH, >> >> -- >> Alan Gauld >> 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 >> > > > _______________________________________________ > 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 andres at chandia.net Tue Apr 12 10:08:17 2011 From: andres at chandia.net (=?iso-8859-1?Q?=22Andr=E9s_Chand=EDa=22?=) Date: Tue, 12 Apr 2011 10:08:17 +0200 Subject: [Tutor] Converting files In-Reply-To: References: Message-ID: <9dfe2d02bc51a181dc91b4cec4ca83d8.squirrel@mail.chandia.net> I don't know how to do it, but I'm 99% sure I have seen a something related in cherrypy pages, try googling "cherrypy pdf generation" or something similiar Good luck! El Mar, 12 de Abril de 2011, 10:02, sunil tech escribi?: thank you for all your valuable suggestions... but i want it to be converted using python code .. On Tue, Apr 12, 2011 at 2:38 AM, Evans Anyokwu onyxtic at gmail.com> wrote: I use Openoffice and it has an option to export your files to .pdf and lots of other file formats. It's a free download - and has all the usual Office applications... Search for 'OpenOffice' online. ? On Mon, Apr 11, 2011 at 9:48 PM, Alan Gauld alan.gauld at btinternet.com> wrote: "sunil tech" sunil.techspk at gmail.com> wrote is there any way to convert any file (eg: document files & image files) to .pdf? if so, kindly share... Install a PDF print driver and then print the file to that printer. Set it to save as a file. Then if its printable you can get it as a PDF. You can do the same with postscript(and postscript drivers come with most OS). Then send the postscript file to Adobe's web site to get them to generate the PDF from postscript. (You can also download free convertors) Finally, and because this is a Python list, ?you could use a Python library and generate the file yourself - but while thats ok for your own data its a lot harder for many file types! HTH, -- Alan Gauld 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 _______________________________________________ Tutor maillist ?- ?Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor _______________________ ????????????andr?s chand?a P No imprima innecesariamente. ?Cuide el medio ambiente! -------------- next part -------------- An HTML attachment was scrubbed... URL: From andres at chandia.net Tue Apr 12 10:12:18 2011 From: andres at chandia.net (=?iso-8859-1?Q?=22Andr=E9s_Chand=EDa=22?=) Date: Tue, 12 Apr 2011 10:12:18 +0200 Subject: [Tutor] Converting files In-Reply-To: References: Message-ID: this is the list for cherrypy "cherrypy-users" El Mar, 12 de Abril de 2011, 10:02, sunil tech escribi?: thank you for all your valuable suggestions... but i want it to be converted using python code .. On Tue, Apr 12, 2011 at 2:38 AM, Evans Anyokwu onyxtic at gmail.com> wrote: I use Openoffice and it has an option to export your files to .pdf and lots of other file formats. It's a free download - and has all the usual Office applications... Search for 'OpenOffice' online. ? On Mon, Apr 11, 2011 at 9:48 PM, Alan Gauld alan.gauld at btinternet.com> wrote: "sunil tech" sunil.techspk at gmail.com> wrote is there any way to convert any file (eg: document files & image files) to .pdf? if so, kindly share... Install a PDF print driver and then print the file to that printer. Set it to save as a file. Then if its printable you can get it as a PDF. You can do the same with postscript(and postscript drivers come with most OS). Then send the postscript file to Adobe's web site to get them to generate the PDF from postscript. (You can also download free convertors) Finally, and because this is a Python list, ?you could use a Python library and generate the file yourself - but while thats ok for your own data its a lot harder for many file types! HTH, -- Alan Gauld 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 _______________________________________________ Tutor maillist ?- ?Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor _______________________ ????????????andr?s chand?a P No imprima innecesariamente. ?Cuide el medio ambiente! -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Tue Apr 12 14:02:52 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 12 Apr 2011 22:02:52 +1000 Subject: [Tutor] Converting files In-Reply-To: References: Message-ID: <4DA43F6C.6030305@pearwood.info> sunil tech wrote: > Hi all... > > is there any way to convert any file (eg: document files & image files) to > .pdf? If the file is printable, print it to a PDF gateway that generates a PS or PDF file. If it is a Microsoft Office document, or similar, then install OpenOffice or LibreOffice and use it to convert to PDF. If it's not printable, then your question doesn't make sense. What would an ISO or EXE or ZIP file look like converted to PDF? But I wonder whether you bothered to google for "python pdf" first? The very first link is a comprehensive review of installing and using a PDF generator from Python. -- Steven From steve at pearwood.info Tue Apr 12 13:58:33 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 12 Apr 2011 21:58:33 +1000 Subject: [Tutor] Import multiple lines of text into a variable In-Reply-To: References: Message-ID: <4DA43E69.1090900@pearwood.info> Sean Carolan wrote: >>> if line.startswith('notes'): >>> break >>> notes = open('myfile','r').read().split(notes:\n')[1] >> The first two lines are redundant you only need the last one. > > I should have clarified, the "if line.startswith" part was used to > break out of the previous for loop, which was used to import the > other, shorter strings. Just for reference, "import" has special meaning in Python, and you hurt my brain by using it as a synonym for "read". For what it's worth, here's my solution. Rather than use the funky new "open files are iterable" feature, go back to the old-style way of reading line by line: # untested fp = open("myfile.txt") for while True: line = fp.readline() # read one line if not line: # nothing left to read break if "ham" in line: process_ham(line) # Mmmm, processed ham... if "spam" in line: process_spam(line) if line.startswith("notes"): notes = fp.read() # reads the rest of the file fp.close() Note that it is okay to mix calls to read() and readline(), but it is NOT okay to mix iteration over a file with calls to read() or readline(). -- Steven From l.leichtnam at gmail.com Tue Apr 12 18:40:45 2011 From: l.leichtnam at gmail.com (l.leichtnam at gmail.com) Date: Tue, 12 Apr 2011 16:40:45 +0000 Subject: [Tutor] Print images links Message-ID: <1430940022-1302626445-cardhu_decombobulator_blackberry.rim.net-640939092-@bda740.bisx.prod.on.blackberry> Hello, I would like to print the adresses of every image that are on the main page of www.columbia.edu. Do you know how to do this? Thanks Sent from my BlackBerry? on the MetroPCS Network From l.leichtnam at gmail.com Tue Apr 12 18:36:25 2011 From: l.leichtnam at gmail.com (l.leichtnam at gmail.com) Date: Tue, 12 Apr 2011 16:36:25 +0000 Subject: [Tutor] Retrieve data Message-ID: <177984764-1302626185-cardhu_decombobulator_blackberry.rim.net-2107943262-@bda740.bisx.prod.on.blackberry> Hello everyone, I would to retrieve data, and especially the temperature and the weather from http://www.nytimes.com/weather. And I don't know how to do so. Thank you, Louis Sent from my BlackBerry? on the MetroPCS Network From enalicho at gmail.com Tue Apr 12 18:57:03 2011 From: enalicho at gmail.com (Noah Hall) Date: Tue, 12 Apr 2011 17:57:03 +0100 Subject: [Tutor] Print images links In-Reply-To: <1430940022-1302626445-cardhu_decombobulator_blackberry.rim.net-640939092-@bda740.bisx.prod.on.blackberry> References: <1430940022-1302626445-cardhu_decombobulator_blackberry.rim.net-640939092-@bda740.bisx.prod.on.blackberry> Message-ID: On Tue, Apr 12, 2011 at 5:40 PM, wrote: > Hello, > > I would like to print the adresses of every image that are on the main page of www.columbia.edu. Do you know how to do this? Yes, I do. ;) As this sounds like homework - Firstly, you want to grab the source code of the webpage. Secondly, you want to find what defines each image link - I'll give you a clue, think of HTML markup for images. Thirdly, use a regex to extract the link and either print it directly, or put it into something you can reuse later. Hope this helps. From ramit.prasad at jpmchase.com Tue Apr 12 18:47:13 2011 From: ramit.prasad at jpmchase.com (Prasad, Ramit) Date: Tue, 12 Apr 2011 12:47:13 -0400 Subject: [Tutor] Print images links In-Reply-To: <1430940022-1302626445-cardhu_decombobulator_blackberry.rim.net-640939092-@bda740.bisx.prod.on.blackberry> References: <1430940022-1302626445-cardhu_decombobulator_blackberry.rim.net-640939092-@bda740.bisx.prod.on.blackberry> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2D960B5BF1@EMARC112VS01.exchad.jpmchase.net> I would use urllib2 with Python (for 2.x) plus some regular expressions. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -----Original Message----- From: tutor-bounces+ramit.prasad=jpmchase.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmchase.com at python.org] On Behalf Of l.leichtnam at gmail.com Sent: Tuesday, April 12, 2011 11:41 AM To: tutor at python.org; tutor-bounces at python.org Subject: [Tutor] Print images links Hello, I would like to print the adresses of every image that are on the main page of www.columbia.edu. Do you know how to do this? Thanks Sent from my BlackBerry(r) on the MetroPCS Network _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase & Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase & Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities. From rafadurancastaneda at gmail.com Tue Apr 12 21:59:02 2011 From: rafadurancastaneda at gmail.com (=?ISO-8859-1?Q?Rafael_Dur=E1n_Casta=F1eda?=) Date: Tue, 12 Apr 2011 21:59:02 +0200 Subject: [Tutor] Retrieve data In-Reply-To: <177984764-1302626185-cardhu_decombobulator_blackberry.rim.net-2107943262-@bda740.bisx.prod.on.blackberry> References: <177984764-1302626185-cardhu_decombobulator_blackberry.rim.net-2107943262-@bda740.bisx.prod.on.blackberry> Message-ID: You cand use urllib to connect that web page and then use a custom html parser to get exactly what you want, even I think you could use regex; just look source code from the webpage, check for the data you are interested in and get it. 2011/4/12 > Hello everyone, > > I would to retrieve data, and especially the temperature and the weather > from http://www.nytimes.com/weather. And I don't know how to do so. > > Thank you, > > Louis > Sent from my BlackBerry? on the MetroPCS Network > _______________________________________________ > 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 eire1130 at gmail.com Tue Apr 12 22:21:42 2011 From: eire1130 at gmail.com (James Reynolds) Date: Tue, 12 Apr 2011 16:21:42 -0400 Subject: [Tutor] Retrieve data In-Reply-To: <177984764-1302626185-cardhu_decombobulator_blackberry.rim.net-2107943262-@bda740.bisx.prod.on.blackberry> References: <177984764-1302626185-cardhu_decombobulator_blackberry.rim.net-2107943262-@bda740.bisx.prod.on.blackberry> Message-ID: NYtimes has an API http://developer.nytimes.com/ No clue on how well it works or even if the weather is in the API. Looks like a lot of fluff, like comments and such. At any rate, maybe you can request they add weather to their API. On Tue, Apr 12, 2011 at 12:36 PM, wrote: > Hello everyone, > > I would to retrieve data, and especially the temperature and the weather > from http://www.nytimes.com/weather. And I don't know how to do so. > > Thank you, > > Louis > Sent from my BlackBerry? on the MetroPCS Network > _______________________________________________ > 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 Wed Apr 13 01:07:01 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 13 Apr 2011 09:07:01 +1000 Subject: [Tutor] Print images links In-Reply-To: <1430940022-1302626445-cardhu_decombobulator_blackberry.rim.net-640939092-@bda740.bisx.prod.on.blackberry> References: <1430940022-1302626445-cardhu_decombobulator_blackberry.rim.net-640939092-@bda740.bisx.prod.on.blackberry> Message-ID: <4DA4DB15.7050308@pearwood.info> l.leichtnam at gmail.com wrote: > Hello, > > I would like to print the adresses of every image that are on the main page of www.columbia.edu. Do you know how to do this? Pretty much the same answer applies as for your previous question. -- Steven From steve at pearwood.info Wed Apr 13 01:03:27 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 13 Apr 2011 09:03:27 +1000 Subject: [Tutor] Retrieve data In-Reply-To: <177984764-1302626185-cardhu_decombobulator_blackberry.rim.net-2107943262-@bda740.bisx.prod.on.blackberry> References: <177984764-1302626185-cardhu_decombobulator_blackberry.rim.net-2107943262-@bda740.bisx.prod.on.blackberry> Message-ID: <4DA4DA3F.8060809@pearwood.info> l.leichtnam at gmail.com wrote: > Hello everyone, > > I would to retrieve data, and especially the temperature and the weather from http://www.nytimes.com/weather. And I don't know how to do so. Consider whether the NY Times terms and conditions permit such automated scraping of their web site. Be careful you do not abuse their hospitality by hammering their web site unnecessarily (say, by checking the weather eighty times a minute). Consider whether they have a public API for downloading data directly. If so, use that. Otherwise: Use the urlib2 and urlib modules to download the raw HTML source of the page you are interested in. You may need to use them to login, to set cookies, set the referer [sic], submit data via forms, change the user-agent... it's a PITA. Better to use an API if the web site offers one. Use the htmllib module to parse the source looking for the information you are after. If their HTML is crap, as it so often is with commercial websites that should know better, download and install BeautifulSoup, and use that for parsing the HTML. Don't be tempted to use regexes for parsing the HTML. That is the wrong solution. Regexes *seem* like a good idea for parsing HTML, and for simple tasks they are quick to program, but they invariably end up being ten times as much work as a proper HTML parser. If the content you are after requires Javascript, you're probably out of luck. -- Steven From garybeynon at hotmail.co.uk Wed Apr 13 17:14:48 2011 From: garybeynon at hotmail.co.uk (Gary Beynon) Date: Wed, 13 Apr 2011 16:14:48 +0100 Subject: [Tutor] Python 3.2 - Running in Idle but not in command window Message-ID: -- Voice of a Noob! -- I am currently running through Python Programming for the Absolute Beginner and have written the attached program. It's not the code I've got a problem with (I think). In idle (Windows) when i press f5 it runs perfect but when I run it by double click from folder the program ignores my input (from menu) I do have ArcGIS (Python 2.6) & Python 2.5 installed. Are these causing a problem? Thanks for your help. Gary -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: footy_father_son.py Type: text/x-script.phyton Size: 3406 bytes Desc: not available URL: From alan.gauld at btinternet.com Wed Apr 13 18:57:49 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 13 Apr 2011 17:57:49 +0100 Subject: [Tutor] Python 3.2 - Running in Idle but not in command window References: Message-ID: "Gary Beynon" wrote > I do have ArcGIS (Python 2.6) & Python 2.5 installed. Are these causing a problem? Yes, in Python v2 input will return the numeric version of the number - ie it converts from the string. In Python v3 - which is what your program expects - input always returns a string. If you explicitly convert choice to an int and return that from menu and then test for the int option in your main code it should work in both Python versions. Either that or change the file association in Windows to always pick up Version 3 - but that may not be good if you have other v2 scripts on your PC... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From eire1130 at gmail.com Wed Apr 13 19:04:27 2011 From: eire1130 at gmail.com (James Reynolds) Date: Wed, 13 Apr 2011 13:04:27 -0400 Subject: [Tutor] Python 3.2 - Running in Idle but not in command window In-Reply-To: References: Message-ID: I double clicked it from my desktop and it opens just fine (though I didn't attempt to run it, because I have 2.6 on my work machine and I'm sure that will cause it to fail). Have you added python to Path environment variables in windows? On Wed, Apr 13, 2011 at 11:14 AM, Gary Beynon wrote: > -- Voice of a Noob! -- > > I am currently running through Python Programming for the Absolute Beginner > and have written the attached program. > > It's not the code I've got a problem with (I think). > > In idle (Windows) when i press f5 it runs perfect but when I run it by > double click from folder the program ignores my input (from menu) > > > > I do have ArcGIS (Python 2.6) & Python 2.5 installed. Are these causing a > problem? > > Thanks for your help. > Gary > > > _______________________________________________ > 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 eire1130 at gmail.com Wed Apr 13 19:06:11 2011 From: eire1130 at gmail.com (James Reynolds) Date: Wed, 13 Apr 2011 13:06:11 -0400 Subject: [Tutor] Python 3.2 - Running in Idle but not in command window In-Reply-To: References: Message-ID: Oh, belay my last, I misread the question. My apologies. On Wed, Apr 13, 2011 at 1:04 PM, James Reynolds wrote: > I double clicked it from my desktop and it opens just fine (though I didn't > attempt to run it, because I have 2.6 on my work machine and I'm sure that > will cause it to fail). > > Have you added python to Path environment variables in windows? > > On Wed, Apr 13, 2011 at 11:14 AM, Gary Beynon wrote: > >> -- Voice of a Noob! -- >> >> I am currently running through Python Programming for the Absolute >> Beginner and have written the attached program. >> >> It's not the code I've got a problem with (I think). >> >> In idle (Windows) when i press f5 it runs perfect but when I run it by >> double click from folder the program ignores my input (from menu) >> >> >> >> I do have ArcGIS (Python 2.6) & Python 2.5 installed. Are these causing a >> problem? >> >> Thanks for your help. >> Gary >> >> >> _______________________________________________ >> 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 jf_byrnes at comcast.net Wed Apr 13 22:33:42 2011 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Wed, 13 Apr 2011 15:33:42 -0500 Subject: [Tutor] Need help with the property function Message-ID: <4DA608A6.4040001@comcast.net> I'm trying to teach myself OOP in python (again). The following code from Dawson's book runs fine, unaltered [1]. class Critter(object): """ A virtual pet """ def __init__(self, name): print "A new critter is born" self.name = name def get_name(self): return self.__name def set_name(self, new_name): if new_name == "": print "A critters name cant be the empty string" else: self.__name = new_name print "Name change successful" name = property(get_name, set_name) #[1] # name = property(get_name) #[2] #different_name = property(get_name) #[3] def talk(self): print "Hi. I'm", self.name If I change [1] to [2] I get: Traceback (most recent call last): File "propertycritter.py", line 26, in crit = Critter("Poochie") File "propertycritter.py", line 7, in __init__ self.name = name AttributeError: can't set attribute If I change [1] to [3] the program runs with no errors. Could someone please explain why I am seeing these results. Thanks, Jim From ramit.prasad at jpmchase.com Wed Apr 13 22:37:42 2011 From: ramit.prasad at jpmchase.com (Prasad, Ramit) Date: Wed, 13 Apr 2011 16:37:42 -0400 Subject: [Tutor] Need help with the property function In-Reply-To: <4DA608A6.4040001@comcast.net> References: <4DA608A6.4040001@comcast.net> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2D961BEE13@EMARC112VS01.exchad.jpmchase.net> I do not think you can override a property. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -----Original Message----- From: tutor-bounces+ramit.prasad=jpmchase.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmchase.com at python.org] On Behalf Of Jim Byrnes Sent: Wednesday, April 13, 2011 3:34 PM To: tutor at python.org Subject: [Tutor] Need help with the property function I'm trying to teach myself OOP in python (again). The following code from Dawson's book runs fine, unaltered [1]. class Critter(object): """ A virtual pet """ def __init__(self, name): print "A new critter is born" self.name = name def get_name(self): return self.__name def set_name(self, new_name): if new_name == "": print "A critters name cant be the empty string" else: self.__name = new_name print "Name change successful" name = property(get_name, set_name) #[1] # name = property(get_name) #[2] #different_name = property(get_name) #[3] def talk(self): print "Hi. I'm", self.name If I change [1] to [2] I get: Traceback (most recent call last): File "propertycritter.py", line 26, in crit = Critter("Poochie") File "propertycritter.py", line 7, in __init__ self.name = name AttributeError: can't set attribute If I change [1] to [3] the program runs with no errors. Could someone please explain why I am seeing these results. Thanks, Jim _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase & Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase & Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities. From nookasree at yahoo.com Wed Apr 13 22:40:23 2011 From: nookasree at yahoo.com (nookasree ponamala) Date: Wed, 13 Apr 2011 13:40:23 -0700 (PDT) Subject: [Tutor] python clusters Message-ID: <330972.11210.qm@web65410.mail.ac4.yahoo.com> Hi I've 30 variables in a text file and I want to read this text file and create 10 clusters based on 18 variables. I want to read an other text file and find the closest match using these clusters Could you pls. help me with this. Thanks, Sree. From steve at pearwood.info Thu Apr 14 01:05:15 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 14 Apr 2011 09:05:15 +1000 Subject: [Tutor] python clusters In-Reply-To: <330972.11210.qm@web65410.mail.ac4.yahoo.com> References: <330972.11210.qm@web65410.mail.ac4.yahoo.com> Message-ID: <4DA62C2B.6090501@pearwood.info> nookasree ponamala wrote: > Hi > > I've 30 variables in a text file and I want to read this text file and create 10 clusters based on 18 variables. How do you get variables in a text file? Normally text files contain text. What is a cluster? How would you create 10 clusters based on 18 variables, if the variables were in memory? Do exactly the same thing, but read the variables from the test file first. > I want to read an other text file and find the closest match using these clusters What is in the other text file? How do you define "closest match"? -- Steven From steve at pearwood.info Thu Apr 14 01:18:18 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 14 Apr 2011 09:18:18 +1000 Subject: [Tutor] Need help with the property function In-Reply-To: <4DA608A6.4040001@comcast.net> References: <4DA608A6.4040001@comcast.net> Message-ID: <4DA62F3A.20109@pearwood.info> Jim Byrnes wrote: > I'm trying to teach myself OOP in python (again). The following code > from Dawson's book runs fine, unaltered [1]. What's Dawson's book? > class Critter(object): > """ A virtual pet """ > def __init__(self, name): > print "A new critter is born" > self.name = name > > def get_name(self): > return self.__name > > def set_name(self, new_name): > if new_name == "": > print "A critters name cant be the empty string" > else: > self.__name = new_name > print "Name change successful" > > > name = property(get_name, set_name) #[1] This defines a read/write property. You can read it, and write to it. > # name = property(get_name) #[2] This, uncommented out, defines a read-only property. You can't write to it. > #different_name = property(get_name) #[3] Uncommented out, this defines a read-only property, but you don't get any errors because nowhere in your code do you try to write to it. > def talk(self): > print "Hi. I'm", self.name > > If I change [1] to [2] I get: > > Traceback (most recent call last): > File "propertycritter.py", line 26, in > crit = Critter("Poochie") > File "propertycritter.py", line 7, in __init__ > self.name = name > AttributeError: can't set attribute That's because you're trying to write to a read-only property inside the __init__ method with the line "self.name = name". > If I change [1] to [3] the program runs with no errors. Until you do this: crit = Critter("Poochie") crit.different_name = "Itchy" and then you will see the same error. The property function takes at least one, and at most four, arguments: name = property(getter, setter, deleter, docstring) "getter" must be a method that tells the class what to do when the caller *reads* the attribute with "instance.name". If present, "setter" must be a method that tells the class what to do when the caller *writes* the attribute with "instance.name = value". If there is no setter, you can't write to the attribute. If present, "deleter" must be a method that tells the class what to do when the caller *deletes* the attribute with "del instance.name". If there's no deleter, you can't delete the attribute. And finally, "docstring", if present, needs to be a text string which is used, well, it's never actually used anywhere, but you can find it if you look for it. It's just a message to anyone reading it. docstring is short for "documentation string". -- Steven From alan.gauld at btinternet.com Thu Apr 14 01:51:38 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 14 Apr 2011 00:51:38 +0100 Subject: [Tutor] python clusters References: <330972.11210.qm@web65410.mail.ac4.yahoo.com> Message-ID: "nookasree ponamala" wrote > I've 30 variables in a text file I've no idea what a variable in a text file looks like or means. variables only make sense inside a program context, in a file the only thing that exists is data. You may have 30 values? > and I want to read this text file and create 10 clusters > based on 18 variables. What is a cluster? I know the general concept but how does it relate to programming? > I want to read an other text file and find the closest > match using these clusters Define a class to represent your clusters - whatever they are. Write a method of the class to take a value and return a comparison score, based on whatever arbnitrary definition of closeness you want to use. Call that method to compare your value and the cluster and keep track of the minimum (on the asumption that the value represents "distance" from the cluster...) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From davea at ieee.org Thu Apr 14 03:57:53 2011 From: davea at ieee.org (Dave Angel) Date: Wed, 13 Apr 2011 21:57:53 -0400 Subject: [Tutor] Need help with the property function In-Reply-To: <4DA608A6.4040001@comcast.net> References: <4DA608A6.4040001@comcast.net> Message-ID: <4DA654A1.9050208@ieee.org> On 01/-10/-28163 02:59 PM, Jim Byrnes wrote: > I'm trying to teach myself OOP in python (again). The following code > from Dawson's book runs fine, unaltered [1]. > > class Critter(object): > """ A virtual pet """ > def __init__(self, name): > print "A new critter is born" > self.name = name > > def get_name(self): > return self.__name > > def set_name(self, new_name): > if new_name == "": > print "A critters name cant be the empty string" > else: > self.__name = new_name > print "Name change successful" > > > name = property(get_name, set_name) #[1] > # name = property(get_name) #[2] > #different_name = property(get_name) #[3] > > def talk(self): > print "Hi. I'm", self.name > > If I change [1] to [2] I get: > > Traceback (most recent call last): > File "propertycritter.py", line 26, in > crit = Critter("Poochie") > File "propertycritter.py", line 7, in __init__ > self.name = name > AttributeError: can't set attribute > > If I change [1] to [3] the program runs with no errors. > > Could someone please explain why I am seeing these results. > > Thanks, Jim > In case#2 you're making name a read-only property. So why on earth would you expect to be able to modify that property? DaveA From luc.kesters at hotmail.com Thu Apr 14 12:32:47 2011 From: luc.kesters at hotmail.com (Luc Kesters) Date: Thu, 14 Apr 2011 12:32:47 +0200 Subject: [Tutor] python clusters Message-ID: When you say "text file" and variables, you mean you have a file with n records and m fields? Isn't the following what you are searching for? http://docs.scipy.org/doc/scipy/reference/cluster.html -------------- next part -------------- An HTML attachment was scrubbed... URL: From emafrs at gmail.com Thu Apr 14 15:42:28 2011 From: emafrs at gmail.com (ema francis) Date: Thu, 14 Apr 2011 19:12:28 +0530 Subject: [Tutor] how to develop a python exe file in windows using python3.1 Message-ID: I am using python3.1 in windows environment.How can I create a python executable file? I tried with py2exe package but it is not compatible with python3.1.Is there any other way... pls help me... -------------- next part -------------- An HTML attachment was scrubbed... URL: From eire1130 at gmail.com Thu Apr 14 16:00:38 2011 From: eire1130 at gmail.com (James Reynolds) Date: Thu, 14 Apr 2011 10:00:38 -0400 Subject: [Tutor] how to develop a python exe file in windows using python3.1 In-Reply-To: References: Message-ID: We literally just answered this question a couple days ago, but if you need to make an executable in 3.1, CX freeze i believe should work. On Thu, Apr 14, 2011 at 9:42 AM, ema francis wrote: > I am using python3.1 in windows environment.How can I create a python > executable file? > I tried with py2exe package but it is not compatible with python3.1.Isthere any other way... > pls help me... > > _______________________________________________ > 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 jf_byrnes at comcast.net Thu Apr 14 16:09:36 2011 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Thu, 14 Apr 2011 09:09:36 -0500 Subject: [Tutor] Need help with the property function In-Reply-To: <4DA62F3A.20109@pearwood.info> References: <4DA608A6.4040001@comcast.net> <4DA62F3A.20109@pearwood.info> Message-ID: <4DA70020.80303@comcast.net> Steven D'Aprano wrote: > Jim Byrnes wrote: >> I'm trying to teach myself OOP in python (again). The following code >> from Dawson's book runs fine, unaltered [1]. > > What's Dawson's book? > Python Programming for the absolute beginner, by Michael Dawson Thanks for the explanation. It was exactly with I was hoping for. The book and a couple of other resources I looked at didn't lay it out so completely. They all assumed I knew more than I did. Regards, Jim From jf_byrnes at comcast.net Thu Apr 14 16:12:33 2011 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Thu, 14 Apr 2011 09:12:33 -0500 Subject: [Tutor] Need help with the property function In-Reply-To: <4DA654A1.9050208@ieee.org> References: <4DA608A6.4040001@comcast.net> <4DA654A1.9050208@ieee.org> Message-ID: <4DA700D1.1070507@comcast.net> Dave Angel wrote: > On 01/-10/-28163 02:59 PM, Jim Byrnes wrote: >> I'm trying to teach myself OOP in python (again). The following code >> from Dawson's book runs fine, unaltered [1]. >> >> class Critter(object): >> """ A virtual pet """ >> def __init__(self, name): >> print "A new critter is born" >> self.name = name >> >> def get_name(self): >> return self.__name >> >> def set_name(self, new_name): >> if new_name == "": >> print "A critters name cant be the empty string" >> else: >> self.__name = new_name >> print "Name change successful" >> >> >> name = property(get_name, set_name) #[1] >> # name = property(get_name) #[2] >> #different_name = property(get_name) #[3] >> >> def talk(self): >> print "Hi. I'm", self.name >> >> If I change [1] to [2] I get: >> >> Traceback (most recent call last): >> File "propertycritter.py", line 26, in >> crit = Critter("Poochie") >> File "propertycritter.py", line 7, in __init__ >> self.name = name >> AttributeError: can't set attribute >> >> If I change [1] to [3] the program runs with no errors. >> >> Could someone please explain why I am seeing these results. >> >> Thanks, Jim >> > > In case#2 you're making name a read-only property. So why on earth would > you expect to be able to modify that property? > > DaveA > > Because I was confused and didn't fully understand the process. I was experimenting and trying understand it to use it something else I was writing. Regards, Jim From james at jamesthornton.com Thu Apr 14 17:11:26 2011 From: james at jamesthornton.com (James Thornton) Date: Thu, 14 Apr 2011 10:11:26 -0500 Subject: [Tutor] super() with Multiple Inheritance Message-ID: Why does user.params() not return all the params up the inheritance chain? -- It's not including the params defined in Person() -- notice Vertex() does not have a params() method. class Element(object): def __init__(self,element_type): self.oid = None self.uuid = uuid.uuid4() self.key = None self.element_type = element_type def params(self): return dict(uuid=self.uuid, key=self.key) class Vertex(Element): def __init__(self): super(Vertex,self).__init__("vertex") class Person(Vertex): def __init__(self,name=None,uri=None,email=None): self.s = super(Person,self) self.s.__init__() self.name=name self.uri=uri self.email = email def params(self): params = dict(name=self.name,uri=self.uri,email=self.email) params.update(self.s.params()) return params class User(Person): def __init__(self, name=None, uri=None, email=None, first_name=None, last_name=None, facebook_id=None, facebook_link=None, facebook_username=None, gender=None, locale=None): self.s = super(User,self) self.s.__init__(name,uri,email) self.first_name = first_name self.last_name = last_name self.facebook_id = facebook_id self.facebook_link = facebook_link self.facebook_username = facebook_username self.gender = gender self.locale = locale def params(self): params = dict(first_name=self.first_name, last_name=self.last_name, facebook_id=self.facebook_id, facebook_link=self.facebook_link, facebook_username=self.facebook_username, gender=self.gender, locale=self.locale) print self.s.params() params.update(self.s.params()) return params From nookasree at yahoo.com Thu Apr 14 18:58:57 2011 From: nookasree at yahoo.com (nookasree ponamala) Date: Thu, 14 Apr 2011 09:58:57 -0700 (PDT) Subject: [Tutor] python clusters In-Reply-To: Message-ID: <619713.40833.qm@web65410.mail.ac4.yahoo.com> Thank you very much. This is exactly what I'm looking for. Do I have to install numpy and Scipy? It throws an error No module named numpy. ? I'm completely new to Python programming, trying to convert SAS code to python. I am able to do some simple steps, but this one is the clustering program in SAS enterprise miner and I don't have any idea of how to start with inb Python, that's the reason I did not post any code. I just used SAS language like variables. ? Thanks, Sree. --- On Thu, 4/14/11, Luc Kesters wrote: From: Luc Kesters Subject: Re: [Tutor] python clusters To: tutor at python.org Date: Thursday, April 14, 2011, 4:02 PM When you say "text file" and variables, you mean you have a file with n records and m fields? Isn't the following?what you are?searching for? ? http://docs.scipy.org/doc/scipy/reference/cluster.html -----Inline Attachment Follows----- _______________________________________________ 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 alan.gauld at btinternet.com Thu Apr 14 19:20:52 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 14 Apr 2011 18:20:52 +0100 Subject: [Tutor] python clusters References: <619713.40833.qm@web65410.mail.ac4.yahoo.com> Message-ID: "nookasree ponamala" wrote > ...trying to convert SAS code to python. .... this one > is the clustering program in SAS enterprise miner OK, I tried Google and got a 3Meg SAS PDF file that didn't help much. :-( I'm curious. Could someone post the elevator pitch on SAS Clustering? What on earth is it? Alan G. From alan.gauld at btinternet.com Thu Apr 14 19:25:45 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 14 Apr 2011 18:25:45 +0100 Subject: [Tutor] super() with Multiple Inheritance References: Message-ID: "James Thornton" wrote > Why does user.params() not return all the params up the inheritance > chain? -- It's not including the params defined in Person() -- > notice > Vertex() does not have a params() method. > class Element(object): > def params(self): > return dict(uuid=self.uuid, key=self.key) > > class Vertex(Element): > > class Person(Vertex): > def params(self): > params = dict(name=self.name,uri=self.uri,email=self.email) > params.update(self.s.params()) > return params > > class User(Person): > def params(self): > params = dict(first_name=self.first_name, > locale=self.locale) > print self.s.params() > params.update(self.s.params()) > return params Where does User.params call Person.params? Or for that matter Person.params call its super class? It doesn't happen automatically(thank goodness) you have to do it explicitly. From james at jamesthornton.com Thu Apr 14 19:42:33 2011 From: james at jamesthornton.com (James Thornton) Date: Thu, 14 Apr 2011 12:42:33 -0500 Subject: [Tutor] super() with Multiple Inheritance In-Reply-To: References: Message-ID: I found this issue -- I was setting setting self.s to the return value of super() and trying to use self.s in params(): self.s = super(User,self) self.s.__init__(name,uri,email) def params(self): params = dict(name=self.name) params.update(self.s.params()) ...but this won't work. You have to use super each time you want to make a call to a parent's function. It returns an object with an internal queue. If you use this object twice, you will only call the method of the top class (in this case, Element). super does not return an object from the parent class. It is a mechanism from managing multiple inheritance On Thu, Apr 14, 2011 at 12:25 PM, Alan Gauld wrote: > > "James Thornton" wrote > >> Why does user.params() not return all the params up the inheritance >> chain? -- It's not including the params defined in Person() -- ?notice >> Vertex() does not have a params() method. > >> class Element(object): >> ? def params(self): >> ? ? ? return dict(uuid=self.uuid, key=self.key) >> >> class Vertex(Element): >> >> class Person(Vertex): >> ? def params(self): >> ? ? ? params = dict(name=self.name,uri=self.uri,email=self.email) >> ? ? ? params.update(self.s.params()) >> ? ? ? return params >> >> class User(Person): >> ? def params(self): >> ? ? ? params = dict(first_name=self.first_name, >> ? ? ? ? ? ? ? ? ? ? locale=self.locale) >> ? ? ? print self.s.params() >> ? ? ? params.update(self.s.params()) >> ? ? ? return params > > Where does User.params call Person.params? > Or for that matter Person.params call its super class? > It doesn't happen automatically(thank goodness) you > have to do it explicitly. > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Latest Blog: http://jamesthornton.com/blog/how-to-get-to-genius From nookasree at yahoo.com Thu Apr 14 19:45:22 2011 From: nookasree at yahoo.com (nookasree ponamala) Date: Thu, 14 Apr 2011 10:45:22 -0700 (PDT) Subject: [Tutor] python clusters In-Reply-To: Message-ID: <394071.85296.qm@web65411.mail.ac4.yahoo.com> Here is the link which explains Clustering in SAS clearly. Copy and paste it in browser. http://www.hstathome.com/tjziyuan/SAS%20Data%20Mining%20Using%20Sas%20Enterprise%20Miner%20-%20A%20Case%20Study%20Appro.pdf Sree. --- On Thu, 4/14/11, Alan Gauld wrote: > From: Alan Gauld > Subject: Re: [Tutor] python clusters > To: tutor at python.org > Date: Thursday, April 14, 2011, 10:50 PM > > "nookasree ponamala" > wrote > > > ...trying to convert SAS code to python. .... this > one > > is the clustering program in SAS enterprise miner > > OK, I tried Google and got a 3Meg SAS PDF file that didn't > help much. :-( > > I'm curious. Could someone post the elevator pitch on SAS > Clustering? > What on earth is it? > > Alan G. > > > > > > _______________________________________________ > Tutor maillist? -? Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From wallenpb at gmail.com Thu Apr 14 22:25:55 2011 From: wallenpb at gmail.com (Bill Allen) Date: Thu, 14 Apr 2011 15:25:55 -0500 Subject: [Tutor] Python on TV In-Reply-To: <4DA36CEB.7090507@gmail.com> References: <4DA36CEB.7090507@gmail.com> Message-ID: Same here. I did not realize I was living in an internet censored country here in Texas! On Mon, Apr 11, 2011 at 16:04, bob gailer wrote: > On 4/11/2011 4:20 PM, Alan Gauld wrote: > >> I've just watched the Channel 5 programme "The Gadget Show" >> where the presenters set a new Guinness world record for operating >> the heaviest machine(*) using mind power. The software behind >> this feat - was written in Python of course! :-) >> >> (*)The machine in question was a 50 ton industrial crane... used >> to move a car from one end of a warehouse to the other. >> >> The show should be here - Pause at 1 minute 20 for the >> Python screnshot: >> >> >> http://fwd.channel5.com/gadget-show/videos/challenge/surprise-special-part-4 >> > > I am told "the video ... cannot be viewed from your currrent country ..." > > Sigh. > > > -- > 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 wallenpb at gmail.com Thu Apr 14 22:33:21 2011 From: wallenpb at gmail.com (Bill Allen) Date: Thu, 14 Apr 2011 15:33:21 -0500 Subject: [Tutor] how to develop a python exe file in windows using python3.1 In-Reply-To: References: Message-ID: On Thu, Apr 14, 2011 at 08:42, ema francis wrote: > I am using python3.1 in windows environment.How can I create a python > executable file? > I tried with py2exe package but it is not compatible with python3.1.Isthere any other way... > pls help me... > > cxfreeze works quite well for producing stand-alone Python apps. The only issue I have had is the occasional file or files from a third party module that do not get automatically brought over into the distribution target folder. However, in all those cases the error messages when the program was run gave me enough information to know what files I needed to go copy from my Python folders over into the distribution folder so it could find them. I use cxfreeze regularly for situations that are best served with a stand-alone Python program. However, I do recommend carefully evaluating if you need stand-alone or if installing the interpreter is more appropriate. I have found that not every program is best served by being converted to stand-alone. http://cx-freeze.sourceforge.net/ Good Luck, Bill Allen -------------- next part -------------- An HTML attachment was scrubbed... URL: From rabidpoobear at gmail.com Thu Apr 14 22:33:34 2011 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 14 Apr 2011 15:33:34 -0500 Subject: [Tutor] Python on TV In-Reply-To: References: <4DA36CEB.7090507@gmail.com> Message-ID: I don't see how a content provider preventing you from accessing content internationally that they probably don't have international distribution rights to as censorship. It's not like your ISP is blocking your access. ----------------------------- Sent from a mobile device. Apologies for brevity and top-posting. ----------------------------- On Apr 14, 2011, at 3:25 PM, Bill Allen wrote: > Same here. I did not realize I was living in an internet censored country here in Texas! > > > > On Mon, Apr 11, 2011 at 16:04, bob gailer wrote: > On 4/11/2011 4:20 PM, Alan Gauld wrote: > I've just watched the Channel 5 programme "The Gadget Show" > where the presenters set a new Guinness world record for operating > the heaviest machine(*) using mind power. The software behind > this feat - was written in Python of course! :-) > > (*)The machine in question was a 50 ton industrial crane... used > to move a car from one end of a warehouse to the other. > > The show should be here - Pause at 1 minute 20 for the > Python screnshot: > > http://fwd.channel5.com/gadget-show/videos/challenge/surprise-special-part-4 > > I am told "the video ... cannot be viewed from your currrent country ..." > > Sigh. > > > -- > 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 > > _______________________________________________ > 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 Thu Apr 14 22:37:31 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 14 Apr 2011 16:37:31 -0400 Subject: [Tutor] Python on TV In-Reply-To: References: <4DA36CEB.7090507@gmail.com> Message-ID: On Thu, Apr 14, 2011 at 4:25 PM, Bill Allen wrote: > Same here. I did not realize I was living in an internet censored country > here in Texas! > > > > > On Mon, Apr 11, 2011 at 16:04, bob gailer wrote: > >> On 4/11/2011 4:20 PM, Alan Gauld wrote: >> >>> I've just watched the Channel 5 programme "The Gadget Show" >>> where the presenters set a new Guinness world record for operating >>> the heaviest machine(*) using mind power. The software behind >>> this feat - was written in Python of course! :-) >>> >>> (*)The machine in question was a 50 ton industrial crane... used >>> to move a car from one end of a warehouse to the other. >>> >>> The show should be here - Pause at 1 minute 20 for the >>> Python screnshot: >>> >>> >>> http://fwd.channel5.com/gadget-show/videos/challenge/surprise-special-part-4 >>> >> >> I am told "the video ... cannot be viewed from your currrent country ..." >> >> Sigh. >> >> >> -- >> Bob Gailer >> 919-636-4239 >> Chapel Hill NC >> >> I'm guessing that this is caused by copyright restrictions > >> _______________________________________________ >> 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 -------------- next part -------------- An HTML attachment was scrubbed... URL: From wallenpb at gmail.com Thu Apr 14 22:39:27 2011 From: wallenpb at gmail.com (Bill Allen) Date: Thu, 14 Apr 2011 15:39:27 -0500 Subject: [Tutor] Python on TV In-Reply-To: References: <4DA36CEB.7090507@gmail.com> Message-ID: On Thu, Apr 14, 2011 at 15:33, Luke Paireepinart wrote: > I don't see how a content provider preventing you from accessing content > internationally that they probably don't have international distribution > rights to as censorship. It's not like your ISP is blocking your access. > > Seriously, I was only joking! :-) --Bill -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Apr 14 23:33:37 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 14 Apr 2011 22:33:37 +0100 Subject: [Tutor] super() with Multiple Inheritance References: Message-ID: "James Thornton" wrote > I found this issue -- I was setting setting self.s to the return > value > of super() and trying to use self.s in params(): > ...but this won't work. No, because super returns whatever the superclass method returns. Which in init() is usually None. > You have to use super each time you want to make a > call to a parent's function. It returns an object with > an internal queue. It should return the result of the superclasses method, whatever that is. > mechanism from managing multiple inheritance Or even single inheritance if you want to... Alan G. From steve at pearwood.info Fri Apr 15 02:48:13 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 15 Apr 2011 10:48:13 +1000 Subject: [Tutor] super() with Multiple Inheritance In-Reply-To: References: Message-ID: <4DA795CD.3090909@pearwood.info> James, Your subject line is misleading: you ask about *multiple* inheritance, but the code you use is *single* inheritance: object -> Element -> Vertex -> Person -> User Multiple inheritance occurs when you have a class that inherits from two or more parent classes: class Spam(Ham, ManufacturedMeatProduct): [...] This is often problematic, so much so that many object oriented languages prohibit it, or limit it to a subset of MI where the second parent shares no methods with the first ("mixins"). Python allows almost unrestricted MI, but I strongly recommend that you avoid it unless absolutely necessary. Also, it's quite unusual in Python to build long inheritance chains like this. We're a pragmatic people, we Python coders, and if a class only exists to satisfy some sense of theoretical object-hierarchy purity, more often than not we prefer the Zen of Python: >>> import this [...] Practicality beats purity. I'd consider reducing the hierarchy to: object -> Element -> User unless you have real need for the other classes. James Thornton wrote: > Why does user.params() not return all the params up the inheritance > chain? -- It's not including the params defined in Person() -- notice > Vertex() does not have a params() method. You do something fairly unusual here: > class Person(Vertex): > def __init__(self,name=None,uri=None,email=None): > self.s = super(Person,self) > self.s.__init__() I've never seen anyone *store* a super object before! Normally people generate it as needed: super(Person, self).__init__() This leads to your mistake: > class User(Person): > def __init__(self, [...]) > self.s = super(User,self) > self.s.__init__(name,uri,email) So you store the User's super object as attribute "s", and then call the superclasses' __init__ method... but Person's __init__ in turn *also* stores its super object as "s", thus *over-writing* the "s" you just saved. Then, when you call params: > def params(self): > params = dict(...) > print self.s.params() > params.update(self.s.params()) > return params self.s is the super object for Person, not User, and so it skips Person and goes directly to Vertex, Element and object. TL;DR: don't save super objects for later use, they're not that expensive to make. Just regenerate them as needed. -- Steven From steve at pearwood.info Fri Apr 15 03:06:37 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 15 Apr 2011 11:06:37 +1000 Subject: [Tutor] super() with Multiple Inheritance In-Reply-To: References: Message-ID: <4DA79A1D.3010603@pearwood.info> Alan Gauld wrote: > > "James Thornton" wrote > >> I found this issue -- I was setting setting self.s to the return value >> of super() and trying to use self.s in params(): > >> ...but this won't work. > > No, because super returns whatever the superclass > method returns. Which in init() is usually None. No, super returns a proxy object that encapsulates knowledge of the superclasses of the argument (usually "self", but not necessarily). >>> class A(object): ... attr = "Nobody expects the SPANISH INQUISITION!" ... >>> class B(A): ... attr = "something else" ... >>> b = B() >>> s = super(B, b) >>> s , > What you do with that proxy object is then lookup attributes (usually methods, but data attributes are fine too): >>> s.attr 'Nobody expects the SPANISH INQUISITION!' If you look up a method, and *call* that method, then of course the complete chain of super::method lookup::method call will return whatever the method itself returns. But that's different from saying that super itself returns (say) None. -- Steven From alan.gauld at btinternet.com Fri Apr 15 03:35:03 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 15 Apr 2011 02:35:03 +0100 Subject: [Tutor] super() with Multiple Inheritance References: <4DA79A1D.3010603@pearwood.info> Message-ID: "Steven D'Aprano" wrote >> No, because super returns whatever the superclass >> method returns. Which in init() is usually None. > > No, super returns a proxy object that encapsulates knowledge of the > superclasses of the argument (usually "self", but not necessarily). > >>> b = B() > >>> s = super(B, b) > >>> s > , > I stand corrected. And I'm sure Guido knows why he did it that way, but it adds to the complexity in the way Python handles this stuff. I know SmallTalk has it simpler because it only has to deal with single inheritance but the Python super() implementation really, really feels flaky to me, its one of the few Python features I don't enjoy using. > If you look up a method, and *call* that method, then of course the > complete chain of super::method lookup::method call will return > whatever the method itself returns. But that's different from saying > that super itself returns (say) None. True, although it feels like that to the programmer. But under the hood its different and potentially acts different. Thanks for pointing that out - I'm gonna have to give it some (more) thought. I keep trying to embrace super() but every time I try I just find more issues with it. yek! Alan G. From steve at pearwood.info Fri Apr 15 06:14:22 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 15 Apr 2011 14:14:22 +1000 Subject: [Tutor] Python on TV In-Reply-To: References: <4DA36CEB.7090507@gmail.com> Message-ID: <4DA7C61E.10205@pearwood.info> Luke Paireepinart wrote: > I don't see how a content provider preventing you from accessing content internationally that they probably don't have international distribution rights to as censorship. It's not like your ISP is blocking your access. There is nothing about censorship that means it can only be performed by government. Your parents probably censored what you saw and read when you were a child. Fox News censors; private companies and entities of all sizes and forms censor, with varying degrees of success and different motives. As Bill Cole once said: "Here in the US, we are so schizoid and deeply opposed to government censorship that we insist on having unaccountable private parties to do it instead." Not all censorship is bad, nor is it always from a desire to hide information or keep people ignorant. Often it is from a desire to make money by restricting information. Sometimes the entity doing the censorship doesn't gain from it at all, but does so on behalf of another party. Sometimes the party doing the censorship doesn't even realise that they are censoring, because they themselves are equally victims of censorship. It's all still censorship. As for international distribution rights, that concept no longer makes sense in the 21st century. It's well past time that they have their business models catch up to reality. -- Steven From ladymcse2000 at gmail.com Fri Apr 15 08:33:52 2011 From: ladymcse2000 at gmail.com (Becky Mcquilling) Date: Thu, 14 Apr 2011 23:33:52 -0700 Subject: [Tutor] Writing to the file system and verify the files written out. Message-ID: Hi, all: I'm doing a tutorial online and I have run across an assignment to write a unit test. One of the tests is working fine, the other one is failing. The goal of this particular one is: 1) Create a directory 2) Create files in the directory that are listed in the text files 3) Create a set with the filenames of all the files that were created 3) List the files files, using os.listdir 4) Create a set with the above list 5) Compare the two sets to ensure that no files were created that weren't in the text files The setUp() method and the tearDown() method work fine, as well as test_2(), but test_1, is failing the unittest, with: FAIL: test_1 (setupDemo.FileTest) Verify creation of files is possible ---------------------------------------------------------------------- Traceback (most recent call last): File "V:\workspace\Python2_Homework02\src\setupDemo.py", line 33, in test_1 self.assertEqual(dir_list, text_files, "The filelist is not equal") AssertionError: The filelist is not equal I'm not sure why the lists would not be equal Here is the code: """ import unittest import tempfile import shutil import glob import os class FileTest(unittest.TestCase): def setUp(self): self.origdir = os.getcwd() self.dirname = tempfile.mkdtemp("testdir") os.chdir(self.dirname) def test_1(self): "Verify creation of files is possible" text_files = set() for filename in ("this.txt", "that.txt", "the_other.txt"): f = open(filename, "w") f.write("Some text\n") text_files.add(filename) f.close() self.assertTrue(f.closed) dir_list = os.listdir(self.dirname) dir_set = set() for file in dir_list: dir_set.add(file) self.assertEqual(dir_list, text_files, "The filelist is not equal") def test_2(self): "Verify that the current directory is empty" self.assertEqual(glob.glob("*"), [], "Directory not empty") def tearDown(self): os.chdir(self.origdir) shutil.rmtree(self.dirname) if __name__ == "__main__": unittest.main() Any help greatly appreciated! Becky -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Fri Apr 15 09:20:40 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 15 Apr 2011 17:20:40 +1000 Subject: [Tutor] Writing to the file system and verify the files written out. In-Reply-To: References: Message-ID: <4DA7F1C8.8030805@pearwood.info> Becky Mcquilling wrote: > dir_list = os.listdir(self.dirname) > dir_set = set() > for file in dir_list: > dir_set.add(file) > self.assertEqual(dir_list, text_files, "The filelist is not equal") You're comparing a list of file names to a set of file names. They will never match, even if they have the same content. Try this instead: dir_set = set(os.listdir(self.dirname)) self.assertEqual(dir_set, text_files, "The filelist is not equal") -- Steven From i.eat.brainzzz at gmail.com Fri Apr 15 01:10:31 2011 From: i.eat.brainzzz at gmail.com (Casey Key) Date: Thu, 14 Apr 2011 16:10:31 -0700 Subject: [Tutor] Fwd: Python skipping if statement (Really simple code) In-Reply-To: References: Message-ID: ---------- Forwarded message ---------- From: Casey Key Date: Thu, Apr 14, 2011 at 4:02 PM Subject: Python skipping if statement (Really simple code) To: tutor at python.com Hey im a newbie to python, but i made this test code. and it is just skipping over the if statement, which is essential to the program. import random print("Renees a hater, and you know what happens to hater? They hate!") print("They purpose of this program is to express your feelings toward Renee.") print("Note:I am not pointing of a particular Renee it is just a random name.") caution = input("After reading the note do you want to proceed? ") if caution == "yes" : print("Lets get started.") hate = random.randint(1, 5) print("Renees hate level is at ", hate) proceed = input(int("Do you want to see Renees hate in form of a picture? ")) if proceed == "yes": print("Chose a number between 1 and 3. ") choice = input("So whats your choice? ") if choice == "1": print( """ , (`. : \ __..----..__ `.`.| |: _,-':::''' ' `:`-._ `.:\|| _,':::::' `::::`-. \\`| _,':::::::' `:. `':::`. ;` `-'' `::::::. `::\ ,-' .::' `:::::. `::.. `:\ ,' /_) -. `::. `:. | ,'.: ` `:. `:. .::. \ __,-' ___,..-''-. `:. `. /::::. | |):'_,--' `. `::.. |::::::. ::\ `-' |`--.:_::::|_____\::::::::.__ ::| | _/|::::| \::::::|::/\ :| /:./ |:::/ \__:::):/ \ :\ ,'::' /:::| ,'::::/_/ `. ``-.__ jrei '''' (//|/\ ,';':,-' `-.__ `'--..__ """) elif choice == "2": print( """ _,\,\,\|\|\|\|\|\|\|\/-\___.._ __,-' () .\ / __/---\___ __ ---/ | / \ \___________/\\ \___/ | | \ \ \\ | | / | \\__/_ | | | \/_ /\ || \--\ || \\_______ \-------\\____ """) elif choice == "3": print( """ /\ ( ;`~v/~~~ ;._ ,/'"/^) ' < o\ '".~'\\\--, ,/",/W u '`. ~ >,._.., )' ,/' w ,U^v ;//^)/')/^\;~)' ,/"'/ W` ^v W |; )/' ;'' | v' v`" W } \\ " .'\ v `v/^W,) '\)\.)\/) `\ ,/,)' ''')/^"-;' \ ? ". \ """) suprise = input("Are you ready for a suprise?") if suprise == "yes": print( """ MMM88&&&, ,MMM8&&&. `'MMM88&&&, MMMMM88&&&& 'MMM88&&&, MMMMM88&&&&&& 'MMM88&&&, MMMMM88&&&&&& 'MMM88&&& MMMMM88&&&&&& 'MMM88&&& MMMMM88&&&& MMM88&&& 'MMM8&&&' MMMM888&&&& 'MM88&&& MMMM88&&&&& MM88&&& MMMM88&&&&& MM88&&& ,MMM8&&&. MM88&&& MMMMM88&&&& ,MM88&&& MMMMM88&&&&&& MMM88&&&' MMMMM88&&&&&& MMM88&&&' MMMMM88&&&&&& MMM88&&&' MMMMM88&&&& MMM88&&&' 'MMM8&&&' MMM88&&&' MMM88&&&' . """) input("\n\nPress the enter key to exit.") -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Apr 15 09:50:04 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 15 Apr 2011 08:50:04 +0100 Subject: [Tutor] Python skipping if statement (Really simple code) References: Message-ID: "Casey Key" wrote > Hey im a newbie to python, but i made this test code. and it is just > skipping over the if statement, which is essential to the program. Which if statement, there are several? Are there any error messages? If so send them in their entirety. If not can you show us whatever output you do get. If you know which if statement is failing have you tried inserting a print statement to show what the test value is actually stored as? (For example the first if statement would require: print (caution) just before the if statement. ) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ > > import random > > print("Renees a hater, and you know what happens to hater? They > hate!") > print("They purpose of this program is to express your feelings > toward > Renee.") > print("Note:I am not pointing of a particular Renee it is just a > random > name.") > > caution = input("After reading the note do you want to proceed? ") > if caution == "yes" : > print("Lets get started.") > hate = random.randint(1, 5) > print("Renees hate level is at ", hate) > proceed = input(int("Do you want to see Renees hate in form of a > picture? ")) > if proceed == "yes": > print("Chose a number between 1 and 3. ") > choice = input("So whats your choice? ") > if choice == "1": > print( > """ > , > (`. : \ __..----..__ > `.`.| |: _,-':::''' ' `:`-._ > `.:\|| _,':::::' `::::`-. > \\`| _,':::::::' `:. `':::`. > ;` `-'' `::::::. `::\ > ,-' .::' `:::::. `::.. `:\ > ,' /_) -. `::. `:. | > ,'.: ` `:. `:. .::. \ > __,-' ___,..-''-. `:. `. /::::. | > |):'_,--' `. `::.. |::::::. ::\ > `-' |`--.:_::::|_____\::::::::.__ ::| > | _/|::::| \::::::|::/\ :| > /:./ |:::/ \__:::):/ \ :\ > ,'::' /:::| ,'::::/_/ `. ``-.__ > jrei '''' (//|/\ ,';':,-' `-.__ > `'--..__ > > """) > elif choice == "2": > print( > """ > > _,\,\,\|\|\|\|\|\|\|\/-\___.._ > __,-' () .\ > / __/---\___ __ ---/ > | / \ \___________/\\ \___/ > | | \ \ \\ > | | / | \\__/_ > | | | \/_ /\ > || \--\ > || > \\_______ > \-------\\____ > > """) > elif choice == "3": > print( > """ > /\ > ( ;`~v/~~~ ;._ > ,/'"/^) ' < o\ '".~'\\\--, > ,/",/W u '`. ~ >,._.., )' > ,/' w ,U^v ;//^)/')/^\;~)' > ,/"'/ W` ^v W |; )/' > ;'' | v' v`" W } \\ > " .'\ v `v/^W,) '\)\.)\/) > `\ ,/,)' ''')/^"-;' > \ ? > ". > \ > """) > suprise = input("Are you ready for a suprise?") > if suprise == "yes": > print( > """ > > MMM88&&&, > ,MMM8&&&. `'MMM88&&&, > MMMMM88&&&& 'MMM88&&&, > MMMMM88&&&&&& 'MMM88&&&, > MMMMM88&&&&&& 'MMM88&&& > MMMMM88&&&&&& 'MMM88&&& > MMMMM88&&&& MMM88&&& > 'MMM8&&&' MMMM888&&&& 'MM88&&& > MMMM88&&&&& MM88&&& > MMMM88&&&&& MM88&&& > ,MMM8&&&. MM88&&& > MMMMM88&&&& ,MM88&&& > MMMMM88&&&&&& MMM88&&&' > MMMMM88&&&&&& MMM88&&&' > MMMMM88&&&&&& MMM88&&&' > MMMMM88&&&& MMM88&&&' > 'MMM8&&&' MMM88&&&' > MMM88&&&' > > . > """) > input("\n\nPress the enter key to exit.") > -------------------------------------------------------------------------------- > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From __peter__ at web.de Fri Apr 15 09:55:49 2011 From: __peter__ at web.de (Peter Otten) Date: Fri, 15 Apr 2011 09:55:49 +0200 Subject: [Tutor] Fwd: Python skipping if statement (Really simple code) References: Message-ID: Casey Key wrote: > ---------- Forwarded message ---------- > From: Casey Key > Date: Thu, Apr 14, 2011 at 4:02 PM > Subject: Python skipping if statement (Really simple code) > To: tutor at python.com > > > Hey im a newbie to python, but i made this test code. and it is just > skipping over the if statement, which is essential to the program. When you run your code, enter yes to the first question Python stops with a "traceback", a dump of the error that has occured: $ python3 ascii_art.py Renees a hater, and you know what happens to hater? They hate! They purpose of this program is to express your feelings toward Renee. Note:I am not pointing of a particular Renee it is just a random name. After reading the note do you want to proceed? yes Lets get started. Renees hate level is at 3 Traceback (most recent call last): File "ascii_art.py", line 12, in proceed = input(int("Do you want to see Renees hate in form of a picture? ")) ValueError: invalid literal for int() with base 10: 'Do you want to see Renees hate in form of a picture? ' Read the last line carefully, then go upwards where the traceback tells you in what line the error occured and see if you can fix the problem yourself. Come back here if you can't. From bteeuwen at gmail.com Fri Apr 15 10:04:26 2011 From: bteeuwen at gmail.com (Ben Teeuwen) Date: Fri, 15 Apr 2011 10:04:26 +0200 Subject: [Tutor] ImportError: No module named wdmmgext.load References: <25923943-B032-4FB6-A64A-7870E7FD49E7@gmail.com> Message-ID: <37AC980D-046B-4637-881A-6754AB915197@gmail.com> Hi, I'm trying to install the code from http://wheredoesmymoneygo.org/getting-started/ on my local machine. I've got a mac os 10.6.7, python 2.7.1, pip, and the most recent postgres installation. I'm now testing imported data and I get 21 errors (see attached). The majority sounds like: from wdmmgext.load import uganda ImportError: No module named wdmmgext.load I've searched the files that use this module. Attached is an example file. I see 2 more errors; 1) that the file 'ukgov-finances-cra/cra_2009_db.csv' does not exist. 2) SolrException: HTTP code=404, reason=Not Found Maybe both are due to the wdmmgext.load error, so I'll ignore this for now and first try to find answer to my first question. Thanks in advance for the help! Ben -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: example.txt URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: error.txt URL: -------------- next part -------------- From s.charonis at gmail.com Fri Apr 15 14:41:36 2011 From: s.charonis at gmail.com (Spyros Charonis) Date: Fri, 15 Apr 2011 13:41:36 +0100 Subject: [Tutor] Script for Parsing string sequences from a file Message-ID: Hello, I'm doing a biomedical degree and am taking a course on bioinformatics. We were given a raw version of a public database in a file (the file is in simple ASCII) and need to extract only certain lines containing important information. I've made a script that does not work and I am having trouble understanding why. when I run it on the python shell, it prompts for a protein name but then reports that there is no such entry. The first while loop nested inside a for loop is intended to pick up all lines beginning with "gc;", chop off the "gc;" part and keep only the text after that (which is a protein name). Then it scans the file and collects all lines, chops the "gc;" and stores in them in a tuple. This tuple is not built correctly, because as I posted when the program is run it reports that it cannot find my query in the tuple I created and it is certainly in the database. Can you detect what the mistake is? Thank you in advance! Spyros -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: myParser.py Type: application/octet-stream Size: 1232 bytes Desc: not available URL: From joel.goldstick at gmail.com Fri Apr 15 14:54:19 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 15 Apr 2011 08:54:19 -0400 Subject: [Tutor] Script for Parsing string sequences from a file In-Reply-To: References: Message-ID: On Fri, Apr 15, 2011 at 8:41 AM, Spyros Charonis wrote: > Hello, > > I'm doing a biomedical degree and am taking a course on bioinformatics. We > were given a raw version of a public database in a file (the file is in > simple ASCII) and need to extract only certain lines containing important > information. I've made a script that does not work and I am having trouble > understanding why. > > when I run it on the python shell, it prompts for a protein name but then > reports that there is no such entry. The first while loop nested inside a > for loop is intended to pick up all lines beginning with "gc;", chop off the > "gc;" part and keep only the text after that (which is a protein name). > Then it scans the file and collects all lines, chops the "gc;" and stores > in them in a tuple. This tuple is not built correctly, because as I posted > when the program is run it reports that it cannot find my query in the tuple > I created and it is certainly in the database. Can you detect what the > mistake is? Thank you in advance! > > Spyros > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > import os, string printsdb = open('/users/spyros/folder1/python/PRINTSmotifs/prints41_1.kdat', 'r') lines = printsdb.readlines() # find PRINTS name entries you need to have a list to collect your strings: protnames = [] for line in lines: # this gets you each line #while line.startswith('gc;'): this is wrong if line.startswith('gc;'); # do this instead protnames.append(line.lstrip('gc;')) # this adds your stripped string to the protnames list if not protnames: print('error in creating tuple') # check if tuple is true or false #print(protnames) break query = input("search a protein: ") query = query.upper() if query in protnames: print("\nDisplaying Motifs") else: print("\nentry not in database") # Parse motifs def extract_motifs(query): motif_id = () motif = () while query in lines: ####for query, get motif_ids and motifs while line.startswith('ft;'): motif_id = line.lstrip('ft;') motif_ids = (motif_id) #print(motif_id) while line.startswith('fd;'): motif = line.lstrip('fd;') motifs = (motif) #print(motif) return motif_id, motif if __name__ == '__main__': final_motifs = extract_motifs('query') -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Fri Apr 15 14:57:50 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 15 Apr 2011 08:57:50 -0400 Subject: [Tutor] Script for Parsing string sequences from a file In-Reply-To: References: Message-ID: sorry, I hit send too soon on last message On Fri, Apr 15, 2011 at 8:54 AM, Joel Goldstick wrote: > > > On Fri, Apr 15, 2011 at 8:41 AM, Spyros Charonis wrote: > >> Hello, >> >> I'm doing a biomedical degree and am taking a course on bioinformatics. We >> were given a raw version of a public database in a file (the file is in >> simple ASCII) and need to extract only certain lines containing important >> information. I've made a script that does not work and I am having trouble >> understanding why. >> >> when I run it on the python shell, it prompts for a protein name but then >> reports that there is no such entry. The first while loop nested inside a >> for loop is intended to pick up all lines beginning with "gc;", chop off the >> "gc;" part and keep only the text after that (which is a protein name). >> Then it scans the file and collects all lines, chops the "gc;" and stores >> in them in a tuple. This tuple is not built correctly, because as I posted >> when the program is run it reports that it cannot find my query in the tuple >> I created and it is certainly in the database. Can you detect what the >> mistake is? Thank you in advance! >> >> Spyros >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > import os, string > > printsdb = > open('/users/spyros/folder1/python/PRINTSmotifs/prints41_1.kdat', 'r') > lines = printsdb.readlines() > > # find PRINTS name entries > you need to have a list to collect your strings: > protnames = [] > for line in lines: # this gets you each line > #while line.startswith('gc;'): this is wrong > if line.startswith('gc;'); # do this instead > protnames.append(line.lstrip('gc;')) # this adds your stripped > string to the protnames list > # try doing something like: print protnames # this should give you a list of all your lines that started with 'gc;' # this block I don't understand > if not protnames: > print('error in creating tuple') # check if tuple is true or > false > #print(protnames) > break > > Now, you have protnames with all of your protein names see if above helps. then you have below to figure out query = input("search a protein: ") > query = query.upper() > if query in protnames: > print("\nDisplaying Motifs") > else: > print("\nentry not in database") > > # Parse motifs > def extract_motifs(query): > motif_id = () > motif = () > while query in lines: ####for query, get motif_ids and motifs > while line.startswith('ft;'): > motif_id = line.lstrip('ft;') > motif_ids = (motif_id) > #print(motif_id) > while line.startswith('fd;'): > motif = line.lstrip('fd;') > motifs = (motif) > #print(motif) > return motif_id, motif > > if __name__ == '__main__': > final_motifs = extract_motifs('query') > > > > -- > Joel Goldstick > > -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From andres at chandia.net Fri Apr 15 18:21:43 2011 From: andres at chandia.net (=?iso-8859-1?Q?=22Andr=E9s_Chand=EDa=22?=) Date: Fri, 15 Apr 2011 18:21:43 +0200 Subject: [Tutor] Help to explain commenting In-Reply-To: <4DA0E5EF.9020104@googlemail.com> References: <4DA0E5EF.9020104@googlemail.com> Message-ID: <957d7e2abbfe95f19b83cef056261697.squirrel@mail.chandia.net> Hello everybody, I could finally complete succesfully the code I was working with. As I'm quite new to python, many of the things I have in my code are copied from different sources, and I do not undertand all of them, well, I have to deliver this code for a project, and in the best documented way that I could, I already commented all that I know, and I suppouse wrongly in some parts. So the request is, if you can take a look at the code, comment the parts that are not yet commented, correct the errors, and propouse some improvement in the parts you think diserves it. I attach the code in a tgz file, if the attached can not be seen then this link: http://www.chandia.net/compart/NMT-2.4-20110415.tar.gz Thanks in advance to all of you and to the people that already helped me. _______________________ ????????????andr?s chand?a P No imprima innecesariamente. ?Cuide el medio ambiente! -------------- next part -------------- A non-text attachment was scrubbed... Name: NMT-2.4-20110415.tar.gz Type: application/x-gzip Size: 4177 bytes Desc: not available URL: From alan.gauld at btinternet.com Fri Apr 15 21:35:14 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 15 Apr 2011 20:35:14 +0100 Subject: [Tutor] Python on TV References: <4DA36CEB.7090507@gmail.com> Message-ID: "bob gailer" wrote >> The show should be here - Pause at 1 minute 20 for the >> Python screnshot: >> >> http://fwd.channel5.com/gadget-show/videos/challenge/surprise-special-part-4 > > I am told "the video ... cannot be viewed from your currrent country > ..." I don't know if YouTube will be any more obliging but try this: http://www.youtube.com/watch?v=oDNZP1X30WE&list=SL Python can be seen at around 29 mins 45 secs... Enjoy (I hope) Alan G. From lea-parker at bigpond.com Fri Apr 15 23:52:22 2011 From: lea-parker at bigpond.com (Lea Parker) Date: Sat, 16 Apr 2011 07:52:22 +1000 Subject: [Tutor] Help - accumulator not working (Lea) Message-ID: <000001cbfbb7$666bd140$334373c0$@bigpond.com> Hello I am trying to create this program for a uni assignment. I cannot get it to add the expenses to the accumulator I have set. Would you mind having a look and letting me know if I have something in the wrong place or indented incorrectly. Perhaps I am missing something. There could be other things wrong but I need to fix this first and then I can focus on the next thing. I have difficulty trying to fix lots of things at once so if you could just comment on the problem and I will ask again if I can't work out the next problem I have. I like to have a go myself first. J My code is: """This program is to calculate if the user is over or under budget for the month""" def main(): # Create an accumulator total_expense = 0.0 # Ask user for the monthly budget budget = float(raw_input('Enter the amount of your budget for the month: $')) # Calculate a series of expenses expense = float(raw_input('Enter your first expense $')) # Accumlate expense total_expense = total_expense + expense # Continue processing as long as the user # does not enter 0 while expense != 0: #Get another expense expense = float(raw_input('Enter the next expense or 0 to finish $')) #Calculate surplus surplus = budget - total_expense #Display results print 'Your total expenses for the month $', total_expense print 'Your surplus amount after expenses $', surplus # Call the main function. main() Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Sat Apr 16 00:47:21 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 15 Apr 2011 18:47:21 -0400 Subject: [Tutor] Help - accumulator not working (Lea) In-Reply-To: <000001cbfbb7$666bd140$334373c0$@bigpond.com> References: <000001cbfbb7$666bd140$334373c0$@bigpond.com> Message-ID: On Fri, Apr 15, 2011 at 5:52 PM, Lea Parker wrote: > Hello > > > > I am trying to create this program for a uni assignment. I cannot get it to > add the expenses to the accumulator I have set. Would you mind having a look > and letting me know if I have something in the wrong place or indented > incorrectly. Perhaps I am missing something. > > > > There could be other things wrong but I need to fix this first and then I > can focus on the next thing. I have difficulty trying to fix lots of things > at once so if you could just comment on the problem and I will ask again if > I can?t work out the next problem I have. I like to have a go myself first. > J > > > > My code is: > > > > """This program is to calculate if the user is over or under budget > > for the month""" > > > > > > def main(): > > > > # Create an accumulator > > total_expense = 0.0 > > > > # Ask user for the monthly budget > > budget = float(raw_input('Enter the amount of your budget for the > month: $')) > > > above here is good > > > # Calculate a series of expenses > > expense = float(raw_input('Enter your first expense $')) > > > I would remove the input above and move it to your loop. > # Accumlate expense > > total_expense = total_expense + expense > > above you don't need this since you haven't added anything yet (see below) > > I set expense to 1 just to get the loop started. It could be anything but 0 > # Continue processing as long as the user > > # does not enter 0 > > while expense != 0: > > > > #Get another expense > > expense = float(raw_input('Enter the next expense or 0 to finish > $')) > > > > #Calculate surplus > > surplus = budget - total_expense > > > > #Display results > > print 'Your total expenses for the month $', total_expense > > print 'Your surplus amount after expenses $', surplus > > > > # Call the main function. > > main() > > > > Thank you. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > def main(): # Create an accumulator total_expense = 0.0 # Ask user for the monthly budget budget = float(raw_input('Enter the amount of your budget for the month: $')) expense = 1 total_expense = 0 while expense != 0: #Get another expense expense = float(raw_input('Enter the next expense or 0 to finish $')) #Calculate surplus total_expense = total_expense + expense surplus = budget - total_expense print budget, total_expense #Display results print 'Your total expenses for the month $', total_expense print 'Your surplus amount after expenses $', surplus main() Good luck with your course -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From jigenbakuda at yahoo.com Sat Apr 16 00:46:32 2011 From: jigenbakuda at yahoo.com (michael scott) Date: Fri, 15 Apr 2011 15:46:32 -0700 (PDT) Subject: [Tutor] Help - accumulator not working (Lea) In-Reply-To: <000001cbfbb7$666bd140$334373c0$@bigpond.com> References: <000001cbfbb7$666bd140$334373c0$@bigpond.com> Message-ID: <670739.27615.qm@web130203.mail.mud.yahoo.com> Hi Lea, how are you today? Well please keep in mind that nothing is "wrong" with your code, its doing exactly what you asked it to do. But I would call your attention to your while loop, you want to accumulate things, but may I ask exactly what are you accumulating in your loop? Also quite by accident I entered 00 as my budget and I got a negative surplus, lol. Perhaps you should implement something that ensures that a (stupid) user like myself does not enter a 0- or negative value for the budget. Just a thought... To help me attempt to understand the small programs I write, I pretend that I'm the computer and I literally compute the program as if I was the interpreter, I follow each line of my code to truly understand it. Perhaps with these gentle nudges you will solve your problem :) ---- What is it about you... that intrigues me so? ________________________________ From: Lea Parker To: tutor at python.org Sent: Fri, April 15, 2011 5:52:22 PM Subject: [Tutor] Help - accumulator not working (Lea) Hello I am trying to create this program for a uni assignment. I cannot get it to add the expenses to the accumulator I have set. Would you mind having a look and letting me know if I have something in the wrong place or indented incorrectly. Perhaps I am missing something. There could be other things wrong but I need to fix this first and then I can focus on the next thing. I have difficulty trying to fix lots of things at once so if you could just comment on the problem and I will ask again if I can?t work out the next problem I have. I like to have a go myself first. J My code is: """This program is to calculate if the user is over or under budget for the month""" def main(): # Create an accumulator total_expense = 0.0 # Ask user for the monthly budget budget = float(raw_input('Enter the amount of your budget for the month: $')) # Calculate a series of expenses expense = float(raw_input('Enter your first expense $')) # Accumlate expense total_expense = total_expense + expense # Continue processing as long as the user # does not enter 0 while expense != 0: #Get another expense expense = float(raw_input('Enter the next expense or 0 to finish $')) #Calculate surplus surplus = budget - total_expense #Display results print 'Your total expenses for the month $', total_expense print 'Your surplus amount after expenses $', surplus # Call the main function. main() Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Apr 16 01:27:22 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 16 Apr 2011 00:27:22 +0100 Subject: [Tutor] Help - accumulator not working (Lea) References: <000001cbfbb7$666bd140$334373c0$@bigpond.com> Message-ID: "Lea Parker" wrote > I am trying to create this program for a uni assignment. I cannot > get it to > add the expenses to the accumulator I have set. You have to write the code to add each value to the accumulator Your loop does not do that.... > """This program is to calculate if the user is over or under budget > > for the month""" > > > > Wow! Thats a lot of whitespace. It is good to separate code blocks into logical segments with whitespace, but too much of it just makes the code flow hard to see. In the old days of green screen terminals on mainframes they used to say that a function should all fit on a single screen - 24 lines. Nowadays we don't need to be quite so penny pinching, but the concept of seeing the whole flow in one place is a good one. I'll remove some excess space below... > def main(): > # Create an accumulator Oh, and if you can use a good variable name to describe the variable you don't need a comment either - It's just more distracting wasted space. Comments are to explain *why* (and occasionally, for the really obscure, how), but good names describe what. > total_expense = 0.0 > budget = float(raw_input('Enter the amount of your budget for the > month:')) > > # Calculate a series of expenses I left this comment because it explains why we have a loop... > expense = float(raw_input('Enter your first expense $')) > total_expense = total_expense + expense > while expense != 0: > expense = float(raw_input('Enter the next expense or 0 to > finish')) > surplus = budget - total_expense > > print 'Your total expenses for the month $', total_expense > print 'Your surplus amount after expenses $', surplus > > main() Hopefully that makes it easier to see what you missed out? -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From lea-parker at bigpond.com Sat Apr 16 01:42:41 2011 From: lea-parker at bigpond.com (Lea Parker) Date: Sat, 16 Apr 2011 09:42:41 +1000 Subject: [Tutor] than "Re: Contents of Tutor digest..." Tutor Digest, Vol 86, Issue 56 Message-ID: <000501cbfbc6$cfafc350$6f0f49f0$@bigpond.com> Thank you message 4 this has solved my problem I can now work out the next part of my program. Thank you so much. -----Original Message----- From: tutor-bounces+lea-parker=bigpond.com at python.org [mailto:tutor-bounces+lea-parker=bigpond.com at python.org] On Behalf Of tutor-request at python.org Sent: Saturday, 16 April 2011 8:47 AM To: tutor at python.org Subject: Tutor Digest, Vol 86, Issue 56 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. Help to explain commenting (Andr?s Chand?a) 2. Re: Python on TV (Alan Gauld) 3. Help - accumulator not working (Lea) (Lea Parker) 4. Re: Help - accumulator not working (Lea) (Joel Goldstick) ---------------------------------------------------------------------- Message: 1 Date: Fri, 15 Apr 2011 18:21:43 +0200 From: "Andr?s Chand?a" Subject: [Tutor] Help to explain commenting Message-ID: <957d7e2abbfe95f19b83cef056261697.squirrel at mail.chandia.net> Content-Type: text/plain; charset="iso-8859-1" Hello everybody, I could finally complete succesfully the code I was working with. As I'm quite new to python, many of the things I have in my code are copied from different sources, and I do not undertand all of them, well, I have to deliver this code for a project, and in the best documented way that I could, I already commented all that I know, and I suppouse wrongly in some parts. So the request is, if you can take a look at the code, comment the parts that are not yet commented, correct the errors, and propouse some improvement in the parts you think diserves it. I attach the code in a tgz file, if the attached can not be seen then this link: http://www.chandia.net/compart/NMT-2.4-20110415.tar.gz Thanks in advance to all of you and to the people that already helped me. _______________________ ????????????andr?s chand?a P No imprima innecesariamente. ?Cuide el medio ambiente! -------------- next part -------------- A non-text attachment was scrubbed... Name: NMT-2.4-20110415.tar.gz Type: application/x-gzip Size: 4177 bytes Desc: not available URL: ------------------------------ Message: 2 Date: Fri, 15 Apr 2011 20:35:14 +0100 From: "Alan Gauld" To: tutor at python.org Subject: Re: [Tutor] Python on TV Message-ID: Content-Type: text/plain; format=flowed; charset="iso-8859-1"; reply-type=response "bob gailer" wrote >> The show should be here - Pause at 1 minute 20 for the Python >> screnshot: >> >> http://fwd.channel5.com/gadget-show/videos/challenge/surprise-special >> -part-4 > > I am told "the video ... cannot be viewed from your currrent country > ..." I don't know if YouTube will be any more obliging but try this: http://www.youtube.com/watch?v=oDNZP1X30WE&list=SL Python can be seen at around 29 mins 45 secs... Enjoy (I hope) Alan G. ------------------------------ Message: 3 Date: Sat, 16 Apr 2011 07:52:22 +1000 From: "Lea Parker" To: Subject: [Tutor] Help - accumulator not working (Lea) Message-ID: <000001cbfbb7$666bd140$334373c0$@bigpond.com> Content-Type: text/plain; charset="us-ascii" Hello I am trying to create this program for a uni assignment. I cannot get it to add the expenses to the accumulator I have set. Would you mind having a look and letting me know if I have something in the wrong place or indented incorrectly. Perhaps I am missing something. There could be other things wrong but I need to fix this first and then I can focus on the next thing. I have difficulty trying to fix lots of things at once so if you could just comment on the problem and I will ask again if I can't work out the next problem I have. I like to have a go myself first. J My code is: """This program is to calculate if the user is over or under budget for the month""" def main(): # Create an accumulator total_expense = 0.0 # Ask user for the monthly budget budget = float(raw_input('Enter the amount of your budget for the month: $')) # Calculate a series of expenses expense = float(raw_input('Enter your first expense $')) # Accumlate expense total_expense = total_expense + expense # Continue processing as long as the user # does not enter 0 while expense != 0: #Get another expense expense = float(raw_input('Enter the next expense or 0 to finish $')) #Calculate surplus surplus = budget - total_expense #Display results print 'Your total expenses for the month $', total_expense print 'Your surplus amount after expenses $', surplus # Call the main function. main() Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: ------------------------------ Message: 4 Date: Fri, 15 Apr 2011 18:47:21 -0400 From: Joel Goldstick To: tutor at python.org Subject: Re: [Tutor] Help - accumulator not working (Lea) Message-ID: Content-Type: text/plain; charset="utf-8" On Fri, Apr 15, 2011 at 5:52 PM, Lea Parker wrote: > Hello > > > > I am trying to create this program for a uni assignment. I cannot get > it to add the expenses to the accumulator I have set. Would you mind > having a look and letting me know if I have something in the wrong > place or indented incorrectly. Perhaps I am missing something. > > > > There could be other things wrong but I need to fix this first and > then I can focus on the next thing. I have difficulty trying to fix > lots of things at once so if you could just comment on the problem and > I will ask again if I can?t work out the next problem I have. I like to have a go myself first. > J > > > > My code is: > > > > """This program is to calculate if the user is over or under budget > > for the month""" > > > > > > def main(): > > > > # Create an accumulator > > total_expense = 0.0 > > > > # Ask user for the monthly budget > > budget = float(raw_input('Enter the amount of your budget for the > month: $')) > > > above here is good > > > # Calculate a series of expenses > > expense = float(raw_input('Enter your first expense $')) > > > I would remove the input above and move it to your loop. > # Accumlate expense > > total_expense = total_expense + expense > > above you don't need this since you haven't added anything yet (see below) > > I set expense to 1 just to get the loop started. It could be anything but 0 > # Continue processing as long as the user > > # does not enter 0 > > while expense != 0: > > > > #Get another expense > > expense = float(raw_input('Enter the next expense or 0 to > finish > $')) > > > > #Calculate surplus > > surplus = budget - total_expense > > > > #Display results > > print 'Your total expenses for the month $', total_expense > > print 'Your surplus amount after expenses $', surplus > > > > # Call the main function. > > main() > > > > Thank you. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > def main(): # Create an accumulator total_expense = 0.0 # Ask user for the monthly budget budget = float(raw_input('Enter the amount of your budget for the month: $')) expense = 1 total_expense = 0 while expense != 0: #Get another expense expense = float(raw_input('Enter the next expense or 0 to finish $')) #Calculate surplus total_expense = total_expense + expense surplus = budget - total_expense print budget, total_expense #Display results print 'Your total expenses for the month $', total_expense print 'Your surplus amount after expenses $', surplus main() Good luck with your course -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: ------------------------------ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor End of Tutor Digest, Vol 86, Issue 56 ************************************* From lea-parker at bigpond.com Sat Apr 16 01:58:07 2011 From: lea-parker at bigpond.com (Lea Parker) Date: Sat, 16 Apr 2011 09:58:07 +1000 Subject: [Tutor] Contents of Tutor digest Vol 86 Issue 57 Message-ID: <000a01cbfbc8$f7b77ee0$e7267ca0$@bigpond.com> Hi Michael Scott Thank you and yes I agree there is room for user error. I am going to add a validator but I wanted to get the first part right. I appreciate your comment on the white space too. Being a beginner I find it easier to write the main thing I want the code to do and then add extra to make it work efficiently. Perhaps not what a programmer does but it helps me this way. Thanks so much. Leonie -----Original Message----- From: tutor-bounces+lea-parker=bigpond.com at python.org [mailto:tutor-bounces+lea-parker=bigpond.com at python.org] On Behalf Of tutor-request at python.org Sent: Saturday, 16 April 2011 9:43 AM To: tutor at python.org Subject: Tutor Digest, Vol 86, Issue 57 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: Help - accumulator not working (Lea) (michael scott) 2. Re: Help - accumulator not working (Lea) (Alan Gauld) 3. Re: than "Re: Contents of Tutor digest..." Tutor Digest, Vol 86, Issue 56 (Lea Parker) ---------------------------------------------------------------------- Message: 1 Date: Fri, 15 Apr 2011 15:46:32 -0700 (PDT) From: michael scott To: tutor at python.org Subject: Re: [Tutor] Help - accumulator not working (Lea) Message-ID: <670739.27615.qm at web130203.mail.mud.yahoo.com> Content-Type: text/plain; charset="utf-8" Hi Lea, how are you today? Well please keep in mind that nothing is "wrong" with your code, its doing exactly what you asked it to do. But I would call your attention to your while loop, you want to accumulate things, but may I ask exactly what are you accumulating in your loop? Also quite by accident I entered 00 as my budget and I got a negative surplus, lol. Perhaps you should implement something that ensures that a (stupid) user like myself does not enter a 0- or negative value for the budget. Just a thought... To help me attempt to understand the small programs I write, I pretend that I'm the computer and I literally compute the program as if I was the interpreter, I follow each line of my code to truly understand it. Perhaps with these gentle nudges you will solve your problem :) ---- What is it about you... that intrigues me so? ________________________________ From: Lea Parker To: tutor at python.org Sent: Fri, April 15, 2011 5:52:22 PM Subject: [Tutor] Help - accumulator not working (Lea) Hello I am trying to create this program for a uni assignment. I cannot get it to add the expenses to the accumulator I have set. Would you mind having a look and letting me know if I have something in the wrong place or indented incorrectly. Perhaps I am missing something. There could be other things wrong but I need to fix this first and then I can focus on the next thing. I have difficulty trying to fix lots of things at once so if you could just comment on the problem and I will ask again if I can?t work out the next problem I have. I like to have a go myself first. J My code is: """This program is to calculate if the user is over or under budget for the month""" def main(): # Create an accumulator total_expense = 0.0 # Ask user for the monthly budget budget = float(raw_input('Enter the amount of your budget for the month: $')) # Calculate a series of expenses expense = float(raw_input('Enter your first expense $')) # Accumlate expense total_expense = total_expense + expense # Continue processing as long as the user # does not enter 0 while expense != 0: #Get another expense expense = float(raw_input('Enter the next expense or 0 to finish $')) #Calculate surplus surplus = budget - total_expense #Display results print 'Your total expenses for the month $', total_expense print 'Your surplus amount after expenses $', surplus # Call the main function. main() Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: ------------------------------ Message: 2 Date: Sat, 16 Apr 2011 00:27:22 +0100 From: "Alan Gauld" To: tutor at python.org Subject: Re: [Tutor] Help - accumulator not working (Lea) Message-ID: Content-Type: text/plain; format=flowed; charset="iso-8859-1"; reply-type=original "Lea Parker" wrote > I am trying to create this program for a uni assignment. I cannot get > it to add the expenses to the accumulator I have set. You have to write the code to add each value to the accumulator Your loop does not do that.... > """This program is to calculate if the user is over or under budget > > for the month""" > > > > Wow! Thats a lot of whitespace. It is good to separate code blocks into logical segments with whitespace, but too much of it just makes the code flow hard to see. In the old days of green screen terminals on mainframes they used to say that a function should all fit on a single screen - 24 lines. Nowadays we don't need to be quite so penny pinching, but the concept of seeing the whole flow in one place is a good one. I'll remove some excess space below... > def main(): > # Create an accumulator Oh, and if you can use a good variable name to describe the variable you don't need a comment either - It's just more distracting wasted space. Comments are to explain *why* (and occasionally, for the really obscure, how), but good names describe what. > total_expense = 0.0 > budget = float(raw_input('Enter the amount of your budget for the > month:')) > > # Calculate a series of expenses I left this comment because it explains why we have a loop... > expense = float(raw_input('Enter your first expense $')) > total_expense = total_expense + expense > while expense != 0: > expense = float(raw_input('Enter the next expense or 0 to > finish')) > surplus = budget - total_expense > > print 'Your total expenses for the month $', total_expense > print 'Your surplus amount after expenses $', surplus > > main() Hopefully that makes it easier to see what you missed out? -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ------------------------------ Message: 3 Date: Sat, 16 Apr 2011 09:42:41 +1000 From: "Lea Parker" To: Subject: Re: [Tutor] than "Re: Contents of Tutor digest..." Tutor Digest, Vol 86, Issue 56 Message-ID: <000501cbfbc6$cfafc350$6f0f49f0$@bigpond.com> Content-Type: text/plain; charset="us-ascii" Thank you message 4 this has solved my problem I can now work out the next part of my program. Thank you so much. -----Original Message----- From: tutor-bounces+lea-parker=bigpond.com at python.org [mailto:tutor-bounces+lea-parker=bigpond.com at python.org] On Behalf Of tutor-request at python.org Sent: Saturday, 16 April 2011 8:47 AM To: tutor at python.org Subject: Tutor Digest, Vol 86, Issue 56 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. Help to explain commenting (Andr?s Chand?a) 2. Re: Python on TV (Alan Gauld) 3. Help - accumulator not working (Lea) (Lea Parker) 4. Re: Help - accumulator not working (Lea) (Joel Goldstick) ---------------------------------------------------------------------- Message: 1 Date: Fri, 15 Apr 2011 18:21:43 +0200 From: "Andr?s Chand?a" Subject: [Tutor] Help to explain commenting Message-ID: <957d7e2abbfe95f19b83cef056261697.squirrel at mail.chandia.net> Content-Type: text/plain; charset="iso-8859-1" Hello everybody, I could finally complete succesfully the code I was working with. As I'm quite new to python, many of the things I have in my code are copied from different sources, and I do not undertand all of them, well, I have to deliver this code for a project, and in the best documented way that I could, I already commented all that I know, and I suppouse wrongly in some parts. So the request is, if you can take a look at the code, comment the parts that are not yet commented, correct the errors, and propouse some improvement in the parts you think diserves it. I attach the code in a tgz file, if the attached can not be seen then this link: http://www.chandia.net/compart/NMT-2.4-20110415.tar.gz Thanks in advance to all of you and to the people that already helped me. _______________________ ????????????andr?s chand?a P No imprima innecesariamente. ?Cuide el medio ambiente! -------------- next part -------------- A non-text attachment was scrubbed... Name: NMT-2.4-20110415.tar.gz Type: application/x-gzip Size: 4177 bytes Desc: not available URL: ------------------------------ Message: 2 Date: Fri, 15 Apr 2011 20:35:14 +0100 From: "Alan Gauld" To: tutor at python.org Subject: Re: [Tutor] Python on TV Message-ID: Content-Type: text/plain; format=flowed; charset="iso-8859-1"; reply-type=response "bob gailer" wrote >> The show should be here - Pause at 1 minute 20 for the Python >> screnshot: >> >> http://fwd.channel5.com/gadget-show/videos/challenge/surprise-special >> -part-4 > > I am told "the video ... cannot be viewed from your currrent country > ..." I don't know if YouTube will be any more obliging but try this: http://www.youtube.com/watch?v=oDNZP1X30WE&list=SL Python can be seen at around 29 mins 45 secs... Enjoy (I hope) Alan G. ------------------------------ Message: 3 Date: Sat, 16 Apr 2011 07:52:22 +1000 From: "Lea Parker" To: Subject: [Tutor] Help - accumulator not working (Lea) Message-ID: <000001cbfbb7$666bd140$334373c0$@bigpond.com> Content-Type: text/plain; charset="us-ascii" Hello I am trying to create this program for a uni assignment. I cannot get it to add the expenses to the accumulator I have set. Would you mind having a look and letting me know if I have something in the wrong place or indented incorrectly. Perhaps I am missing something. There could be other things wrong but I need to fix this first and then I can focus on the next thing. I have difficulty trying to fix lots of things at once so if you could just comment on the problem and I will ask again if I can't work out the next problem I have. I like to have a go myself first. J My code is: """This program is to calculate if the user is over or under budget for the month""" def main(): # Create an accumulator total_expense = 0.0 # Ask user for the monthly budget budget = float(raw_input('Enter the amount of your budget for the month: $')) # Calculate a series of expenses expense = float(raw_input('Enter your first expense $')) # Accumlate expense total_expense = total_expense + expense # Continue processing as long as the user # does not enter 0 while expense != 0: #Get another expense expense = float(raw_input('Enter the next expense or 0 to finish $')) #Calculate surplus surplus = budget - total_expense #Display results print 'Your total expenses for the month $', total_expense print 'Your surplus amount after expenses $', surplus # Call the main function. main() Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: ------------------------------ Message: 4 Date: Fri, 15 Apr 2011 18:47:21 -0400 From: Joel Goldstick To: tutor at python.org Subject: Re: [Tutor] Help - accumulator not working (Lea) Message-ID: Content-Type: text/plain; charset="utf-8" On Fri, Apr 15, 2011 at 5:52 PM, Lea Parker wrote: > Hello > > > > I am trying to create this program for a uni assignment. I cannot get > it to add the expenses to the accumulator I have set. Would you mind > having a look and letting me know if I have something in the wrong > place or indented incorrectly. Perhaps I am missing something. > > > > There could be other things wrong but I need to fix this first and > then I can focus on the next thing. I have difficulty trying to fix > lots of things at once so if you could just comment on the problem and > I will ask again if I can?t work out the next problem I have. I like to have a go myself first. > J > > > > My code is: > > > > """This program is to calculate if the user is over or under budget > > for the month""" > > > > > > def main(): > > > > # Create an accumulator > > total_expense = 0.0 > > > > # Ask user for the monthly budget > > budget = float(raw_input('Enter the amount of your budget for the > month: $')) > > > above here is good > > > # Calculate a series of expenses > > expense = float(raw_input('Enter your first expense $')) > > > I would remove the input above and move it to your loop. > # Accumlate expense > > total_expense = total_expense + expense > > above you don't need this since you haven't added anything yet (see below) > > I set expense to 1 just to get the loop started. It could be anything but 0 > # Continue processing as long as the user > > # does not enter 0 > > while expense != 0: > > > > #Get another expense > > expense = float(raw_input('Enter the next expense or 0 to > finish > $')) > > > > #Calculate surplus > > surplus = budget - total_expense > > > > #Display results > > print 'Your total expenses for the month $', total_expense > > print 'Your surplus amount after expenses $', surplus > > > > # Call the main function. > > main() > > > > Thank you. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > def main(): # Create an accumulator total_expense = 0.0 # Ask user for the monthly budget budget = float(raw_input('Enter the amount of your budget for the month: $')) expense = 1 total_expense = 0 while expense != 0: #Get another expense expense = float(raw_input('Enter the next expense or 0 to finish $')) #Calculate surplus total_expense = total_expense + expense surplus = budget - total_expense print budget, total_expense #Display results print 'Your total expenses for the month $', total_expense print 'Your surplus amount after expenses $', surplus main() Good luck with your course -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: ------------------------------ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor End of Tutor Digest, Vol 86, Issue 56 ************************************* ------------------------------ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor End of Tutor Digest, Vol 86, Issue 57 ************************************* From therealdotcomboy at gmail.com Sat Apr 16 03:00:38 2011 From: therealdotcomboy at gmail.com (Rodney Lewis) Date: Fri, 15 Apr 2011 18:00:38 -0700 Subject: [Tutor] os.chdir() will not accept string variable Message-ID: I cannot get os.chdir() to accept inputData[0]. os.chdir() works as expected in the interpreter when I put the little 'r' before the exact same string but as a literal, e.g.: r"F:\Music\Siouxsie and the Banshees\the rapture" When I try to run it I get the following error in reference to the os.chdir() line: WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect 'F:\\Music\\Siouxsie and the Banshees\\the rapture\n' Why is it doubling the backslashes and adding '\n' to the end? How do I make it stop? What does the little 'r' mean before a string literal and how do I do the same for a string variable? # mdf -- mp3datafixer import glob, os def mdf(): inputFile = open( 'mdfinputs.txt', 'r' ) inputData = inputFile.readlines() inputFile.close() os.chdir( r'%s' % inputData[0] ) newNames = [] oldNames = glob.glob( '*.*' ) for index, item in enumerate( oldNames ): print index, item if __name__ == '__main__': mdf() raw_input( "\nPress 'enter' to close console window:" ) # Keeps console window open in Windows Thanks! -- Rodney Lewis Please Visit My Homepage: http://www.squidoo.com/dotcomboy From steve at alchemy.com Sat Apr 16 03:13:47 2011 From: steve at alchemy.com (Steve Willoughby) Date: Fri, 15 Apr 2011 18:13:47 -0700 Subject: [Tutor] os.chdir() will not accept string variable In-Reply-To: References: Message-ID: <4DA8ED4B.4020701@alchemy.com> On 15-Apr-11 18:00, Rodney Lewis wrote: > I cannot get os.chdir() to accept inputData[0]. os.chdir() works as > expected in the interpreter when I put the little 'r' before the exact > same string but as a literal, e.g.: r"F:\Music\Siouxsie and the > Banshees\the rapture" It's because the string in inputData[0] has a trailing newline. > WindowsError: [Error 123] The filename, directory name, or volume > label syntax is incorrect 'F:\\Music\\Siouxsie and the Banshees\\the > rapture\n' > > Why is it doubling the backslashes and adding '\n' to the end? How do The actual string value is: F:\Music\Sousie and the Banshees\the rapture When printing it out to you in the error message, Python REPRESENTED that string TO YOU with extra backslash codes so you could see what was in the sring: F:\\Music\\Sousie and the Banshees\\the rapture\n The extra backslashes aren't really in the string. Your problem is that readlines() retains the end-of-line character in the lines it reads, which is not actually part of the filename, so os.chdir() doesn't like it. You'll need to strip off the newlines from the strings you read before giving them to os.chdir(). > I make it stop? What does the little 'r' mean before a string literal > and how do I do the same for a string variable? It means not to interpret (most) backslash codes in the string as it's compiled from your source code into the internal string data managed by the program. If you wanted to put that string literally in your source code, you could do either of these: 'F:\\Music\\Sousie and the Banshees\\the rapture' or r'F:\Music\Sousie and the Banshees\the rapture' But that's not your problem in this case. You don't need this when reading in lines of data from another source, since they wouldn't get the same backslash interpretation as source lines do. > > # mdf -- mp3datafixer > > import glob, os > > def mdf(): > inputFile = open( 'mdfinputs.txt', 'r' ) > inputData = inputFile.readlines() > inputFile.close() > > os.chdir( r'%s' % inputData[0] ) > newNames = [] > oldNames = glob.glob( '*.*' ) > for index, item in enumerate( oldNames ): > print index, item > > if __name__ == '__main__': > mdf() > raw_input( "\nPress 'enter' to close console window:" ) # Keeps > console window open in Windows > > Thanks! > > -- 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 bgailer at gmail.com Sat Apr 16 05:07:12 2011 From: bgailer at gmail.com (bob gailer) Date: Fri, 15 Apr 2011 23:07:12 -0400 Subject: [Tutor] Python on TV In-Reply-To: References: <4DA36CEB.7090507@gmail.com> Message-ID: <4DA907E0.5090502@gmail.com> On 4/15/2011 3:35 PM, Alan Gauld wrote: > "bob gailer" wrote > >>> The show should be here - Pause at 1 minute 20 for the >>> Python screnshot: >>> >>> http://fwd.channel5.com/gadget-show/videos/challenge/surprise-special-part-4 >>> >> >> I am told "the video ... cannot be viewed from your currrent country >> ..." > > I don't know if YouTube will be any more obliging but try this: > > http://www.youtube.com/watch?v=oDNZP1X30WE&list=SL > Nope. -- Bob Gailer 919-636-4239 Chapel Hill NC From lea-parker at bigpond.com Sat Apr 16 05:33:28 2011 From: lea-parker at bigpond.com (Lea Parker) Date: Sat, 16 Apr 2011 13:33:28 +1000 Subject: [Tutor] Help - 2nd validator won't work Message-ID: <000001cbfbe7$0d41e2f0$27c5a8d0$@bigpond.com> Hello I now need to get the validator to work on my expense input. If the user puts in a negative I want an error to come up. I have managed it for the budget input but cannot seem to get it to work for the expense. Thanks in advance again for your wonderful help. """This program is to calculate if the user is over or under budget for the month""" def main(): # Create an accumulator total_expense = 0.00 # Ask user for the monthly budget budget = float(raw_input('Enter the amount of your budget for the month: ')) # Validation variable for budget while budget <0: print 'ERROR: the budget cannot be a negative amount' budget = float(raw_input('Enter the correct budget for the month: ')) # Ask user for expense expense = float(raw_input('Enter your first expense ')) total_expense += expense # Continue processing as long as the user does not enter 0 while expense != 0: #Get another expense expense = float(raw_input('Enter expense or 0 to finish ')) total_expense += expense # Validation variable for expense while expense <0: print 'ERROR: the budget cannot be a negative amount' expense = float(raw_input('Enter the correct budget for the month: ')) total_expense += expense #Calculate surplus budget_difference = budget - total_expense #Display results print 'Your total expenses for the month ', total_expense if budget_difference>=0: print 'You are under budget by ', budget_difference, 'dollars.' else: print 'You are over budget by ', budget_difference, 'dollars.' # Call the main function. main() -------------- next part -------------- An HTML attachment was scrubbed... URL: From enalicho at gmail.com Sat Apr 16 09:48:20 2011 From: enalicho at gmail.com (Noah Hall) Date: Sat, 16 Apr 2011 08:48:20 +0100 Subject: [Tutor] Help - 2nd validator won't work In-Reply-To: <000001cbfbe7$0d41e2f0$27c5a8d0$@bigpond.com> References: <000001cbfbe7$0d41e2f0$27c5a8d0$@bigpond.com> Message-ID: On Sat, Apr 16, 2011 at 4:33 AM, Lea Parker wrote: > ??? budget = float(raw_input('Enter the amount of your budget for the month: > ')) > > ??? # Validation variable for budget > > ??? while budget <0: > > ??????? print 'ERROR: the budget cannot be a negative amount' > > ??????? budget = float(raw_input('Enter the correct budget for the month: > ')) > This is alright, but it still allows users to enter 0 for the budget > ??? expense = float(raw_input('Enter your first expense ')) > > ??? total_expense += expense This is where you're going wrong. You don't validate the expense here at all before adding it to total_expense. > ????# Continue processing as long as the user does not enter 0 > > ??? while expense != 0: > ??????? #Get another expense > > ??????? expense = float(raw_input('Enter expense or 0 to finish ')) > > ??????? total_expense += expense > > ??????? while expense <0: > > ??????????? print 'ERROR: the budget cannot be a negative amount' > > ??????????? expense = float(raw_input('Enter the correct budget for the > month: ')) > > ??????????? total_expense += expense Same again here as above. > ????#Calculate surplus > > ??? budget_difference = budget - total_expense > Now, given that total_expense could be negative, you'll end up with a budget_difference that is in fact larger than the budget - crazy, I know. > # Call the main function. > > main() It's also good practise to use if __name__ == '__main__': main() So that you can then use this script for a module later on. HTH From japhy at pearachute.com Sat Apr 16 01:50:59 2011 From: japhy at pearachute.com (Japhy Bartlett) Date: Fri, 15 Apr 2011 19:50:59 -0400 Subject: [Tutor] Help - accumulator not working (Lea) In-Reply-To: <000001cbfbb7$666bd140$334373c0$@bigpond.com> References: <000001cbfbb7$666bd140$334373c0$@bigpond.com> Message-ID: I think that here: > ??????? expense = float(raw_input('Enter the next expense or 0 to finish $')) you want to use `expense +=` instead. Instead of adding it to the previous expenses, you're resetting the `expense` variable each time. I think there's some other things that won't behave as expected, but that seems what like you asked. - @japherwocky From tsartsaris at gmail.com Sat Apr 16 23:50:44 2011 From: tsartsaris at gmail.com (Sotiris Tsartsaris) Date: Sun, 17 Apr 2011 00:50:44 +0300 Subject: [Tutor] Fwd: Python skipping if statement (Really simple code) In-Reply-To: References: Message-ID: this proceed = input(int("Do you want to see Renees hate in form of a > picture? ")) > if proceed == "yes": > > should be proceed = input("Do you want to see Renees hate in form of a picture? ") if proceed == "yes": cause you are checking for a yes or no but you convert the input of the user to an integer. nice drawings by the way -- Tsartsaris Sotirios -------------- next part -------------- An HTML attachment was scrubbed... URL: From wallenpb at gmail.com Sun Apr 17 00:13:53 2011 From: wallenpb at gmail.com (Bill Allen) Date: Sat, 16 Apr 2011 17:13:53 -0500 Subject: [Tutor] os.rename vs. shutil.move Message-ID: What are the particular advantages or disadvantages concerning using either os.rename or shutil.move to rename a file. I have tried both and for simple renaming they seem equivalent. Thanks, Bill Allen -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sun Apr 17 01:15:11 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 17 Apr 2011 09:15:11 +1000 Subject: [Tutor] os.rename vs. shutil.move In-Reply-To: References: Message-ID: <4DAA22FF.2050205@pearwood.info> Bill Allen wrote: > What are the particular advantages or disadvantages concerning using either > os.rename or shutil.move to rename a file. I have tried both and for > simple renaming they seem equivalent. Consider non-simple renaming. At the interactive interpreter, call: help(os.rename) and then help(shutil.move) to be enlightened. And read the Fine Manual: http://docs.python.org/library/shutil.html which conveniently now links directly to the source code, so you can see for yourself all the extra work shutil.move does to cover cases which os.rename may not cover (depending on the OS and/or file system). http://docs.python.org/library/os.html#os.rename os.rename is a thin wrapper around your file system's rename/mv command, with the same limitations as it has. shutil.move attempts to do extra work to overcome such limitations. -- Steven From ranceh at gmail.com Sun Apr 17 01:49:18 2011 From: ranceh at gmail.com (Rance Hall) Date: Sat, 16 Apr 2011 18:49:18 -0500 Subject: [Tutor] data validation logic Message-ID: Hey gang: I need some help trying to pythonize (sp?, if this is even a word?) an idea. I'd like to define a datavalidation function that returns true if data is valid, and false if it isn't. Here is the clincher. the logic of the data validator needs to be able to handle different types of data testing on request. So here is my idea: Define a function that can accept multiple inputs. One being the data element to validate, and the additional arguments, which can be null would define the validation needing to be done. For example, if a match value, or set of match values is defined, check the data element to ensure it matches one of the match values. I'd also like to be able to feed this data validator a list of names of tests to check (numeric, alpha-numeric, maxlength=10, etc.) each of these names would be the names of the various sub tests the validator can perform eventually I'll probably convert this to a class, but I really don't have a knack for OOP yet. (I'm still learning that.) Anyway so here is the problem I see with this idea and can't quite figure out how to handle. I need a way to store the pass fail values of each of the individual tests, and then return a pass if the data passes ALL tests no matter how many individual tests might be executed. In my mind an associative array is the best way to track this. It can be dynamically created with each call of the function and the array elements can be named for each test ran. The problem is the final test of pass/fail based on the pass/fail results of individual tests. It might be as simple as looping through the array elements and if any value is false break out of the loop and return false. else if all are true return true. Would someone be kind enough to help me work out the finer details of such an approach. Perhaps lists might be better for this sort of thing?, perhaps I have screwed up my logic somewhere? Thanks for any hints you can provide. PS this is on python 3.x. Rance From wallenpb at gmail.com Sun Apr 17 01:56:50 2011 From: wallenpb at gmail.com (Bill Allen) Date: Sat, 16 Apr 2011 18:56:50 -0500 Subject: [Tutor] os.rename vs. shutil.move In-Reply-To: <4DAA22FF.2050205@pearwood.info> References: <4DAA22FF.2050205@pearwood.info> Message-ID: Ok, thanks. --Bill On Sat, Apr 16, 2011 at 18:15, Steven D'Aprano wrote: > Bill Allen wrote: > >> What are the particular advantages or disadvantages concerning using >> either >> os.rename or shutil.move to rename a file. I have tried both and for >> simple renaming they seem equivalent. >> > > Consider non-simple renaming. > > At the interactive interpreter, call: > > help(os.rename) > > and then > > help(shutil.move) > > to be enlightened. > > And read the Fine Manual: > > http://docs.python.org/library/shutil.html > > which conveniently now links directly to the source code, so you can see > for yourself all the extra work shutil.move does to cover cases which > os.rename may not cover (depending on the OS and/or file system). > > http://docs.python.org/library/os.html#os.rename > > os.rename is a thin wrapper around your file system's rename/mv command, > with the same limitations as it has. shutil.move attempts to do extra work > to overcome such limitations. > > > > -- > 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 alan.gauld at btinternet.com Sun Apr 17 02:19:31 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 17 Apr 2011 01:19:31 +0100 Subject: [Tutor] data validation logic References: Message-ID: "Rance Hall" wrote > I'd like to define a datavalidation function that returns true if > data > is valid, and false if it isn't. > > > Here is the clincher. the logic of the data validator needs to be > able to handle different types of data testing on request. > This is a good candidate for a factory function which takes a function as a parameter. The function can be applied to the data and the resultant function returned as the validator used by your code. Something like(untested): def makeValidator(operator, validValues) def validator(data, vals = validValues): return operator(data, vals) return validator validLowFloat = makeValidator(lambda d,v: type(d) == float and v[0] < d < v[1], (0.0,10.0)) validChoice = makeValidator(lambda d,v: type(d) == str and d.lower() in v, ("yes", "no")) x = 12.0 print validLowFloat(x) # returns False y = 7.4 print validLowFloat(y) # returns True s = "Maybe" print validChoice(s) # -> False print validChoice("No") # -> True If you really want to get clever you could probably wrap this as a decorator! Whether its worth the effort over just defining validators as needed is another matter... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Sun Apr 17 04:09:24 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 17 Apr 2011 12:09:24 +1000 Subject: [Tutor] Contents of Tutor digest Vol 86 Issue 57 In-Reply-To: <000a01cbfbc8$f7b77ee0$e7267ca0$@bigpond.com> References: <000a01cbfbc8$f7b77ee0$e7267ca0$@bigpond.com> Message-ID: <4DAA4BD4.20300@pearwood.info> Lea Parker wrote: > Hi Michael Scott > > Thank you and yes I agree there is room for user error. I am going to add a > validator but I wanted to get the first part right. I appreciate your > comment on the white space too. > > Being a beginner I find it easier to write the main thing I want the code to > do and then add extra to make it work efficiently. Perhaps not what a > programmer does but it helps me this way. No, that's a perfectly acceptable way of programming. In fact, it's the best way: Make it work. Make it correct. Then make it fast. http://en.wikipedia.org/wiki/Program_optimization#Quotes You can't imagine how much time and effort has been wasted by people trying to optimize broken code, so that code that does the wrong thing does it really, really quickly. It's a macho thing (no offense to Michael): many programmers like to think of themselves as "top guns" writing the fastest, tightest code imaginable, but writing *correct* code is tedious, hard work. It's *easy* to time how fast code runs (although very tricky to *accurately* time how fast it runs), but quite difficult to test code for correctness. In one of my projects, I have approximately three lines of test code checking correctness for every line of code to do the work, and I consider that barely adequate to be confident that my code contains no *obvious* errors. (By the way, when replying to a Digest, could you please change the subject line to something more sensible?) -- Steven From ladymcse2000 at gmail.com Sun Apr 17 08:54:53 2011 From: ladymcse2000 at gmail.com (Becky Mcquilling) Date: Sat, 16 Apr 2011 23:54:53 -0700 Subject: [Tutor] Creating Binary Files of 1MB Message-ID: I'm trying to work out a method to create a binary file of 1mb and I'm somewhat confused by the docs I'm reading is there a method that will do this? Becky -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sun Apr 17 09:34:18 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 17 Apr 2011 17:34:18 +1000 Subject: [Tutor] Creating Binary Files of 1MB In-Reply-To: References: Message-ID: <4DAA97FA.6030903@pearwood.info> Becky Mcquilling wrote: > I'm trying to work out a method to create a binary file of 1mb and I'm > somewhat confused by the docs I'm reading is there a method that will do > this? # Open a file in binary (b) mode for writing. fp = open("mybinaryfile", "wb") # Write whatever data you like to it. fp.write('\0'*1000000) fp.close() That writes one million ASCII NULL bytes to the file. If you prefer binary megabytes instead of decimal megabytes, use 1024*1024 instead of one million. If you want some other binary data, you'll have to tell us what binary data you want to write. -- Steven From davea at ieee.org Sun Apr 17 12:46:11 2011 From: davea at ieee.org (Dave Angel) Date: Sun, 17 Apr 2011 06:46:11 -0400 Subject: [Tutor] data validation logic In-Reply-To: References: Message-ID: <4DAAC4F3.6080505@ieee.org> On 01/-10/-28163 02:59 PM, Rance Hall wrote: > Hey gang: > > I need some help trying to pythonize (sp?, if this is even a word?) an idea. > > I'd like to define a datavalidation function that returns true if data > is valid, and false if it isn't. > > > > I need a way to store the pass fail values of each of the individual > tests, and then return a pass if the data passes ALL tests no matter > how many individual tests might be executed. > > In my mind an associative array is the best way to track this. It can > be dynamically created with each call of the function and the array > elements can be named for each test ran. > > The problem is the final test of pass/fail based on the pass/fail > results of individual tests. > > It might be as simple as looping through the array elements and if any > value is false break out of the loop and return false. else if all > are true return true. > Alan gave a suggestion for the first part of your approach. Essentially, generate a function object for each test you want to perform. For the "return a pass if the data passes ALL..." part, you can use the all() builtin function. You mention having an "associative array" (known in Python as a dict) containing the Trues and Falses for the corresponding tests. To determine if all items in the dict are true, use all(mydict.itervalues()) But, if you don't need to keep track of which test failed, why not just store the results in a list? Then use all(mylist) That will return True if all the items in the list are true, and False if any of them is false. DaveA From ladymcse2000 at gmail.com Sun Apr 17 19:39:13 2011 From: ladymcse2000 at gmail.com (Becky Mcquilling) Date: Sun, 17 Apr 2011 10:39:13 -0700 Subject: [Tutor] Creating Binary Files of 1MB In-Reply-To: <4DAA97FA.6030903@pearwood.info> References: <4DAA97FA.6030903@pearwood.info> Message-ID: Thanks, Steve. For the first step, I just wasn't sure how to write the file. I appreciate the help. Becky On Sun, Apr 17, 2011 at 12:34 AM, Steven D'Aprano wrote: > Becky Mcquilling wrote: > >> I'm trying to work out a method to create a binary file of 1mb and I'm >> somewhat confused by the docs I'm reading is there a method that will do >> this? >> > > > # Open a file in binary (b) mode for writing. > fp = open("mybinaryfile", "wb") > # Write whatever data you like to it. > fp.write('\0'*1000000) > fp.close() > > > That writes one million ASCII NULL bytes to the file. If you prefer binary > megabytes instead of decimal megabytes, use 1024*1024 instead of one > million. > > If you want some other binary data, you'll have to tell us what binary data > you want to write. > > > > -- > 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 david.crisp at gmail.com Mon Apr 18 03:58:46 2011 From: david.crisp at gmail.com (David Crisp) Date: Mon, 18 Apr 2011 11:58:46 +1000 Subject: [Tutor] Memory profileing on Python 2.7 64bit for windows Message-ID: Hello, I need to look at the memory usage of a number of sets of data I am working with. I have been able to find memory profilers for Python 2.6 but I havent been able to find anything for Python 2.7 and or Python 2.7 64bit. Can anybody point me in the right direction for this? Regards, David From mebesylvie at yahoo.com Mon Apr 18 05:11:52 2011 From: mebesylvie at yahoo.com (Sylvia DeAguiar) Date: Sun, 17 Apr 2011 20:11:52 -0700 (PDT) Subject: [Tutor] Trouble executing an if statement with a string from an input Message-ID: <988275.14552.qm@web112310.mail.gq1.yahoo.com> The code runs fine on python shell (from run module) but when I try to execute the program from its file, it always prints out c, regardless of the input. What is wrong? Thanks for any help :) ? x = input("a, b, or c:") if x == "a": ??? print ("a") elif x == "b": ??? print ("b") else: ??? print ('c') -------------- next part -------------- An HTML attachment was scrubbed... URL: From timomlists at gmail.com Mon Apr 18 09:50:54 2011 From: timomlists at gmail.com (Timo) Date: Mon, 18 Apr 2011 09:50:54 +0200 Subject: [Tutor] Trouble executing an if statement with a string from an input In-Reply-To: <988275.14552.qm@web112310.mail.gq1.yahoo.com> References: <988275.14552.qm@web112310.mail.gq1.yahoo.com> Message-ID: <4DABED5E.4010300@gmail.com> On 18-04-11 05:11, Sylvia DeAguiar wrote: > > The code runs fine on python shell (from run module) but when I try to > execute the program from its file, it always prints out c, regardless > of the input. What is wrong? Thanks for any help :) > > x = input("a, b, or c:") > Enter a debug print statement here to see what 'x' really is: print repr(x) Cheers, Timo > if x == "a": > > print ("a") > > elif x == "b": > > print ("b") > > else: > > print ('c') > > > _______________________________________________ > 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 Mon Apr 18 09:59:27 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 18 Apr 2011 08:59:27 +0100 Subject: [Tutor] Trouble executing an if statement with a string from aninput References: <988275.14552.qm@web112310.mail.gq1.yahoo.com> Message-ID: "Sylvia DeAguiar" wrote > The code runs fine on python shell (from run module) but > when I try to execute the program from its file, it always > prints out c, regardless > x = input("a, b, or c:") > ... > else: > print ('c') It looks like IDLE is running Python V3 where as the shell is picking up Python V2. If you are using Linux type $ which python to check which version. You might want to create an alias for the two versions or somesuch. On Windows you may need to set up a different file association for Python. The probl;em is with the input() function. In v2 input() evaluates the string typed by the user so that in this case it returns the numeric versions of the input. Thus it never equals the strings used in your tests. In v3 input() just returns the string typed by the user. If you want your code to work in both Python versions you could explicitly convert the input() result to a string: x = str(input("a, b, or c:")) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From __peter__ at web.de Mon Apr 18 10:24:43 2011 From: __peter__ at web.de (Peter Otten) Date: Mon, 18 Apr 2011 10:24:43 +0200 Subject: [Tutor] Trouble executing an if statement with a string from aninput References: <988275.14552.qm@web112310.mail.gq1.yahoo.com> Message-ID: Alan Gauld wrote: > > "Sylvia DeAguiar" wrote > >> The code runs fine on python shell (from run module) but >> when I try to execute the program from its file, it always >> prints out c, regardless > >> x = input("a, b, or c:") >> ... >> else: >> print ('c') > > It looks like IDLE is running Python V3 where as the > shell is picking up Python V2. > > If you are using Linux type > > $ which python > > to check which version. You might want to create > an alias for the two versions or somesuch. > On Windows you may need to set up a different > file association for Python. > > The probl;em is with the input() function. > In v2 input() evaluates the string typed by the user > so that in this case it returns the numeric versions > of the input. Thus it never equals the strings used > in your tests. In v3 input() just returns the string > typed by the user. If she were using 2.x and typed an 'a' she would get a NameError. > If you want your code to work in both Python > versions you could explicitly convert the input() > result to a string: > > x = str(input("a, b, or c:")) str() doesn't magically uneval. Typing 'a' would still give you a traceback. If you want to emulate 3.x input() in 2.x: try: input = raw_input except NameError: pass Sylvia: follow Timo's advice and add print(repr(x)) # outer parens necessary for 3.x If there are different versions of Python 3 on your machine and you are using Windows you may have run into http://bugs.python.org/issue11272 . A workaround then may be x = input("a, b, or c:").strip("\r") From alan.gauld at btinternet.com Mon Apr 18 11:34:01 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 18 Apr 2011 10:34:01 +0100 Subject: [Tutor] Trouble executing an if statement with a string fromaninput References: <988275.14552.qm@web112310.mail.gq1.yahoo.com> Message-ID: "Peter Otten" <__peter__ at web.de> wrote >>> x = input("a, b, or c:") >>> ... > If she were using 2.x and typed an 'a' she would get a NameError. Oops, too early in the morning. For some reason I thought she was using numbers... Doh! >> If you want your code to work in both Python >> versions you could explicitly convert the input() >> result to a string: >> >> x = str(input("a, b, or c:")) > > str() doesn't magically uneval. Nope, again it would only work with numbers! Sorry folks, I'll drink a coffee before answering posts in future! :-) -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From element.effect at gmail.com Mon Apr 18 18:02:08 2011 From: element.effect at gmail.com (Eric Stevens) Date: Mon, 18 Apr 2011 11:02:08 -0500 Subject: [Tutor] wxPython issues Message-ID: I am trying to create an addressbook program and am currently working on prototype pages. Right now, I am trying to create a wx.ScrolledWindow class with a wx.ListCtrl to display the names of all contacts. I keep running into an error with my current configuration that is stating I have not specified the 'parent' position when instantiating my class, but from my best understanding, I have. (The full Exception Error is below). I have attatched a text file with a copy of my program. I am new at this, so I am sure my program is not optimal, so I would also appreciate any further advice or comments if you have the time. Thank you. Traceback (most recent call last): File "C:\Python27\programming\wxPython practice", line 34, in frame= RandomFrame(None, -1, 'Random') File "C:\Python27\programming\wxPython practice", line 29, in __init__ listpage = ScrolledWindow(panel, -1) File "C:\Python27\programming\wxPython practice", line 9, in __init__ wx.ScrolledWindow.__init__(self) File "C:\Python27\lib\site-packages\wx-2.8-msw-unicode\wx\_windows.py", line 145, in __init__ _windows_.ScrolledWindow_swiginit(self,_windows_.new_ScrolledWindow(*args, **kwargs)) TypeError: Required argument 'parent' (pos 1) not found -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: contacts program.rtf Type: application/rtf Size: 1512 bytes Desc: not available URL: From alan.gauld at btinternet.com Mon Apr 18 19:10:01 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 18 Apr 2011 18:10:01 +0100 Subject: [Tutor] wxPython issues References: Message-ID: "Eric Stevens" wrote > prototype pages. Right now, I am trying to create a > wx.ScrolledWindow class I would strongly recommend not calling your class the same as the standard widget. I don't think thats causing issues here but I wouldn't be surprised! Its a bit like overrriding built-in Python functions. Users of wxPython expect "ScrolledWindow" to refer to the standard one... > understanding, I have. (The full Exception Error is below). I have > attatched > a text file with a copy of my program. Being picky, you attached an RTF file which mostly won't cause a problem, but you might as well just have attached the original python code since it truly is a text file! And that way there is no chance of anything getting clipped or distorted during the cut n paste or import/conversion process > File "C:\Python27\programming\wxPython practice", line 34, in > > frame= RandomFrame(None, -1, 'Random') > File "C:\Python27\programming\wxPython practice", line 29, in > __init__ > listpage = ScrolledWindow(panel, -1) > File "C:\Python27\programming\wxPython practice", line 9, in > __init__ > wx.ScrolledWindow.__init__(self) > File > "C:\Python27\lib\site-packages\wx-2.8-msw-unicode\wx\_windows.py", > line 145, in __init__ > > _windows_.ScrolledWindow_swiginit(self,_windows_.new_ScrolledWindow(*args, > **kwargs)) > TypeError: Required argument 'parent' (pos 1) not found Your code looks like: class ScrolledWindow(wx.ScrolledWindow): def __init__(self, parent, id, style = wx.LC_REPORT): wx.ScrolledWindow.__init__(self) Notice that you do not pass the parent etc onto the superclass constructor. You need something like: wx.ScrolledWindow.__init__(self, parent, id, style) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From coolankur2006 at gmail.com Mon Apr 18 21:28:41 2011 From: coolankur2006 at gmail.com (ANKUR AGGARWAL) Date: Tue, 19 Apr 2011 00:58:41 +0530 Subject: [Tutor] First Game Attempt Message-ID: Hey I was reading Pygame API for a month and made out a very basic ,small game named as "Hungry Snake" as practice. Want to share out the code with uou guys. Here's the link http://code.google.com/p/hungry-snakes/downloads/list Thanks Ankur Aggarwal -------------- next part -------------- An HTML attachment was scrubbed... URL: From ranceh at gmail.com Tue Apr 19 02:17:42 2011 From: ranceh at gmail.com (Rance Hall) Date: Mon, 18 Apr 2011 19:17:42 -0500 Subject: [Tutor] working with strings in python3 Message-ID: Ok so I know what I am doing is deprecated (or at least poor form) but the replacement must be awkward cause I'm not getting it. so this is in a cli based program designed to print status messages to the terminal on a linux box. pseudo code: message = "Bah." if test: message = message + " Humbug!" print(message) end pseudo code I'm sure this is not the way we are supposed to augment strings like this. maybe there is string.append() method or something I should be using instead? In my case the optional extra parts are always at the end of the current value of the string. Thanks for clearing this up for me. Rance From steve at alchemy.com Tue Apr 19 02:33:14 2011 From: steve at alchemy.com (Steve Willoughby) Date: Mon, 18 Apr 2011 17:33:14 -0700 Subject: [Tutor] working with strings in python3 In-Reply-To: References: Message-ID: <4DACD84A.5020500@alchemy.com> On 18-Apr-11 17:17, Rance Hall wrote: > if test: > message = message + " Humbug!" > I'm sure this is not the way we are supposed to augment strings like this. > maybe there is string.append() method or something I should be using instead? Nope, strings are immutable so once they are instantiated they cannot be changed (or lots of things like dictionary keys would break). So you want to create a new string value by taking the current value of message, plus a new value, and assigning that back to the name "message" as a new string object: message = message + " Humbug!" Although that can be more conveniently written as message += " Humbug!" There are other approaches, like building a list of strings and later joining them, etc., but that depends on your application as to what approach makes most sense for you. message.append() is impossible because that would be altering the string object named by "message" in-place, which is disallowed for strings. -- 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 prologic at shortcircuit.net.au Tue Apr 19 02:35:42 2011 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 19 Apr 2011 10:35:42 +1000 Subject: [Tutor] working with strings in python3 In-Reply-To: References: Message-ID: On Tue, Apr 19, 2011 at 10:34 AM, James Mills wrote: > Normally it's considered bad practise to concatenate strings. > Use a a format specifier like this: > >> message = "Bah." >> >> if test: >> ? message = "%s %s" (message, " Humbug!") >> >> print(message) > > Python3 (afaik) also introduced the .format(...) method on strings. Opps I posted to the wrong list :/ -- -- James Mills -- -- "Problems are solved by method" From tktucker at gmail.com Tue Apr 19 02:27:58 2011 From: tktucker at gmail.com (tktucker at gmail.com) Date: Tue, 19 Apr 2011 00:27:58 +0000 Subject: [Tutor] working with strings in python3 In-Reply-To: Message-ID: <000e0cd4a6967c934204a13a94c7@google.com> Your code worked fine for me. Is it possible your "test" variable wasn't true? >>> message = "Bah." >>> message = message + " Humbug!" >>> print(message) Bah. Humbug! On Apr 18, 2011 8:17pm, Rance Hall wrote: > Ok so I know what I am doing is deprecated (or at least poor form) but > the replacement must be awkward cause I'm not getting it. > so this is in a cli based program designed to print status messages to > the terminal on a linux box. > pseudo code: > message = "Bah." > if test: > message = message + " Humbug!" > print(message) > end pseudo code > I'm sure this is not the way we are supposed to augment strings like this. > maybe there is string.append() method or something I should be using > instead? > In my case the optional extra parts are always at the end of the > current value of the string. > Thanks for clearing this up for me. > Rance > _______________________________________________ > 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 marc.tompkins at gmail.com Tue Apr 19 03:10:13 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Mon, 18 Apr 2011 18:10:13 -0700 Subject: [Tutor] working with strings in python3 In-Reply-To: References: Message-ID: On Mon, Apr 18, 2011 at 5:17 PM, Rance Hall wrote: > Ok so I know what I am doing is deprecated (or at least poor form) but > the replacement must be awkward cause I'm not getting it. > > > so this is in a cli based program designed to print status messages to > the terminal on a linux box. > > pseudo code: > > > message = "Bah." > > if test: > message = message + " Humbug!" > > print(message) > > end pseudo code > > > I'm sure this is not the way we are supposed to augment strings like this. > > maybe there is string.append() method or something I should be using > instead? > > In my case the optional extra parts are always at the end of the > >> current value of the string. >> > > The reason it's deprecated is because it's SLOW - since strings are immutable, there's a lot of extra copying going on behind the scenes. If this code were inside a loop, being run lots and lots of times, this would quickly become one of the bottlenecks of your program. However, in the example you've given, I'm not sure it would make an important difference - as slow as string concatenation is, it's still a heck of a lot faster than the human operator! If you just want to have a status update for your user - like a progress bar - you could simply print one string at a time and not store the result. (i.e. if you just want to display a line of dots to indicate activity, you don't need to store the full number of dots - just print one at a time - without newlines - and forget about it.) If, on the other hand, you always want to have access to the full string AND you want to print it along the way, then try a list. Lists are awesome! message = ['Bah'] # message is a list, which currently contains one item: > 'Bah' > for x in range(10): > message.append(str(x)) # append a string ('0', '1', etc.) to the list > print " ".join(message) # print the contents of the list, separated by > spaces > That's if you want to do this in a loop. If you have a set number of items to display, then string formatting is your friend: message = 'The %s in %s stays mainly in the %s' % ('rain', 'Spain', 'plain') > -------------- next part -------------- An HTML attachment was scrubbed... URL: From amonroe at columbus.rr.com Tue Apr 19 03:35:48 2011 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Mon, 18 Apr 2011 21:35:48 -0400 Subject: [Tutor] First Game Attempt In-Reply-To: References: Message-ID: <183529209933.20110418213548@columbus.rr.com> > I was reading Pygame API for a month and made out a very basic ,small game > named as "Hungry Snake" as practice. Not bad! From ranceh at gmail.com Tue Apr 19 03:53:15 2011 From: ranceh at gmail.com (Rance Hall) Date: Mon, 18 Apr 2011 20:53:15 -0500 Subject: [Tutor] working with strings in python3 In-Reply-To: References: Message-ID: On Mon, Apr 18, 2011 at 8:10 PM, Marc Tompkins wrote: > On Mon, Apr 18, 2011 at 5:17 PM, Rance Hall wrote: >> >> Ok so I know what I am doing is deprecated (or at least poor form) but >> the replacement must be awkward cause I'm not getting it. >> >> >> so this is in a cli based program designed to print status messages to >> the terminal on a linux box. >> >> pseudo code: >> >> >> message = "Bah." >> >> if test: >> ? message = message + " Humbug!" >> >> print(message) >> >> end pseudo code >> >> >> I'm sure this is not the way we are supposed to augment strings like this. >> >> maybe there is string.append() method or something I should be using >> instead? >> >> In my case the optional extra parts are always at the end of the >>> >>> current value of the string. >> > > The reason it's deprecated is because it's SLOW - since strings are > immutable, there's a lot of extra copying going on behind the scenes.? If > this code were inside a loop, being run lots and lots of times, this would > quickly become one of the bottlenecks of your program.? However, in the > example you've given, I'm not sure it would make an important difference - > as slow as string concatenation is, it's still a heck of a lot faster than > the human operator! > So you have a CLI based app that asks a question of the user and you are trying to feed the prompt for the input function. I have a mode variable that stores how a function was called so I know the difference between a new entry, and an entry update. An entry update has default values for all the questions. so you might have an example like: message = "Please type the location address line 1." and if the mode was edit you can add message = message + "\nPress Enter to accept the default of " + dbrecord["address1"] then later your code doesn't care it just prints the message variable no matter what it contains. I'm going to go ahead and use this format even though it is deprecated and then later when we upgrade it I can fix it. > If you just want to have a status update for your user - like a progress bar > - you could simply print one string at a time and not store the result. > (i.e. if you just want to display a line of dots to indicate activity, you > don't need to store the full number of dots - just print one at a time - > without newlines - and forget about it.) > > If, on the other hand, you always want to have access to the full string AND > you want to print it along the way, then try a list.? Lists are awesome! > >> message = ['Bah'] # message is a list, which currently contains one item: >> 'Bah' >> for x in range(10): >> ??? message.append(str(x))? # append a string ('0', '1', etc.) to the list >> ??? print " ".join(message)? # print the contents of the list, separated >> by spaces > > That's if you want to do this in a loop.? If you have a set number of items > to display, then string formatting is your friend: > >> message = 'The %s in %s stays mainly in the %s' % ('rain', 'Spain', >> 'plain') > > String formatting doesn't work for me in this case as the message is sort of dynamic. Way too much logic around printing a statement. A list might make sense, but printing a message one word at a time doesn't seem to me like much of a time saver. I totally get the immutable string thing. I can't say that I care one way or the other, mutable or not, each has consequences. But are CLI apps so rare that this sort of thing just doesn't happen anymore? This seems like such a basic thing and deprecating it seems rather harsh. I'm not really trying to start a flame fest, I'm just trying to understand the thought process. I don't see what I would call a legitimate alternative to this type of string usage. Rance From marc.tompkins at gmail.com Tue Apr 19 04:50:02 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Mon, 18 Apr 2011 19:50:02 -0700 Subject: [Tutor] working with strings in python3 In-Reply-To: References: Message-ID: On Mon, Apr 18, 2011 at 6:53 PM, Rance Hall wrote: > I'm going to go ahead and use this format even though it is deprecated > and then later when we upgrade it I can fix it. > > And there you have your answer. A list might make sense, but printing a message one word at a time > doesn't seem to me like much of a time saver. > Did you try my example code? It doesn't "print a message one word at a time"; any time you print " ".join(message), you get the whole thing. Put a \n between the quotes, and you get the whole thing on separate lines. It's just that it's not stored as a single string, but assembled on-demand. And you're right - doing this once or twice, or even ten times as in my example code, doesn't make a huge difference. But at some point, if you intend to continue programming, you will run into a situation where your code needs to do something over and over and over and over... and getting out of bad habits like string concatenation can make a very noticeable difference in speed. > But are CLI apps so rare that this sort of thing just doesn't happen > anymore? No, they're not all that rare, and CLI-ness has nothing to do with it. > This seems like such a basic thing and deprecating it seems > rather harsh. > > Bottom line: Python is not BASIC. In BASIC, strings aren't immutable, so in-place string concatenation doesn't carry (much of) a performance penalty. In Python, it will make your program unnecessarily slow. I think you're under the impression that "deprecation" is a value judgment, or that "message = message + foo" is deprecated because it looks like BASIC syntax. Neither is true. >From the Python wiki: http://wiki.python.org/moin/PythonSpeed/PerformanceTips#String_Concatenation We may ask ourselves "why did Guido decide to make strings immutable in the first place?"; probably the best reason is "so that strings can be used as keys in a dictionary", but since I'm not Guido - not even Dutch! - I really can't speak for him. I'm not really trying to start a flame fest, I'm just trying to > understand the thought process. I don't see what I would call a > legitimate alternative to this type of string usage. > Again, that's because you're holding onto the idea of mutable strings. Accept that they're immutable, but that lists of strings are both mutable and fast, and the difficulties disappear. But also: if you want to use concatenation, knock yourself out! Nobody's going to condemn you for it. Except possibly your users. -------------- next part -------------- An HTML attachment was scrubbed... URL: From gollumgreg407366 at gmail.com Tue Apr 19 06:57:26 2011 From: gollumgreg407366 at gmail.com (Greg Nielsen) Date: Mon, 18 Apr 2011 23:57:26 -0500 Subject: [Tutor] Distutils Font Error Message-ID: Dear Fellow Python Users, I am currently working on a small Python 3.1.3 game on a Windows 7 machine and am attempting to freezing it using Distutils and cx_freeze so I can share it with friends and family. Several attempts in I reached an error that I am unable to fix and was hoping for some advice. The error is as followes. C:\Users\Greg\Documents\NetBeansProjects\Racing1\src\build\exe.win32-3.1>racing1 .exe C:\Users\Greg\Documents\NetBeansProjects\Racing1\src\build\exe.win32-3.1\library .zip\RacingLibrary.py:335: RuntimeWarning: use font: DLL load failed: %1 is not a valid Win32 application. (ImportError: DLL load failed: %1 is not a valid Win32 application.) Traceback (most recent call last): File "C:\Python31\lib\site-packages\cx_Freeze\initscripts\Console3.py", line 2 7, in exec(code, m.__dict__) File "racing1.py", line 81, in File "racing1.py", line 28, in main File "C:\Users\Greg\Documents\NetBeansProjects\Racing1\src\RacingLibrary.py", line 335, in __init__ self.font = pygame.font.Font("freesansbold.ttf", 20) File "C:\Python31\lib\site-packages\pygame\__init__.py", line 70, in __getattr __ raise NotImplementedError(MissingPygameModule) NotImplementedError: font module not available (ImportError: DLL load failed: %1 is not a valid Win32 application.) This error occurs regardless to whether I use a freeware font and save a copy of it in the .exe directory or if I attempt to call SysFont("None") Is it possible that either Distutils or cx_freeze does not support .ttf? It's the best guess I have at the moment. Hopefully someone can shed some light into what is really going on here. Thank you to everyone who takes time to read this and perhaps even respond with a possible solution. Mr. Nielsen -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Tue Apr 19 07:04:00 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Mon, 18 Apr 2011 22:04:00 -0700 Subject: [Tutor] Distutils Font Error In-Reply-To: References: Message-ID: On Mon, Apr 18, 2011 at 9:57 PM, Greg Nielsen wrote: > Dear Fellow Python Users, > > I am currently working on a small Python 3.1.3 game on a Windows 7 > machine and am attempting to freezing it using Distutils and cx_freeze so I > can share it with friends and family. Several attempts in I reached an error > that I am unable to fix and was hoping for some advice. The error is as > followes. > > > C:\Users\Greg\Documents\NetBeansProjects\Racing1\src\build\exe.win32-3.1>racing1 > .exe > > C:\Users\Greg\Documents\NetBeansProjects\Racing1\src\build\exe.win32-3.1\library > .zip\RacingLibrary.py:335: RuntimeWarning: use font: DLL load failed: %1 is > not > a valid Win32 application. > (ImportError: DLL load failed: %1 is not a valid Win32 application.) > Traceback (most recent call last): > File "C:\Python31\lib\site-packages\cx_Freeze\initscripts\Console3.py", > line 2 > 7, in > exec(code, m.__dict__) > File "racing1.py", line 81, in > File "racing1.py", line 28, in main > File > "C:\Users\Greg\Documents\NetBeansProjects\Racing1\src\RacingLibrary.py", > line 335, in __init__ > self.font = pygame.font.Font("freesansbold.ttf", 20) > File "C:\Python31\lib\site-packages\pygame\__init__.py", line 70, in > __getattr > __ > raise NotImplementedError(MissingPygameModule) > NotImplementedError: font module not available > (ImportError: DLL load failed: %1 is not a valid Win32 application.) > > This error occurs regardless to whether I use a freeware font and save a > copy of it in the .exe directory or if I attempt to call SysFont("None") Is > it possible that either Distutils or cx_freeze does not support .ttf? It's > the best guess I have at the moment. Hopefully someone can shed some light > into what is really going on here. Thank you to everyone who takes time to > read this and perhaps even respond with a possible solution. Mr. Nielsen > > It looks like the problem is not with your font, but with the font module - which I presume is an optional part of Pygame? I don't use either Pygame or cx_freeze, so my advice is limited... but that's how I read it. Does cx_freeze give you some way of selecting which modules/submodules will be included? That's where I'd look. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Tue Apr 19 13:41:45 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 19 Apr 2011 21:41:45 +1000 Subject: [Tutor] working with strings in python3 In-Reply-To: References: Message-ID: <4DAD74F9.3050505@pearwood.info> Rance Hall wrote: > Ok so I know what I am doing is deprecated (or at least poor form) but > the replacement must be awkward cause I'm not getting it. [...] > message = "Bah." > if test: > message = message + " Humbug!" It's not deprecated, nor is it poor form. However, it can be abused, or perhaps *misused* is a better term, and it is the misuse you need to watch out for. Somebody posted a similar comment on another Python list today, which I answered, so I'll copy and paste my answer here: There's nothing wrong with concatenating (say) two or three strings. What's a bad idea is something like: s = '' while condition: s += "append stuff to end" Even worse: s = '' while condition: s = "insert stuff at beginning" + s because that defeats the runtime optimization (CPython only!) that *sometimes* can alleviate the badness of repeated string concatenation. See Joel on Software for more: http://www.joelonsoftware.com/articles/fog0000000319.html But a single concatenation is more or less equally efficient as string formatting operations (and probably more efficient, because you don't have the overheard of parsing the format mini-language). For repeated concatenation, the usual idiom is to collect all the substrings in a list, then join them all at once at the end: pieces = [] while condition: pieces.append('append stuff at end') s = ''.join(pieces) -- Steven From vearasilp at gmail.com Tue Apr 19 14:57:17 2011 From: vearasilp at gmail.com (Kann Vearasilp) Date: Tue, 19 Apr 2011 14:57:17 +0200 Subject: [Tutor] Type error: must be string or read-only character buffer, not seq Message-ID: Dear all, I tried concatenating string variables with multiple strings and have the file handle write the statement into a file. I don't know why I always get the type error: must be string or read-only character buffer, not seq error. I tried casting the whole new concatenated string using str(), but was not successful as well. Do you have any clue why this happen? Best, Kann ############################################################# 42 43 statement = 'mirna = miRBase(accession = "' + mir_acc + '", '\ 44 + 'name = "' + mir_name + '", '\ 45 + 'specie = "' + mir_specie + '", '\ 46 + 'description = "' + mir_desc + '", '\ 47 + 'refDBs = "' + mir_dbrefs + '", '\ 48 + 'comment = "' + mir_comment + '", '\ 49 + 'seq = "' + mir_seq + '")' + "\n" 50 51 52 str(statement) 53 insert.write(statement) ############################################################3 processing the insert statment Traceback (most recent call last): File "mirbase.py", line 60, in generate_insert(db_file) File "mirbase.py", line 53, in generate_insert insert.write(statement) TypeError: must be string or read-only character buffer, not Seq ############################################################# -------------- next part -------------- An HTML attachment was scrubbed... URL: From rabidpoobear at gmail.com Tue Apr 19 15:29:47 2011 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 19 Apr 2011 08:29:47 -0500 Subject: [Tutor] Type error: must be string or read-only character buffer, not seq In-Reply-To: References: Message-ID: It's saying one of your variables is not a string. Is one of them a sequence? Perhaps Mir-seq? If so, you need to come up with a way to build a string from this object. You can call the str method and pass in your object or you can explicitly create a string from the data in the object. ----------------------------- Sent from a mobile device. Apologies for brevity and top-posting. ----------------------------- On Apr 19, 2011, at 7:57 AM, Kann Vearasilp wrote: > Dear all, > > I tried concatenating string variables with multiple strings and have the file handle write the statement into a file. I don't know why I always get the type error: must be string or read-only character buffer, not seq error. I tried casting the whole new concatenated string using str(), but was not successful as well. Do you have any clue why this happen? > > Best, > > Kann > > > ############################################################# > 42 > 43 statement = 'mirna = miRBase(accession = "' + mir_acc + '", '\ > 44 + 'name = "' + mir_name + '", '\ > 45 + 'specie = "' + mir_specie + '", '\ > 46 + 'description = "' + mir_desc + '", '\ > 47 + 'refDBs = "' + mir_dbrefs + '", '\ > 48 + 'comment = "' + mir_comment + '", '\ > 49 + 'seq = "' + mir_seq + '")' + "\n" > 50 > 51 > 52 str(statement) > 53 insert.write(statement) > > ############################################################3 > processing the insert statment > Traceback (most recent call last): > File "mirbase.py", line 60, in > generate_insert(db_file) > File "mirbase.py", line 53, in generate_insert > insert.write(statement) > TypeError: must be string or read-only character buffer, not Seq > ############################################################# > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From modulok at gmail.com Tue Apr 19 15:38:26 2011 From: modulok at gmail.com (Modulok) Date: Tue, 19 Apr 2011 07:38:26 -0600 Subject: [Tutor] Metaclass confusion... Message-ID: List, I've been messing with metaclasses. I thought I understood them until I ran into this. (See code below.) I was expecting the generated class, 'Foo' to have an 'x' class-level attribute, as forced upon it by the metaclass 'DracoMeta' at creation. Unfortunately, it doesn't and I don't know why. I'm obviously missing something big. I thought a metaclass created the class object, so this should work. (But obviously doesn't.) class DracoMeta(type): '''Metaclass that creates a serial number as a class property.''' def __init__(self, name, bases, members): # Force a class attribute on the class-to-be: members['serial'] = 3 # Now make the class: type.__init__(self, name, bases, members) class Foo(object): __metaclass__ = DracoMeta print hasattr(Foo, 'serial') #<-- I was really expecting this to be True. I could add the attribute in the definition or a decorator, but the point was learning to use (albeit abuse) metaclasses. Anyway, if anyone could take a look I'd be grateful. Thanks! -Modulok- From ranceh at gmail.com Tue Apr 19 15:44:21 2011 From: ranceh at gmail.com (Rance Hall) Date: Tue, 19 Apr 2011 08:44:21 -0500 Subject: [Tutor] working with strings in python3 In-Reply-To: References: Message-ID: On Mon, Apr 18, 2011 at 9:50 PM, Marc Tompkins wrote: > On Mon, Apr 18, 2011 at 6:53 PM, Rance Hall wrote: > >> >> I'm going to go ahead and use this format even though it is deprecated >> and then later when we upgrade it I can fix it. >> > And there you have your answer. > >> A list might make sense, but printing a message one word at a time >> doesn't seem to me like much of a time saver. > > > Did you try my example code?? It doesn't "print a message one word at a > time"; any time you print " ".join(message), you get the whole thing.? Put a > \n between the quotes, and you get the whole thing on separate lines. > I think you misunderstood me, I simply meant that the print " ".join(message) has to parse through each word in order to get any output, I didn't mean to suggest that you got output one word at a time. Sorry for the confusion. > It's just that it's not stored as a single string, but assembled on-demand. > And you're right - doing this once or twice, or even ten times as in my > example code, doesn't make a huge difference.? But at some point, if you > intend to continue programming, you will run into a situation where your > code needs to do something over and over and over and over... and getting > out of bad habits like string concatenation can make a very noticeable > difference in speed. > >> >> But are CLI apps so rare that this sort of thing just doesn't happen >> anymore? > > No, they're not all that rare, and CLI-ness has nothing to do with it. > >> >> This seems like such a basic thing and deprecating it seems >> rather harsh. >> > Bottom line: Python is not BASIC.? In BASIC, strings aren't immutable, so > in-place string concatenation doesn't carry (much of) a performance > penalty.? In Python, it will make your program unnecessarily slow.? I think > you're under the impression that "deprecation" is a value judgment, or that > "message = message + foo" is deprecated because it looks like BASIC syntax. > Neither is true. > Again a little misunderstanding. I didn't mean BASIC the programming language. I forgot all I knew about that language long ago. I mean basic in the fundamental concept sense. Variables are variable, that's why we call them variable. Constants are constant, and that's why we call them constant. The idea of immutable strings variables blurs the line between these two mathematical concepts which are part of my thinking about teaching math (which I do at a local community college) as well as my thinking of computer programming. > From the Python wiki: > http://wiki.python.org/moin/PythonSpeed/PerformanceTips#String_Concatenation > Thanks for this pointer, it was interesting reading. > We may ask ourselves "why did Guido decide to make strings immutable in the > first place?"; probably the best reason is "so that strings can be used as > keys in a dictionary", but since I'm not Guido - not even Dutch! - I really > can't speak for him. > I'm not sure I buy this explanation as strings have been used as keys in dictionaries or "associative arrays" for a long time, a string variable is variable or mutable, where a keyname can not be. Anyway, thanks everyone for taking the time to help me get my head wrapped around this, I'm not sure I managed to do it yet, but the seeds were planted. Rance From mesrod at juno.com Tue Apr 19 15:49:00 2011 From: mesrod at juno.com (mesrod at juno.com) Date: Tue, 19 Apr 2011 13:49:00 GMT Subject: [Tutor] adding to PYTHONPATH Message-ID: <20110419.074900.2950.0@webmail03.vgs.untd.com> How can I add a directory to PYTHONPATH? Using Ubuntu 10.04. From joel.goldstick at gmail.com Tue Apr 19 16:28:20 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 19 Apr 2011 10:28:20 -0400 Subject: [Tutor] adding to PYTHONPATH In-Reply-To: <20110419.074900.2950.0@webmail03.vgs.untd.com> References: <20110419.074900.2950.0@webmail03.vgs.untd.com> Message-ID: On Tue, Apr 19, 2011 at 9:49 AM, mesrod at juno.com wrote: > How can I add a directory to PYTHONPATH? Using Ubuntu 10.04. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > from the shell type this: export PYTHONPATH=$PYTHONPATH:/your/path/to/python/modules -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Tue Apr 19 16:29:20 2011 From: steve at alchemy.com (Steve Willoughby) Date: Tue, 19 Apr 2011 07:29:20 -0700 Subject: [Tutor] working with strings in python3 In-Reply-To: References: Message-ID: <4DAD9C40.4010707@alchemy.com> On 19-Apr-11 06:44, Rance Hall wrote: > On Mon, Apr 18, 2011 at 9:50 PM, Marc Tompkins wrote: >> On Mon, Apr 18, 2011 at 6:53 PM, Rance Hall wrote: > I think you misunderstood me, I simply meant that the print " > ".join(message) has to parse through each word in order to get any > output, I didn't mean to suggest that you got output one word at a > time. Sorry for the confusion. Not quite true. join() doesn't need to parse through words or anything. It takes a list of strings and efficiently copies them into a new large string. Maybe you're thinking of split() or something? > I'm not sure I buy this explanation as strings have been used as keys > in dictionaries or "associative arrays" for a long time, a string > variable is variable or mutable, where a keyname can not be. You're forgetting that you're not talking about a string VALUE like in most other languages, but rather a string OBJECT. In C, if you store a value in a hash table with a string key, that key doesn't change even if the variable it came from takes a new value. So it doesn't upset the key at all. In Python, the string OBJECT you use may still be referenced by a variable, so if you were to mutate that string object, it would change and ALL variables referring to it would see the change, including the hash table structure which forms the dictionary. In this sense, think of Python variable names more like C's pointers (sort of). It's the same effect you'd get if you kept a pointer (in C) to the string value you stored your data in a hash table there, then went through that pointer to corrupt the hash table after the fact. I'm not sure if your background in programming includes those concepts (I'm assuming so) or if I explained that clearly enough, but that illustrates why Python string OBJECTS need to be immutable (as are simple numeric OBJECTS. The confusion that trips a lot of new Python programmers is that Python variables don't work like other languages, they're more of a blending of "variables", "pointers" and "references" which just "do the right thing" most of the time due to how Python manages variable access. But they are not quite the same as any of those in other languages. -- 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 steve at alchemy.com Tue Apr 19 16:31:10 2011 From: steve at alchemy.com (Steve Willoughby) Date: Tue, 19 Apr 2011 07:31:10 -0700 Subject: [Tutor] adding to PYTHONPATH In-Reply-To: <20110419.074900.2950.0@webmail03.vgs.untd.com> References: <20110419.074900.2950.0@webmail03.vgs.untd.com> Message-ID: <4DAD9CAE.1010703@alchemy.com> On 19-Apr-11 06:49, mesrod at juno.com wrote: > How can I add a directory to PYTHONPATH? Using Ubuntu 10.04. That's an environment variable, so it depends on your shell. If PYTHONPATH already exists, you can add your directory to it (with colons between the names of directories). But you probably want this to be a permanent change, so you need to edit the start-up file for your shell (.cshrc, .bashrc, .profile, whatever) and add an instruction to set that variable everytime you open a shell. -- 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 barthpi at gmail.com Tue Apr 19 16:53:13 2011 From: barthpi at gmail.com (Pierre Barthelemy) Date: Tue, 19 Apr 2011 16:53:13 +0200 Subject: [Tutor] win32com and python Message-ID: Hello, I would need to control a powerpoint file from python. I have installed the win32com library for python, then i used makepy to create a powerpoint-specific library. The things i need to do are pretty basic: open a file, create a new slide, place a picture and a comment to the picture. The problem i have is that, often, while the script is running, the powerpoint file would already be open. In this case, my script would open it anew, and make the modifications in the newly opened file. To prevent that problem, i need to be able to look at the filenames of the open powerpoint files. It there a way to do that ? And, by the way, is there any kind of help or manual or document to understand how to use win32com and the related application-specific libraries ? The code i am using now is the following: [code] import win32com.client import win32com.gen_py.ppt11b as ppt11b ppt = win32com.client.Dispatch("Powerpoint.Application") #Open the powerpoint application ppt.Visible = True pptfile = ppt.Presentations.Open('FileName',ReadOnly=0, Untitled=0, WithWindow=1)#Open the desired ppt file Slide = pptfile.Slides.Add(len(pptfile.Slides)+1, ppLayoutBlank) shape1 = Slide.Shapes.AddTextbox(Orientation=0x1,Left=100,Top=50,Width=400,Height=100) shape1.TextFrame.TextRange.Text='Trial' shape2=Slide.Shapes.AddPicture(FileName='PictureName', LinkToFile=False, SaveWithDocument=True, Left=100, Top=100, Width=400, Height=400) pptfile.Save() pptfile.Close() [\code] From __peter__ at web.de Tue Apr 19 17:25:32 2011 From: __peter__ at web.de (Peter Otten) Date: Tue, 19 Apr 2011 17:25:32 +0200 Subject: [Tutor] Metaclass confusion... References: Message-ID: Modulok wrote: > List, > > I've been messing with metaclasses. I thought I understood them until I > ran into this. (See code below.) I was expecting the generated class, > 'Foo' to have an 'x' class-level attribute, as forced upon it by the > metaclass 'DracoMeta' at creation. Unfortunately, it doesn't and I don't > know why. I'm obviously missing something big. I thought a metaclass > created the class object, so this should work. (But obviously doesn't.) > > > > class DracoMeta(type): > '''Metaclass that creates a serial number as a class property.''' > def __init__(self, name, bases, members): > # Force a class attribute on the class-to-be: > members['serial'] = 3 > > # Now make the class: > type.__init__(self, name, bases, members) > > class Foo(object): > __metaclass__ = DracoMeta > > print hasattr(Foo, 'serial') #<-- I was really expecting this to be > True. > > I could add the attribute in the definition or a decorator, but the point > was learning to use (albeit abuse) metaclasses. Anyway, if anyone could > take a look I'd be grateful. You are a little late to the show; the class, i. e. the instance of the metaclass with all its attributes has already been created by the type.__new__() method. If you move the manipulation of the members dict into a custom __new__() method you get the desired behaviour: >>> class DracoMeta(type): ... def __new__(cls, name, bases, members): ... members["serial"] = 3 ... return type.__new__(cls, name, bases, members) ... >>> class Foo: ... __metaclass__ = DracoMeta ... >>> Foo.serial 3 Alternatively you can take advantage of the fact that 'self' in the metaclass is the metaclass instance, i. e. the class, and assign directly to it: >>> class NianMeta(type): ... def __init__(self, name, bases, members): ... self.serial = 3 ... >>> class Bar: ... __metaclass__ = NianMeta ... >>> Bar.serial 3 From __peter__ at web.de Tue Apr 19 17:29:55 2011 From: __peter__ at web.de (Peter Otten) Date: Tue, 19 Apr 2011 17:29:55 +0200 Subject: [Tutor] Type error: must be string or read-only character buffer, not seq References: Message-ID: Kann Vearasilp wrote: > I tried concatenating string variables with multiple strings and have the > file handle write the statement into a file. I don't know why I always get > the type error: must be string or read-only character buffer, not seq > error. I tried casting the whole new concatenated string using str(), but > was not successful as well. Do you have any clue why this happen? > 52 str(statement) > 53 insert.write(statement) Line 52 doesn't do what you think it does -- it converts statement to a string and then discards the result. Try statement = str(statement) insert.write(statement) or insert.write(str(statement)) instead. From mail at timgolden.me.uk Tue Apr 19 17:51:01 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 19 Apr 2011 16:51:01 +0100 Subject: [Tutor] win32com and python In-Reply-To: References: Message-ID: <4DADAF65.1080106@timgolden.me.uk> On 19/04/2011 15:53, Pierre Barthelemy wrote: > The problem i have is that, often, while the script is running, the > powerpoint file would already be open. In this case, my script would > open it anew, and make the modifications in the newly opened file. > To prevent that problem, i need to be able to look at the filenames of > the open powerpoint files. > It there a way to do that ? See if this might help (mutatis mutandis): http://timgolden.me.uk/python/win32_how_do_i/see-if-an-excel-workbook-is-open.html TJG From vearasilp at gmail.com Tue Apr 19 18:10:59 2011 From: vearasilp at gmail.com (Kann Vearasilp) Date: Tue, 19 Apr 2011 18:10:59 +0200 Subject: [Tutor] Type error: must be string or read-only character buffer, not seq In-Reply-To: References: Message-ID: Thanks Peter, That just fixes my problem. : ) Kann On Tue, Apr 19, 2011 at 5:29 PM, Peter Otten <__peter__ at web.de> wrote: > Kann Vearasilp wrote: > >> I tried concatenating string variables with multiple strings and have the >> file handle write the statement into a file. I don't know why I always get >> the type error: must be string or read-only character buffer, not seq >> error. I tried casting the whole new concatenated string using str(), but >> was not successful as well. Do you have any clue why this happen? > >> ?52 ? ? ? ? str(statement) >> ?53 ? ? ? ? insert.write(statement) > > Line 52 doesn't do what you think it does -- it converts statement to a > string and then discards the result. > > Try > > statement = str(statement) > insert.write(statement) > > or > > insert.write(str(statement)) > > instead. > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From marc.tompkins at gmail.com Tue Apr 19 19:03:10 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 19 Apr 2011 10:03:10 -0700 Subject: [Tutor] Fwd: working with strings in python3 In-Reply-To: References: Message-ID: Forgot to send to group. Grrr. ---------- Forwarded message ---------- From: Marc Tompkins Date: Tue, Apr 19, 2011 at 10:01 AM Subject: Re: [Tutor] working with strings in python3 To: Rance Hall On Tue, Apr 19, 2011 at 6:44 AM, Rance Hall wrote: > > Bottom line: Python is not BASIC. In BASIC, strings aren't immutable, > so in-place string concatenation doesn't carry (much of) a performance > > penalty. In Python, it will make your program unnecessarily slow. I > think you're under the impression that "deprecation" is a value judgment, or > that > > "message = message + foo" is deprecated because it looks like BASIC > syntax. > > Neither is true. > > Again a little misunderstanding. I didn't mean BASIC the programming > language. I forgot all I knew about that language long ago. I mean basic > in the fundamental concept sense. > No, I wasn't conflating 'basic' and BASIC, nor did I think you were - I was just using BASIC as the first example I could think of where "message = message + foo" is the standard way to concatenate strings. You can't do it that way in C or Perl or assembler; it's not recommended in Java for much the same reason as in Python ( http://www.ibm.com/developerworks/websphere/library/bestpractices/string_concatenation.html); I don't remember what I used to do in COBOL; the only example that came to mind was BASIC. Which is a different language from Python, and different rules apply, which was the only point I was trying to make. Variables are variable, that's why we call them variable. > Constants are constant, and that's why we call them constant. > > There's an old programmer's saying: "Constants aren't, and variables don't." More to the point, though, Python was designed from the ground up as an object-oriented language (as opposed to a conventional language with object support bolted on as an afterthought); both constants and variables are actually objects, and act differently than they do in a non-OO language. > We may ask ourselves "why did Guido decide to make strings immutable in > the first place?"; probably the best reason is "so that strings can be used > as keys in a dictionary", but since I'm not Guido - not even Dutch! - I > really can't speak for him. > > I'm not sure I buy this explanation as strings have been used as keys in > dictionaries or "associative arrays" for a long time, a string variable is > variable or mutable, where a keyname can not be. > Reread the two parts of your own sentence - "strings have been used as keys... for a long time" and "a string variable is variable or mutable, where a keyname can not be". It's like a Zen koan. Reconcile those two concepts and I think you will have grasped the Buddha-nature of Python strings. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Tue Apr 19 19:50:56 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 20 Apr 2011 03:50:56 +1000 Subject: [Tutor] working with strings in python3 In-Reply-To: References: Message-ID: <4DADCB80.5040104@pearwood.info> Rance Hall wrote: > On Mon, Apr 18, 2011 at 9:50 PM, Marc Tompkins wrote: >> On Mon, Apr 18, 2011 at 6:53 PM, Rance Hall wrote: >> >>> I'm going to go ahead and use this format even though it is deprecated >>> and then later when we upgrade it I can fix it. >>> >> And there you have your answer. >> >>> A list might make sense, but printing a message one word at a time >>> doesn't seem to me like much of a time saver. >> >> Did you try my example code? It doesn't "print a message one word at a >> time"; any time you print " ".join(message), you get the whole thing. Put a >> \n between the quotes, and you get the whole thing on separate lines. >> > > I think you misunderstood me, I simply meant that the print " > ".join(message) has to parse through each word in order to get any > output, I didn't mean to suggest that you got output one word at a > time. Sorry for the confusion. Well, yes, but you have to walk over each word at some point. The join idiom merely puts that off until just before you need the complete string, instead of walking over them over and over and over again. That's why the join idiom is usually better: it walks over each string once, while repeated concatenation has the potential to walk over each one dozens, hundreds or thousands of times (depending on how many strings you have to concatenate). To be precise: if there are N strings to add, the join idiom does work proportional to N, while the repeated concatenation idiom does work proportional to N*N. This is potentially *so* catastrophic for performance that recent versions of CPython actually go out of its way to protect you from it (other Python, like Jython, IronPython and PyPy might not). But with a little bit of extra work, we can shoot ourselves in the foot and see how bad *repeated* string concatenation can be: >>> from timeit import Timer >>> >>> class Magic: ... def __add__(self, other): ... return other ... >>> m = Magic() >>> strings = ['a']*10000 >>> >>> t1 = Timer('"".join(strings)', 'from __main__ import strings') >>> t2 = Timer('sum(strings, m)', 'from __main__ import strings, m') >>> >>> t1.timeit(1000) # one thousand timing iterations 1.0727810859680176 >>> t2.timeit(1000) 19.48655891418457 In Real Life, the performance hit can be substantial. Some time ago (perhaps a year?) there was a bug report that copying files over the network was *really* slow in Python. By memory, the bug report was that to download a smallish file took Internet Explorer about 0.1 second, the wget utility about the same, and the Python urllib module about TEN MINUTES. To cut a long story short, it turned out that the module in question was doing repeated string concatenation. Most users never noticed the problem because Python now has a special optimization that detects repeated concatenation and does all sorts of funky magic to make it smarter and faster, but for this one user, there was some strange interaction between how Windows manages memory and the Python optimizer, the magic wasn't applied, and consequently the full inefficiency of the algorithm was revealed in all it's horror. Bottom line: unless you have actually timed your code and have hard measurements showing different, you should always expect repeated string concatenation to be slow and the join idiom to be fast. -- Steven From steve at pearwood.info Tue Apr 19 20:24:03 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 20 Apr 2011 04:24:03 +1000 Subject: [Tutor] Variables and constants [was Re: working with strings in python3] In-Reply-To: References: Message-ID: <4DADD343.1000205@pearwood.info> Rance Hall wrote: > Variables are variable, that's why we call them variable. > Constants are constant, and that's why we call them constant. And Python has neither variables nor constants in the sense that (say) Pascal, C or Fortran have, even though we often use the same words. The differences are quite deep, but they're also subtle. In classic programming languages with variables and/or constants, the model is that names like "x" refer to *memory locations*. If the name is a variable, the compiler will allow you to mutate the value stored at that memory location; if the name is a constant, it won't. But once a name "x" is associated with memory location (say) 123456, it can never move. But note that the "variability" or "constantness" is associated with the *name* (the memory location), not the value. In languages like Python, names are associated with values, without reference to memory locations. In this case, the "variability" or "constantness" is associated with the *value*, not the name. Consider x = 42; x = x+1. In Pascal, C or Fortran, this will actually change a block of memory that had the value 42 into 43 instead: The name x points to a memory location with value 42. Leave the name pointing to the same place, but change the value to 43 instead. In Python, the situation is different: The name x points to an object with value 42. Leave the object 42 alone, but change the name x to point to an object with value 43 instead. -- Steven From element.effect at gmail.com Tue Apr 19 20:59:24 2011 From: element.effect at gmail.com (Eric Stevens) Date: Tue, 19 Apr 2011 13:59:24 -0500 Subject: [Tutor] wxPython parent classes Message-ID: I've been noticing that in all the example codes I have seen, when someone creates container, x, inside of a frame or other container class, y, they always seem to create an instance of wx.Panel first and then use that instance as the parent class of container x. I have been just placing 'self' in there, however, letting the class I am creating (whether it be a wx.Frame subclass, wx.ScrolledWindow subclass, etc) be the parent class of any other wx.Window class I instantiate inside that class. Is one way better than the other, and if so, why? Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mark at martialfit.net Tue Apr 19 21:21:00 2011 From: mark at martialfit.net (Mark Weil) Date: Tue, 19 Apr 2011 12:21:00 -0700 Subject: [Tutor] wxPython parent classes In-Reply-To: References: Message-ID: wx.Panel provides better cross-platform reliability, so it's fairly standard practice to go with a Panel in a Frame, and place the buttons, etc. on the panel. On Tue, Apr 19, 2011 at 11:59 AM, Eric Stevens wrote: > I've been noticing that in all the example codes I have seen, when someone > creates container, x, inside of a frame or other container class, y, they > always seem to create an instance of wx.Panel first and then use that > instance as the parent class of container x. I have been just placing 'self' > in there, however, letting the class I am creating (whether it be a wx.Frame > subclass, wx.ScrolledWindow subclass, etc) be the parent class of any other > wx.Window class I instantiate inside that class. Is one way better than the > other, and if so, why? Thanks. > _______________________________________________ > 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 bodsda at googlemail.com Tue Apr 19 21:32:10 2011 From: bodsda at googlemail.com (bodsda at googlemail.com) Date: Tue, 19 Apr 2011 19:32:10 +0000 Subject: [Tutor] Variables and constants [was Re: working with strings inpython3] In-Reply-To: <4DADD343.1000205@pearwood.info> References: <4DADD343.1000205@pearwood.info> Message-ID: <1761408942-1303241529-cardhu_decombobulator_blackberry.rim.net-56243370-@b18.c12.bise7.blackberry> And presumably cleans up the leftover object with the value of 42 when it changes to point at the 43 object? Or does it leave all changes in memory until the program exits? Bodsda. Sorry for top posting, my phone won't let me change it Sent from my BlackBerry? wireless device -----Original Message----- From: Steven D'Aprano Sender: tutor-bounces+bodsda=ubuntu.com at python.org Date: Wed, 20 Apr 2011 04:24:03 To: tutor Subject: [Tutor] Variables and constants [was Re: working with strings in python3] Rance Hall wrote: > Variables are variable, that's why we call them variable. > Constants are constant, and that's why we call them constant. And Python has neither variables nor constants in the sense that (say) Pascal, C or Fortran have, even though we often use the same words. The differences are quite deep, but they're also subtle. In classic programming languages with variables and/or constants, the model is that names like "x" refer to *memory locations*. If the name is a variable, the compiler will allow you to mutate the value stored at that memory location; if the name is a constant, it won't. But once a name "x" is associated with memory location (say) 123456, it can never move. But note that the "variability" or "constantness" is associated with the *name* (the memory location), not the value. In languages like Python, names are associated with values, without reference to memory locations. In this case, the "variability" or "constantness" is associated with the *value*, not the name. Consider x = 42; x = x+1. In Pascal, C or Fortran, this will actually change a block of memory that had the value 42 into 43 instead: The name x points to a memory location with value 42. Leave the name pointing to the same place, but change the value to 43 instead. In Python, the situation is different: The name x points to an object with value 42. Leave the object 42 alone, but change the name x to point to an object with value 43 instead. -- Steven _______________________________________________ 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 Tue Apr 19 23:37:08 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 19 Apr 2011 17:37:08 -0400 Subject: [Tutor] Variables and constants [was Re: working with strings inpython3] In-Reply-To: <1761408942-1303241529-cardhu_decombobulator_blackberry.rim.net-56243370-@b18.c12.bise7.blackberry> References: <4DADD343.1000205@pearwood.info> <1761408942-1303241529-cardhu_decombobulator_blackberry.rim.net-56243370-@b18.c12.bise7.blackberry> Message-ID: On Tue, Apr 19, 2011 at 3:32 PM, wrote: > And presumably cleans up the leftover object with the value of 42 when it > changes to point at the 43 object? > > Or does it leave all changes in memory until the program exits? > > Bodsda. > Sorry for top posting, my phone won't let me change it > Sent from my BlackBerry? wireless device > > -----Original Message----- > From: Steven D'Aprano > Sender: tutor-bounces+bodsda=ubuntu.com at python.org > Date: Wed, 20 Apr 2011 04:24:03 > To: tutor > Subject: [Tutor] Variables and constants [was Re: working with strings in > python3] > > Rance Hall wrote: > > > Variables are variable, that's why we call them variable. > > Constants are constant, and that's why we call them constant. > > And Python has neither variables nor constants in the sense that (say) > Pascal, C or Fortran have, even though we often use the same words. > > The differences are quite deep, but they're also subtle. > > In classic programming languages with variables and/or constants, the > model is that names like "x" refer to *memory locations*. If the name is > a variable, the compiler will allow you to mutate the value stored at > that memory location; if the name is a constant, it won't. But once a > name "x" is associated with memory location (say) 123456, it can never > move. But note that the "variability" or "constantness" is associated > with the *name* (the memory location), not the value. > > In languages like Python, names are associated with values, without > reference to memory locations. In this case, the "variability" or > "constantness" is associated with the *value*, not the name. > > Consider x = 42; x = x+1. In Pascal, C or Fortran, this will actually > change a block of memory that had the value 42 into 43 instead: > > The name x points to a memory location with value 42. > Leave the name pointing to the same place, but change the value to 43 > instead. > > In Python, the situation is different: > > The name x points to an object with value 42. > Leave the object 42 alone, but change the name x to point to an object > with value 43 instead. > > > > -- > 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 > If a value has no name bound to it, python figures that out and destroys it -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Apr 19 23:47:07 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 19 Apr 2011 22:47:07 +0100 Subject: [Tutor] working with strings in python3 References: Message-ID: "Rance Hall" wrote > Ok so I know what I am doing is deprecated I'm not aware of string concatenation being deprecated. Ols string formatting is deprecated in the sense that the new string format() method will replace it, but I don't even expect to see that any time soon - too much old code uses formatting. > the replacement must be awkward cause I'm not getting it. There is no replacement but there are alternatives. But the choice of when to use concatenation or when to use the other methods is usually a matter of style and, occasionally, of performance > message = "Bah." > > if test: > message = message + " Humbug!" Apart from maybe using += instead of + I see nothing wrong with this usage. > print(message) Although you could have missed it out and gone straight to: print(message,'Humbug!') Since print will concatenate it's output for you. > I'm sure this is not the way we are supposed to augment strings like > this. It works fine for me, and I don't recall seeing anything saying not to do it. It carries a small performance and memory overhead but thats only a problem in a tight or long loop or if dealing with enormous strings (say megabyte size) > maybe there is string.append() method or something I should be using > instead? You can use the join method of lists which is faster but less obvious: " ".join([message,'Humbug!"]) Or you can use string formatting "{1}{2}".format(message,"Humbug!") I'm not sure how the format() method compares to join for speed, the old style formatting seemed about equivalent in my highly unscientific testing...I haven't tried the new style - I don;t care that much!. > In my case the optional extra parts are always at the end of the > current value of the string. If you only do that operation "occasionally" then using '+' is OK. Don't get overly anxious. Readability counts too. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From marc.tompkins at gmail.com Tue Apr 19 23:55:33 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 19 Apr 2011 14:55:33 -0700 Subject: [Tutor] Variables and constants [was Re: working with strings inpython3] In-Reply-To: References: <4DADD343.1000205@pearwood.info> <1761408942-1303241529-cardhu_decombobulator_blackberry.rim.net-56243370-@b18.c12.bise7.blackberry> Message-ID: On Tue, Apr 19, 2011 at 2:37 PM, Joel Goldstick wrote: > > On Tue, Apr 19, 2011 at 3:32 PM, wrote: > >> And presumably cleans up the leftover object with the value of 42 when it >> changes to point at the 43 object? >> >> Or does it leave all changes in memory until the program exits? >> > > If a value has no name bound to it, python figures that out and destroys it > This is called "garbage collection" - one of those terms you may hear in the background for ages before you realize what it refers to. Automatic memory allocation / garbage collection are among the greatest productivity advantages in using languages like Python; your code probably won't be as efficient as if you'd painstakingly written all the malloc()'s and free()'s yourself, but you'll save many hours of drudgery - and far more importantly, many many hours of debugging to find the places where you forgot something. The other advantage, of course, is that Python is awesome. But you knew that already. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Apr 20 00:00:44 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 19 Apr 2011 23:00:44 +0100 Subject: [Tutor] working with strings in python3 References: Message-ID: "Rance Hall" wrote > String formatting doesn't work for me in this case > as the message is sort of dynamic. I don;t understand that, string formatting is probably the most dynamic way of constructing strings there is, its designed for dynamic data! If your data is really dynamic the only two ways that make sense are joining lists or using format strings. The latter combines dynamic with output control too. > Way too much logic around printing a statement. I don;t see how format strings can be a problem combined with complex logic, string contatenation would be much more complex to deal with. > A list might make sense, but printing a message > one word at a time ... The list doesn't need to contaain single words - unless that is really how dynamic your output is - but even then it will be faster than string concatenation - more typically the list will contain sentence fragments You can even use indirection for more dynamic use cases: # assume gender and hour are dynamically input # or calculated elsewhere stringList = ["Good", "Morning", "Afternoon","Evening", "Night","Sir","Madam"] fields = [] if 6 < hour < 12: fields.append(1) elif 12 <= hours < 18: fields.append(2) elif 18 <= hours <=23 fields.append(3) else: fields.append(4) if gender == "Male": fields.append(5) else: fields.append(6) print( " ".join([stringList[n] for n in fields]) ) > But are CLI apps so rare that this sort of thing just doesn't happen > anymore? This seems like such a basic thing and deprecating it > seems > rather harsh. They aren't rare and concatenation isn't deprecated, but there are other alternatives that may be more suitable depending on your usage. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Apr 20 00:19:04 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 19 Apr 2011 23:19:04 +0100 Subject: [Tutor] working with strings in python3 References: Message-ID: "Rance Hall" wrote > Variables are variable, that's why we call them variable. Yes, but Programming variables(*) are variable in the sense that they can represent different values over time. That is not the same as requiring the values themselves to change. > The idea of immutable strings variables blurs the > line between these two mathematical concepts Not at all. In math you can have a variable reference the number 42. Later the same variable may represent a different number, 66 say. But 66 and 42 are different, immutable numbers. It is no different with strings in Python. A variable can refer to 'foo'; at one point and 'bar' at another. But 'foo' and 'bar' (and indeed 'foobar') are different values just as 42, 66 and 108 are different numbers. Python strings act like numbers in that regard. > variable is variable or mutable, where a keyname can not be. variables are always variable but only some values are mutable You are conflating variables and values. Strings are values (or objects if you prefer) and (arbitrarily) chosen to be immutable by Guido. Variables are associated with values and the values with which they are associated can, and do, change. (*)Note that variables in programming are treated differently from traditional math variables in that math variables are usually considered as symbols for a constant, unchanging value. It is unusual in math to say Let x = 42 .... stuff .... Let x = 66 We would introduce a new variable for the new value. But that idiom is very common in programming generally. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Apr 20 00:27:30 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 19 Apr 2011 23:27:30 +0100 Subject: [Tutor] wxPython parent classes References: Message-ID: "Eric Stevens" wrote > I've been noticing that in all the example codes I have seen, when > someone > creates container, x, inside of a frame or other container class, > y, they > always seem to create an instance of wx.Panel first You got an answer this time, but you will probably get better results posting wxPython questions on the wxPython mailing list/forums. Posting here is more a matter of luck if anyone reading happens to use wx... Alan G. From steve at pearwood.info Wed Apr 20 00:24:08 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 20 Apr 2011 08:24:08 +1000 Subject: [Tutor] Variables and constants [was Re: working with strings inpython3] In-Reply-To: References: <4DADD343.1000205@pearwood.info> <1761408942-1303241529-cardhu_decombobulator_blackberry.rim.net-56243370-@b18.c12.bise7.blackberry> Message-ID: <4DAE0B88.2060001@pearwood.info> Joel Goldstick wrote: > If a value has no name bound to it, python figures that out and destroys it Not quite... if there is no name, or any other reference, then the garbage collector will destroy it. But it doesn't have to be a name: anonymous objects can live inside lists, or dicts, or sets, or as values in functions, etc. -- Steven From steve at pearwood.info Wed Apr 20 00:30:09 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 20 Apr 2011 08:30:09 +1000 Subject: [Tutor] Variables and constants [was Re: working with strings inpython3] In-Reply-To: <1761408942-1303241529-cardhu_decombobulator_blackberry.rim.net-56243370-@b18.c12.bise7.blackberry> References: <4DADD343.1000205@pearwood.info> <1761408942-1303241529-cardhu_decombobulator_blackberry.rim.net-56243370-@b18.c12.bise7.blackberry> Message-ID: <4DAE0CF1.4010000@pearwood.info> bodsda at googlemail.com wrote: > And presumably cleans up the leftover object with the value of 42 when it changes to point at the 43 object? In principle, yes, the garbage collector will destroy the no-longer used object 42 once nothing is pointing to it any more. But in practice, Python caches "small integers", where the definition of small depends on which version of Python you are using, on the basis that it's better to hang onto them in a cache for re-use than to keep making and destroying them over and over again. This is a classic "time versus space" trade-off: using extra memory to save time. -- Steven From modulok at gmail.com Wed Apr 20 13:08:55 2011 From: modulok at gmail.com (Modulok) Date: Wed, 20 Apr 2011 05:08:55 -0600 Subject: [Tutor] Metaclass confusion... In-Reply-To: References: Message-ID: Peter, >> ... the class, i. e. the instance of the metaclass with all its attributes >> has already been created by the type.__new__() method. If you move the >> manipulation of the members dict into a custom __new__() method you get >> the desired behaviour... Thank you! You've solved my problem and broadened my understanding :) Excellent examples as well. Love the class name too. -Modulok- From james at jamesthornton.com Wed Apr 20 20:47:15 2011 From: james at jamesthornton.com (James Thornton) Date: Wed, 20 Apr 2011 13:47:15 -0500 Subject: [Tutor] NLP In-Reply-To: References: Message-ID: http://scikit-learn.sourceforge.net/ On Fri, Apr 8, 2011 at 6:52 AM, Ranjith Kumar wrote: > Hi all, > ?? ?Can anyone suggest me any best Natural Language Processing in > python?other than nltk. > -- > Cheers, > Ranjith Kumar K, > Chennai. > http://ranjithtenz.wordpress.com > > > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Latest Blog: http://jamesthornton.com/blog/how-to-get-to-genius From ron.reiter at gmail.com Wed Apr 20 20:16:16 2011 From: ron.reiter at gmail.com (Ron Reiter) Date: Wed, 20 Apr 2011 21:16:16 +0300 Subject: [Tutor] learnpython.org - Free Interactive Python Tutorial Message-ID: Hey. I've created a website for learning Python interactively online. Check it out, and I would really appreciate it if you can also contribute tutorials. Thanks! -- -- Ron -------------- next part -------------- An HTML attachment was scrubbed... URL: From jenia2009 at yahoo.com Thu Apr 21 01:35:43 2011 From: jenia2009 at yahoo.com (ivlev jenia) Date: Wed, 20 Apr 2011 16:35:43 -0700 (PDT) Subject: [Tutor] jenia. cannot install mysqldb Message-ID: <609686.26815.qm@web126013.mail.ne1.yahoo.com> Hello: I cannot get the mysqldb library to work. I'm trying to setup a Django project on Windows 7 using pydev in eclipse. There are the files I'm using: http://sourceforge.net/projects/mysql-python/ Now, for the life of me, I cannot get the mysqldb library to work. When I try to run the setup file, after the install windows tells me that there was a problem during install. I pointed the eclipse project to the mysqldb directory with all the setup.exe and all the other files. Of course it did not help. Can someone please help me? Thank you for your time and kind concern. Jenia -------------- next part -------------- An HTML attachment was scrubbed... URL: From prologic at shortcircuit.net.au Thu Apr 21 02:22:08 2011 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 21 Apr 2011 10:22:08 +1000 Subject: [Tutor] jenia. cannot install mysqldb In-Reply-To: <609686.26815.qm@web126013.mail.ne1.yahoo.com> References: <609686.26815.qm@web126013.mail.ne1.yahoo.com> Message-ID: On Thu, Apr 21, 2011 at 9:35 AM, ivlev jenia wrote: > I cannot get the mysqldb library to work. > I'm trying to setup a Django project on Windows 7 using pydev in eclipse. > There are the files I'm using: http://sourceforge.net/projects/mysql-python/ > > Now, for the life of me, I cannot get the mysqldb library to work. > When I try to run the setup file, after the install windows tells me that > there was a problem during install. > I pointed the eclipse project to the mysqldb directory with all the > setup.exe and all the other files. > Of course it did not help. > Can someone please help me? Forgive my lack of experience with WIndows in general; However you'll likely need the MySQL C libraries and a compiler of some kind (Visual Studio / C++ ?) in order to install mysql-python from source... You're probably better off finding a pre-built binary distribution (or a pure python lirbary). Either way, you'll need MySQL install (at the very least mysqlxx.dll or something) cheers James -- -- James Mills -- -- "Problems are solved by method" From tcl76 at hotmail.com Thu Apr 21 03:20:42 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Thu, 21 Apr 2011 01:20:42 +0000 Subject: [Tutor] learnpython.org - Free Interactive Python Tutorial In-Reply-To: References: Message-ID: hi Ron, this is great for beginners like me. Could you pls provide the link. tq Date: Wed, 20 Apr 2011 21:16:16 +0300 From: ron.reiter at gmail.com To: tutor at python.org Subject: [Tutor] learnpython.org - Free Interactive Python Tutorial Hey. I've created a website for learning Python interactively online. Check it out, and I would really appreciate it if you can also contribute tutorials. Thanks! -- -- Ron _______________________________________________ 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 achompas at gmail.com Thu Apr 21 05:21:12 2011 From: achompas at gmail.com (Alex Companioni) Date: Wed, 20 Apr 2011 23:21:12 -0400 Subject: [Tutor] list.__init__ within class definition Message-ID: <1303356072.24819.7.camel@Chompbuntu> Hey there, In the following class definition: class Tomato(list): def __init__(self, data): list.__init__(self, data) The list.__init__ method (if it is a method, I'm not clear on what __init__ actually *is*) creates a list, right? In other words, l = Tomato([1,2,3]) will create a list l with the values [1,2,3], correct? Thanks, Alex From prologic at shortcircuit.net.au Thu Apr 21 05:34:07 2011 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 21 Apr 2011 13:34:07 +1000 Subject: [Tutor] list.__init__ within class definition In-Reply-To: <1303356072.24819.7.camel@Chompbuntu> References: <1303356072.24819.7.camel@Chompbuntu> Message-ID: On Thu, Apr 21, 2011 at 1:21 PM, Alex Companioni wrote: > In the following class definition: > > class Tomato(list): > ? ?def __init__(self, data): > ? ? ? ?list.__init__(self, data) > > The list.__init__ method (if it is a method, I'm not clear on what > __init__ actually *is*) creates a list, right? In other words, > > l = Tomato([1,2,3]) > > will create a list l with the values [1,2,3], correct? What you actually want is this: >>> class Tomato(list): ... def __init__(self, data): ... super(Tomato, self).__init__(data) ... >>> l = Tomato([1, 2, 3]) >>> l [1, 2, 3] >>> Your example: >>> class Tomato(list): ... def __init__(self, data): ... list.__init__(data) ... >>> l = Tomato([1, 2, 3]) >>> l [] >>> Do you see why ? cheers James -- -- James Mills -- -- "Problems are solved by method" From jigenbakuda at yahoo.com Thu Apr 21 06:38:19 2011 From: jigenbakuda at yahoo.com (michael scott) Date: Wed, 20 Apr 2011 21:38:19 -0700 (PDT) Subject: [Tutor] python timers Message-ID: <566099.78584.qm@web130221.mail.mud.yahoo.com> Hello how do you do. Today's question has to do with the time module. I want to add a timer to my gui. As I was messing around with it I found a way to measure time... but I'm positive there is a more elegant way to deal with this than what I've thrown together. def thing(): start = time.time() while 1: now = time.time() if now == start + 10.0: print "times up" How are timers usually implemented? By the way, I'm not really asking as much about the how (because I could throw something together that will serve my purpose), I'm asking more about conventions, like is there a standard way people implement timers, like does python come with one built in? Does every programmer who wants a timer write a different one? ---- What is it about you... that intrigues me so? -------------- next part -------------- An HTML attachment was scrubbed... URL: From jenia2009 at yahoo.com Thu Apr 21 02:29:46 2011 From: jenia2009 at yahoo.com (ivlev jenia) Date: Wed, 20 Apr 2011 17:29:46 -0700 (PDT) Subject: [Tutor] jenia. cannot install mysqldb Message-ID: <875723.17507.qm@web126015.mail.ne1.yahoo.com> Hello. I finally was able to install mysqldb, the python library to interact with mysql database. I'm trying to run the "python manage.py sql hello" command where polls is the name of my application. I'm getting this error: _mysql_exceptions.OperationalError: (1049, "Unknown database 'c:\\wamp\\www\\helloworld5\\hello\\mysql.db'") Here is the setting.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'mysql.db', # Or path to database file if using sqlite3. 'USER': 'root', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '127.0.0.1', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '3306', # Set to empty string for default. Not used with sqlite3. } } Thank you for your time and kind concern. Jenia -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Apr 21 09:55:06 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 21 Apr 2011 08:55:06 +0100 Subject: [Tutor] python timers References: <566099.78584.qm@web130221.mail.mud.yahoo.com> Message-ID: "michael scott" wrote > As I was messing around with it I found a way to measure time... but > I'm > positive there is a more elegant way to deal with this than what > I've thrown > together. > > def thing(): > start = time.time() > while 1: > now = time.time() > if now == start + 10.0: > print "times up" I'd probably add a sleep() in there just to avoid too many unnecesary operations burning the CPU. But othewise its a valid approach. > How are timers usually implemented? It depends on what you are doing, there are lots of options and no single answer. Sometimes something similar to your solution is the best fit. A simple pause is usually done with a sleep(). Sometimes the timer will be done in a thread - so the app can keep on working on other things. If you are doing a GUI there will usually be a timer mechanism built into the GUI. Networking often uses select() to implement a timer type function. It just depends what you are trying to do. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Apr 21 10:02:27 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 21 Apr 2011 09:02:27 +0100 Subject: [Tutor] list.__init__ within class definition References: <1303356072.24819.7.camel@Chompbuntu> Message-ID: "James Mills" wrote > What you actually want is this: > >>>> class Tomato(list): > ... def __init__(self, data): > ... super(Tomato, self).__init__(data) > ... >>>> l = Tomato([1, 2, 3]) >>>> l > [1, 2, 3] > Your example: > >>>> class Tomato(list): > ... def __init__(self, data): > ... list.__init__(data) > ... >>>> l = Tomato([1, 2, 3]) >>>> l > [] >>>> > > Do you see why ? This confuses things (at least for me!) It has nothing to do with the use of super() but all to do with the use of self. The OPs style works fuine with self: >>> class Tomato(list): ... def __init__(self,data): ... list.__init__(self,data) ... >>> t = Tomato([1,2,3]) >>> t [1, 2, 3] >>> Using super may be the prefered way of calling the superclass but its not the reason the OP code didn't work. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From raulcumplido at gmail.com Thu Apr 21 10:24:42 2011 From: raulcumplido at gmail.com (=?ISO-8859-1?Q?Ra=FAl_Cumplido?=) Date: Thu, 21 Apr 2011 10:24:42 +0200 Subject: [Tutor] jenia. cannot install mysqldb In-Reply-To: <875723.17507.qm@web126015.mail.ne1.yahoo.com> References: <875723.17507.qm@web126015.mail.ne1.yahoo.com> Message-ID: Maybe that's a stupid question but, have you tried to connect directly to your MySQL database without the django app? I mean using a MySQL admin or something. Have you created the mysql.db schema? The erros says clearly it doesn't knows the database your trying to connect. Is your root user ok? I mean credentials (no password??) ... Ra?l On Thu, Apr 21, 2011 at 2:29 AM, ivlev jenia wrote: > Hello. > > I finally was able to install mysqldb, the python library to interact with > mysql database. > > I'm trying to run the "python manage.py sql hello" command where polls is > the name of my application. > > I'm getting this error: > _mysql_exceptions.OperationalError: (1049, "Unknown database > 'c:\\wamp\\www\\helloworld5\\hello\\mysql.db'") > > > Here is the setting.py: > > DATABASES = { > 'default': { > 'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', > 'postgresql', 'mysql', 'sqlite3' or 'oracle'. > 'NAME': 'mysql.db', # Or path to database file > if using sqlite3. > 'USER': 'root', # Not used with sqlite3. > 'PASSWORD': '', # Not used with sqlite3. > 'HOST': '127.0.0.1', # Set to empty string for > localhost. Not used with sqlite3. > 'PORT': '3306', # Set to empty string for > default. Not used with sqlite3. > > } > } > > > Thank you for your time and kind concern. > Jenia > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Ra?l Cumplido -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Apr 21 10:50:05 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 21 Apr 2011 09:50:05 +0100 Subject: [Tutor] list.__init__ within class definition References: <1303356072.24819.7.camel@Chompbuntu> Message-ID: "Alex Companioni" wrote > > class Tomato(list): > def __init__(self, data): > list.__init__(self, data) > > The list.__init__ method (if it is a method, I'm not clear on what > __init__ actually *is*) creates a list, right? Not quite. __init__ (which is a method) is an initialiser not a constructor(*). The list is already created when you call init(). (Thats done by the __new__() class method) > l = Tomato([1,2,3]) > > will create a list l with the values [1,2,3], correct? Correct. But the creation of the list is done in the superclass __new__() not in the init. The assignment of the data to the list is done by __init__() (*)Although init is not really a construxctir it is usually treated as one and often referred to as such by Python programmers. Indeed I do the same in my tutorial. But technically new() constructs the class, init initialises it. HTH -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Apr 21 10:56:56 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 21 Apr 2011 09:56:56 +0100 Subject: [Tutor] jenia. cannot install mysqldb References: <875723.17507.qm@web126015.mail.ne1.yahoo.com> Message-ID: "ivlev jenia" wrote > I'm trying to run the "python manage.py sql hello" command where > polls is the > name of my application. > > I'm getting this error: > _mysql_exceptions.OperationalError: (1049, "Unknown database > 'c:\\wamp\\www\\helloworld5\\hello\\mysql.db'") Whilst there are Django and MySql users on this list it is really supposed to be about learning the Python language. You will likely get better responses to your questions on a dedicated Django or MySql forum/list. Alan G. From mast.ratna at gmail.com Thu Apr 21 13:49:02 2011 From: mast.ratna at gmail.com (Ratna Banjara) Date: Thu, 21 Apr 2011 17:34:02 +0545 Subject: [Tutor] Jokes on Python Language Message-ID: Hello all, Does anybody knows jokes related to Python Language? If the answer is yes, please do share it... -- Regards, Ratna P Banjara www.rat32.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Thu Apr 21 13:55:45 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 21 Apr 2011 13:55:45 +0200 Subject: [Tutor] Jokes on Python Language In-Reply-To: References: Message-ID: Ratna Banjara, 21.04.2011 13:49: > Does anybody knows jokes related to Python Language? > If the answer is yes, please do share it... http://www.python.org/doc/humor/ Stefan From werner.greg at gmail.com Thu Apr 21 16:23:51 2011 From: werner.greg at gmail.com (Greg Werner) Date: Thu, 21 Apr 2011 09:23:51 -0500 Subject: [Tutor] learnpython.org - Free Interactive Python Tutorial In-Reply-To: References: Message-ID: <8BCDBF10-8BE4-44EC-AE69-D363C483B2C9@gmail.com> Hi Ron may you share the link? I have been using another fun one: www.pyschools.com, although I would love to have another option. Greg On 20/04/2011, at 20:20, tee chwee liong wrote: > hi Ron, > > this is great for beginners like me. Could you pls provide the link. tq > > Date: Wed, 20 Apr 2011 21:16:16 +0300 > From: ron.reiter at gmail.com > To: tutor at python.org > Subject: [Tutor] learnpython.org - Free Interactive Python Tutorial > > Hey. > > I've created a website for learning Python interactively online. Check it out, and I would really appreciate it if you can also contribute tutorials. > > Thanks! > > -- > -- Ron > > _______________________________________________ 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 From swiftone at swiftone.org Thu Apr 21 17:05:55 2011 From: swiftone at swiftone.org (Brett Ritter) Date: Thu, 21 Apr 2011 11:05:55 -0400 Subject: [Tutor] learnpython.org - Free Interactive Python Tutorial In-Reply-To: <8BCDBF10-8BE4-44EC-AE69-D363C483B2C9@gmail.com> References: <8BCDBF10-8BE4-44EC-AE69-D363C483B2C9@gmail.com> Message-ID: On Thu, Apr 21, 2011 at 10:23 AM, Greg Werner wrote: > Hi Ron may you share the link? I have been using another fun one: www.pyschools.com, although I would love to have another option. On 20/04/2011, at 20:20, tee chwee liong wrote: > this is great for beginners like me. Could you pls provide the link. tq To all: The link is in the subject line: http://learnpython.org -- Brett Ritter / SwiftOne swiftone at swiftone.org From marc.tompkins at gmail.com Thu Apr 21 18:36:03 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Thu, 21 Apr 2011 09:36:03 -0700 Subject: [Tutor] Jokes on Python Language In-Reply-To: References: Message-ID: On Thu, Apr 21, 2011 at 4:49 AM, Ratna Banjara wrote: > Hello all, > > Does anybody knows jokes related to Python Language? > If the answer is yes, please do share it... > > It's not exactly a joke, but what you'll see if you accidentally go to python.com instead of python.org is... funny. -------------- next part -------------- An HTML attachment was scrubbed... URL: From avifancy at gmail.com Thu Apr 21 19:39:33 2011 From: avifancy at gmail.com (ifancy) Date: Thu, 21 Apr 2011 17:39:33 +0000 (UTC) Subject: [Tutor] Plotting a Linear Equation References: <4C9C1239.5090509@aim.com> Message-ID: I want to use matplotlib (or similar) to plot an equation in (y=mx+b) or standard form (Ax + By = C). I could make two points out of those manually, but I was wondering if anyone knew of an easier way. Thanks. From __peter__ at web.de Thu Apr 21 20:27:39 2011 From: __peter__ at web.de (Peter Otten) Date: Thu, 21 Apr 2011 20:27:39 +0200 Subject: [Tutor] Jokes on Python Language References: Message-ID: Ratna Banjara wrote: > Does anybody knows jokes related to Python Language? > If the answer is yes, please do share it... import antigravity http://entrian.com/goto/ From woiski at gmail.com Thu Apr 21 21:24:00 2011 From: woiski at gmail.com (Emanuel Woiski) Date: Thu, 21 Apr 2011 16:24:00 -0300 Subject: [Tutor] Plotting a Linear Equation In-Reply-To: References: <4C9C1239.5090509@aim.com> Message-ID: easy: import pylab as pl import numpy as np x1,x2,n,m,b = 0.,10.,11,2.,5. x = np.r_[x1:x2:n*1j] pl.plot(x,m*x + b); pl.grid(); pl.show() regards woiski 2011/4/21 ifancy > I want to use matplotlib (or similar) to plot an equation in > (y=mx+b) or standard form (Ax + By = C). I could make > two points out of those manually, but I was wondering if anyone knew of > an easier way. Thanks. > > > > > _______________________________________________ > 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 marc.tompkins at gmail.com Thu Apr 21 22:35:38 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Thu, 21 Apr 2011 13:35:38 -0700 Subject: [Tutor] Jokes on Python Language In-Reply-To: References: Message-ID: On Thu, Apr 21, 2011 at 4:49 AM, Ratna Banjara wrote: > Hello all, > > Does anybody knows jokes related to Python Language? > If the answer is yes, please do share it... > Of course, there's the AWESOME webcomic xkcd (www.xkcd.com) which is excellent reading even when he's not talking about Python... but in particular, there are several great strips about Python itself (or at least, they mention Python in a fond way): http://xkcd.com/353/ http://xkcd.com/413/ http://xkcd.com/409/ http://xkcd.com/521/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From ron.reiter at gmail.com Thu Apr 21 19:22:39 2011 From: ron.reiter at gmail.com (Ron Reiter) Date: Thu, 21 Apr 2011 20:22:39 +0300 Subject: [Tutor] learnpython.org - Free Interactive Python Tutorial In-Reply-To: References: Message-ID: For those of you who didn't notice the title, here is the link: www.learnpython.org Also, please note that there is still not enough content to actually learn from the website yet. I am hoping people will help me with writing tutorials so the site will be useful as soon as possible. On Wed, Apr 20, 2011 at 9:16 PM, Ron Reiter wrote: > Hey. > > I've created a website for learning Python interactively online. Check it > out, and I would really appreciate it if you can also contribute tutorials. > > Thanks! > > -- > -- Ron > -- -- Ron -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Apr 21 23:40:51 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 21 Apr 2011 22:40:51 +0100 Subject: [Tutor] Plotting a Linear Equation References: <4C9C1239.5090509@aim.com> Message-ID: "Emanuel Woiski" wrote > easy: I love your sense of humour! > import pylab as pl > import numpy as np > x1,x2,n,m,b = 0.,10.,11,2.,5. > x = np.r_[x1:x2:n*1j] > pl.plot(x,m*x + b); pl.grid(); pl.show() Now, given this is a list for beginners to Python, could you try explaining what you did there and how the OP, or anyone else for that matter, might use it? Or were you really just trying to establish that if you try hard you can write Python that is as difficult to read as Perl? >> I want to use matplotlib (or similar) to plot an equation in >> (y=mx+b) or standard form (Ax + By = C). I could make >> two points out of those manually, but I was wondering if anyone >> knew of >> an easier way. Thanks. Alan G. From lea-parker at bigpond.com Fri Apr 22 08:59:18 2011 From: lea-parker at bigpond.com (Lea Parker) Date: Fri, 22 Apr 2011 16:59:18 +1000 Subject: [Tutor] return values function Message-ID: <000301cc00ba$ccffb950$66ff2bf0$@bigpond.com> Hello I am hoping someone can put me on the right track. The code below includes the assignment question at the beginning. I seem to have been able to calculate average ok, but what I can't seem to do is sort it so it will return a grade for each result. Can you give me some advice to head me in the right direction please. My code is: """Write a program that asks the user to enter 5 sets tests scores. The program should then display the 'letter grade' (A, B, C, D, F) for each test score, and the overall average test schore. Write the following functions in the program: * Calc_average: This function should take five test scores as parameters, and return the average score. *determine_grade; this function should take a single test score as a parameter, and return a letter grade for the test. The letter grade should be on the following grade scale: 90-100: A, 80-89: B, 70-79: C, 60-69: D, <60: F.""" def main(): #Get users first test result test1 = int(raw_input('Enter the score for test 1: ')) #Get users second test result test2 = int(raw_input('Enter the score for test 2: ')) #Get users third test result test3 = int(raw_input('Enter the score for test 3: ')) #Get users forth test result test4 = int(raw_input('Enter the score for test 4: ')) #Get users fifth test result test5 = int(raw_input('Enter the score for test 5: ')) #Get the sum of the test results cal_average = sum(test1, test2, test3, test4, test5)/5 #Display the total of tests print 'Together your tests average is: ', cal_average print 'Your grade is: ', grade # The sum function to total all tests def sum(test1, test2, test3, test4, test5): result = test1 + test2 + test3 + test4 + test5 return result def determine_grade(score): #Determine the grade for each score if score <101 and score >89: score = A elif score <90 and score >79: score = B elif score <80 and score >69: score = C elif score <70 and score >59: score = D else: score = F return score # Call the main function main() -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Apr 22 09:32:04 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 22 Apr 2011 08:32:04 +0100 Subject: [Tutor] return values function References: <000301cc00ba$ccffb950$66ff2bf0$@bigpond.com> Message-ID: "Lea Parker" wrote > Write the following functions in the > program: > > * Calc_average: This function should take five test scores as > parameters, > and return the average score. Note that you are supposed to write a function to do this not just do it inline. > *determine_grade; this function should take a single test score as a > parameter, and return a letter grade for the test. > The letter grade should be on the following grade scale: > 90-100: A, 80-89: B, 70-79: C, 60-69: D, <60: F.""" > > def main(): > #Get users first test result > test1 = int(raw_input('Enter the score for test 1: ')) > test2 = int(raw_input('Enter the score for test 2: ')) > test3 = int(raw_input('Enter the score for test 3: ')) > test4 = int(raw_input('Enter the score for test 4: ')) > test5 = int(raw_input('Enter the score for test 5: ')) Every time you see repeating code like that you should ask, can I use a loop? If you store the results in a list, it then becomes a simple job to read 5 results: for n in range(5): results.append( int(raw_input('Enter the score for test %d:" % n')) ) > #Get the sum of the test results > cal_average = sum(test1, test2, test3, test4, test5)/5 This is the average not the sum so your comment is wrong. It's also where you should be using the function you were asked to define. The function body would look like the line above. > print 'Together your tests average is: ', cal_average > print 'Your grade is: ', grade And here you need to call your other function to work out the grade. But again you need to call it for each score. You can repeat it 5 times as you did for raw_input or you could use the loop; method I showed you above. > # The sum function to total all tests > def sum(test1, test2, test3, test4, test5): > result = test1 + test2 + test3 + test4 + test5 > return result You didn't need this because Python already has a sum() function that will do this for you. > def determine_grade(score): > #Determine the grade for each score > if score <101 and score >89: > score = A > elif score <90 and score >79: > score = B > elif score <80 and score >69: > score = C > elif score <70 and score >59: > score = D > else: > score = F > return score The most serious problem, and it should have thrown an error, is that the results need to be strings. Otherwise Python will look for a variable called A,B,C etc. And no such name exists in your code. Its not a good idea to use score for both the input parameter that you test and the result that you return. In this case you should get away with it because you never use score after you set it but in general you run the risk of losing access to the input value after you assign a result to score. In the comparisons Python allows you to write them like if 101 > score > 89: grade = "A" which is slightly easier to type and read. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From ambutler at bowdoin.edu Fri Apr 22 16:13:28 2011 From: ambutler at bowdoin.edu (Alex Butler) Date: Fri, 22 Apr 2011 10:13:28 -0400 Subject: [Tutor] Problem with running Python Message-ID: <047101cc00f7$7411d6b0$5c358410$@bowdoin.edu> Hello all, I am new to programming on Python and am teaching myself. I have figured out some basics of coding, however whenever I try to run the program or check its functionality (Alt + X on my windows) it always comes back saying that "there's an error in your program: invalid syntax." However, when it returns to the IDLE page and highlights the error, it highlights the 7 in the python 2.7.1 above any coding. And if I am able to delete that text, it then links the syntax error to the multiple '>' in the code. Is this a common issue with a simple fix? Thanks Alex Butler -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Fri Apr 22 19:44:39 2011 From: steve at alchemy.com (Steve Willoughby) Date: Fri, 22 Apr 2011 10:44:39 -0700 Subject: [Tutor] Problem with running Python In-Reply-To: <047101cc00f7$7411d6b0$5c358410$@bowdoin.edu> References: <047101cc00f7$7411d6b0$5c358410$@bowdoin.edu> Message-ID: <4DB1BE87.3040603@alchemy.com> On 22-Apr-11 07:13, Alex Butler wrote: > Hello all, > > I am new to programming on Python and am teaching myself. I have figured Hi, Alex, welcome to programming and the Python language. If you want to get the most out of this list, it helps to ask very specific questions, showing what you have tried so far to figure out your problem, with what results. Including examples of your actual code and actual error messages is enormously helpful. > out some basics of coding, however whenever I try to run the program or > check its functionality (Alt + X on my windows) it always comes back > saying that ?there?s an error in your program: invalid syntax.? However, > when it returns to the IDLE page and highlights the error, it highlights > the 7 in the python 2.7.1 above any coding. And if I am able to delete > that text, it then links the syntax error to the multiple ?>? in the > code. Is this a common issue with a simple fix? Thanks It sounds to me like you're confusing the actual program code with other stuff like the >>> prompt Python's interpreter types to you. Are you cutting and pasting more into IDLE than the Python program code itself? You should not have things like "Python 2.7.1" or ">>>" showing up in your source code. -- 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 alan.gauld at btinternet.com Fri Apr 22 20:04:34 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 22 Apr 2011 19:04:34 +0100 Subject: [Tutor] Problem with running Python References: <047101cc00f7$7411d6b0$5c358410$@bowdoin.edu> Message-ID: "Alex Butler" wrote > I am new to programming on Python and am teaching myself. I have > figured > out some basics of coding, however whenever I try to run the program > or > check its functionality (Alt + X on my windows) it always comes back > saying > that "there's an error in your program: invalid syntax." However, > when it > returns to the IDLE page and highlights the error, it highlights the > 7 in > the python 2.7.1 above any coding. And if I am able to delete that > text, it > then links the syntax error to the multiple '>' in the code. Is > this a > common issue with a simple fix? Thanks It sounds like you may be trying to execute the code in the shell window. This won't work because of all the stuff that the interpreter prints. Thus in the interactive prompt you see: >>> print( "hello world") But in your program file you only type: print( "hello world" ) The >>> bit is part of the interpreter not the program. >From your comments thats the best that I can guess. If thats not the problem then we will neeed more detail about what exactly you are doing and the specific error messages you get printed. You might find Danny Yoo's introduction to IDLE useful for a visual reference. http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html Its for Python 2.4 but the principles of using it for later versions are exactly the same. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From outsideme99 at live.com Sat Apr 23 00:02:00 2011 From: outsideme99 at live.com (Brad Desautels) Date: Fri, 22 Apr 2011 18:02:00 -0400 Subject: [Tutor] (no subject) Message-ID: Hello, I am just learning Python 3.0 and I am working on this problem. I need to know what the output would be. Can anybody help Thanks, Brad class Bozo: def __init__(self, value): print("Creating a Boso from:" , value) self.value = 2 * value def clown(self, x): print(x * self.value) return x + self.value def main(): print("Clowning around now.") c1 = Bozo(3) c2 = Bozo(4) print(c1.clown(3)) print(c2. clown(c1.clown(2)) -------------- next part -------------- An HTML attachment was scrubbed... URL: From rmj540 at gmail.com Sat Apr 23 00:07:34 2011 From: rmj540 at gmail.com (Ryan J) Date: Fri, 22 Apr 2011 15:07:34 -0700 Subject: [Tutor] Reading video streams from Internet Message-ID: Hello Python gurus! I am trying to 1) Read and decode video streams from internet. 2) Store them in a buffer. 3) Eventually convert them into data that can be used in Cycling '74's Jitter. If anyone has any idea how to start with this, that would be great! I have limited experience with Python, but I have a bit of exposure to the urllib and urllib2. Any help is much appreciated! Thank you! -Ryan -------------- next part -------------- An HTML attachment was scrubbed... URL: From ambutler at bowdoin.edu Fri Apr 22 20:52:34 2011 From: ambutler at bowdoin.edu (Alex Butler) Date: Fri, 22 Apr 2011 14:52:34 -0400 Subject: [Tutor] Python trouble Message-ID: <04a801cc011e$82be2d90$883a88b0$@bowdoin.edu> Ok let me try to be more clear. I am trying to write code in the IDLE Python GUI of python 2.7. When I open the new python shell, there is a written header as well as the three >s on the left side. I now those are used as indents and I do not type them in. However, whenever I write any type of code and either attempt to run or click alt + x to check module, it says "there is an error in your program: invalid syntax." Then when it goes back to the page to highlight the syntax error the second > is highlighted in color as it is the problem. Before I deleted the header from this program, it would highlight the 7 after the 2. In the header. Alex Butler -------------- next part -------------- An HTML attachment was scrubbed... URL: From amonroe at columbus.rr.com Sat Apr 23 00:38:00 2011 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Fri, 22 Apr 2011 18:38:00 -0400 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: <61174589336.20110422183800@columbus.rr.com> > Hello, I am just learning Python 3.0 and I am working on this > problem. I need to know what the output would be. What happened when you ran it on your computer? You _did_ try that, right? Alan From outsideme99 at live.com Sat Apr 23 00:37:56 2011 From: outsideme99 at live.com (Brad Desautels) Date: Fri, 22 Apr 2011 18:37:56 -0400 Subject: [Tutor] (no subject) Message-ID: Hello, I am just learning Python 3.0 and I am working on this problem. I need to know what the output would be. Can anybody help Thanks, Brad class Bozo: def __init__(self, value): print("Creating a Boso from:" , value) self.value = 2 * value def clown(self, x): print(x * self.value) return x + self.value def main(): print("Clowning around now.") c1 = Bozo(3) c2 = Bozo(4) print(c1.clown(3)) print(c2. clown(c1.clown(2)) -------------- next part -------------- An HTML attachment was scrubbed... URL: From lea-parker at bigpond.com Sat Apr 23 00:40:12 2011 From: lea-parker at bigpond.com (Lea Parker) Date: Sat, 23 Apr 2011 08:40:12 +1000 Subject: [Tutor] return values function thanks Message-ID: <000301cc013e$3e4d8690$bae893b0$@bigpond.com> Hi Alan Thanks once again for your help. Lea -----Original Message----- From: tutor-bounces+lea-parker=bigpond.com at python.org [mailto:tutor-bounces+lea-parker=bigpond.com at python.org] On Behalf Of tutor-request at python.org Sent: Friday, 22 April 2011 5:32 PM To: tutor at python.org Subject: Tutor Digest, Vol 86, Issue 77 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: Jokes on Python Language (Marc Tompkins) 2. Re: learnpython.org - Free Interactive Python Tutorial (Ron Reiter) 3. Re: Plotting a Linear Equation (Alan Gauld) 4. return values function (Lea Parker) 5. Re: return values function (Alan Gauld) ---------------------------------------------------------------------- Message: 1 Date: Thu, 21 Apr 2011 13:35:38 -0700 From: Marc Tompkins To: tutor at python.org Subject: Re: [Tutor] Jokes on Python Language Message-ID: Content-Type: text/plain; charset="iso-8859-1" On Thu, Apr 21, 2011 at 4:49 AM, Ratna Banjara wrote: > Hello all, > > Does anybody knows jokes related to Python Language? > If the answer is yes, please do share it... > Of course, there's the AWESOME webcomic xkcd (www.xkcd.com) which is excellent reading even when he's not talking about Python... but in particular, there are several great strips about Python itself (or at least, they mention Python in a fond way): http://xkcd.com/353/ http://xkcd.com/413/ http://xkcd.com/409/ http://xkcd.com/521/ -------------- next part -------------- An HTML attachment was scrubbed... URL: ------------------------------ Message: 2 Date: Thu, 21 Apr 2011 20:22:39 +0300 From: Ron Reiter To: tutor at python.org Subject: Re: [Tutor] learnpython.org - Free Interactive Python Tutorial Message-ID: Content-Type: text/plain; charset="iso-8859-1" For those of you who didn't notice the title, here is the link: www.learnpython.org Also, please note that there is still not enough content to actually learn from the website yet. I am hoping people will help me with writing tutorials so the site will be useful as soon as possible. On Wed, Apr 20, 2011 at 9:16 PM, Ron Reiter wrote: > Hey. > > I've created a website for learning Python interactively online. Check > it out, and I would really appreciate it if you can also contribute tutorials. > > Thanks! > > -- > -- Ron > -- -- Ron -------------- next part -------------- An HTML attachment was scrubbed... URL: ------------------------------ Message: 3 Date: Thu, 21 Apr 2011 22:40:51 +0100 From: "Alan Gauld" To: tutor at python.org Subject: Re: [Tutor] Plotting a Linear Equation Message-ID: Content-Type: text/plain; format=flowed; charset="iso-8859-1"; reply-type=original "Emanuel Woiski" wrote > easy: I love your sense of humour! > import pylab as pl > import numpy as np > x1,x2,n,m,b = 0.,10.,11,2.,5. > x = np.r_[x1:x2:n*1j] > pl.plot(x,m*x + b); pl.grid(); pl.show() Now, given this is a list for beginners to Python, could you try explaining what you did there and how the OP, or anyone else for that matter, might use it? Or were you really just trying to establish that if you try hard you can write Python that is as difficult to read as Perl? >> I want to use matplotlib (or similar) to plot an equation in >> (y=mx+b) or standard form (Ax + By = C). I could make two points >> out of those manually, but I was wondering if anyone knew of an >> easier way. Thanks. Alan G. ------------------------------ Message: 4 Date: Fri, 22 Apr 2011 16:59:18 +1000 From: "Lea Parker" To: Subject: [Tutor] return values function Message-ID: <000301cc00ba$ccffb950$66ff2bf0$@bigpond.com> Content-Type: text/plain; charset="us-ascii" Hello I am hoping someone can put me on the right track. The code below includes the assignment question at the beginning. I seem to have been able to calculate average ok, but what I can't seem to do is sort it so it will return a grade for each result. Can you give me some advice to head me in the right direction please. My code is: """Write a program that asks the user to enter 5 sets tests scores. The program should then display the 'letter grade' (A, B, C, D, F) for each test score, and the overall average test schore. Write the following functions in the program: * Calc_average: This function should take five test scores as parameters, and return the average score. *determine_grade; this function should take a single test score as a parameter, and return a letter grade for the test. The letter grade should be on the following grade scale: 90-100: A, 80-89: B, 70-79: C, 60-69: D, <60: F.""" def main(): #Get users first test result test1 = int(raw_input('Enter the score for test 1: ')) #Get users second test result test2 = int(raw_input('Enter the score for test 2: ')) #Get users third test result test3 = int(raw_input('Enter the score for test 3: ')) #Get users forth test result test4 = int(raw_input('Enter the score for test 4: ')) #Get users fifth test result test5 = int(raw_input('Enter the score for test 5: ')) #Get the sum of the test results cal_average = sum(test1, test2, test3, test4, test5)/5 #Display the total of tests print 'Together your tests average is: ', cal_average print 'Your grade is: ', grade # The sum function to total all tests def sum(test1, test2, test3, test4, test5): result = test1 + test2 + test3 + test4 + test5 return result def determine_grade(score): #Determine the grade for each score if score <101 and score >89: score = A elif score <90 and score >79: score = B elif score <80 and score >69: score = C elif score <70 and score >59: score = D else: score = F return score # Call the main function main() -------------- next part -------------- An HTML attachment was scrubbed... URL: ------------------------------ Message: 5 Date: Fri, 22 Apr 2011 08:32:04 +0100 From: "Alan Gauld" To: tutor at python.org Subject: Re: [Tutor] return values function Message-ID: Content-Type: text/plain; format=flowed; charset="iso-8859-1"; reply-type=original "Lea Parker" wrote > Write the following functions in the > program: > > * Calc_average: This function should take five test scores as > parameters, and return the average score. Note that you are supposed to write a function to do this not just do it inline. > *determine_grade; this function should take a single test score as a > parameter, and return a letter grade for the test. > The letter grade should be on the following grade scale: > 90-100: A, 80-89: B, 70-79: C, 60-69: D, <60: F.""" > > def main(): > #Get users first test result > test1 = int(raw_input('Enter the score for test 1: ')) > test2 = int(raw_input('Enter the score for test 2: ')) > test3 = int(raw_input('Enter the score for test 3: ')) > test4 = int(raw_input('Enter the score for test 4: ')) > test5 = int(raw_input('Enter the score for test 5: ')) Every time you see repeating code like that you should ask, can I use a loop? If you store the results in a list, it then becomes a simple job to read 5 results: for n in range(5): results.append( int(raw_input('Enter the score for test %d:" % n')) ) > #Get the sum of the test results > cal_average = sum(test1, test2, test3, test4, test5)/5 This is the average not the sum so your comment is wrong. It's also where you should be using the function you were asked to define. The function body would look like the line above. > print 'Together your tests average is: ', cal_average > print 'Your grade is: ', grade And here you need to call your other function to work out the grade. But again you need to call it for each score. You can repeat it 5 times as you did for raw_input or you could use the loop; method I showed you above. > # The sum function to total all tests def sum(test1, test2, test3, > test4, test5): > result = test1 + test2 + test3 + test4 + test5 > return result You didn't need this because Python already has a sum() function that will do this for you. > def determine_grade(score): > #Determine the grade for each score > if score <101 and score >89: > score = A > elif score <90 and score >79: > score = B > elif score <80 and score >69: > score = C > elif score <70 and score >59: > score = D > else: > score = F > return score The most serious problem, and it should have thrown an error, is that the results need to be strings. Otherwise Python will look for a variable called A,B,C etc. And no such name exists in your code. Its not a good idea to use score for both the input parameter that you test and the result that you return. In this case you should get away with it because you never use score after you set it but in general you run the risk of losing access to the input value after you assign a result to score. In the comparisons Python allows you to write them like if 101 > score > 89: grade = "A" which is slightly easier to type and read. HTH, -- Alan Gauld 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 86, Issue 77 ************************************* From steve at alchemy.com Sat Apr 23 00:43:13 2011 From: steve at alchemy.com (Steve Willoughby) Date: Fri, 22 Apr 2011 15:43:13 -0700 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: <4DB20481.1020604@alchemy.com> On 22-Apr-11 15:37, Brad Desautels wrote: > Hello, I am just learning Python 3.0 and I am working on this problem. I > need to know what the output would be.Can anybody help What is your question? If you want to see what its output would be... run it and see the output. Is there more to your question, like what *should* the output be? (in which case, tell us what your output *is* and we can help you see why it's not what you expected). From outsideme99 at live.com Sat Apr 23 00:48:44 2011 From: outsideme99 at live.com (Brad Desautels) Date: Fri, 22 Apr 2011 18:48:44 -0400 Subject: [Tutor] (no subject) In-Reply-To: <61174589336.20110422183800@columbus.rr.com> References: <61174589336.20110422183800@columbus.rr.com> Message-ID: Ya, I did try to run it and I am getting a syntax error before it runs. -----Original Message----- From: tutor-bounces+outsideme99=live.com at python.org [mailto:tutor-bounces+outsideme99=live.com at python.org] On Behalf Of R. Alan Monroe Sent: Friday, April 22, 2011 6:38 PM To: tutor at python.org Subject: Re: [Tutor] (no subject) > Hello, I am just learning Python 3.0 and I am working on this > problem. I need to know what the output would be. What happened when you ran it on your computer? You _did_ try that, right? Alan _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From steve at alchemy.com Sat Apr 23 00:52:14 2011 From: steve at alchemy.com (Steve Willoughby) Date: Fri, 22 Apr 2011 15:52:14 -0700 Subject: [Tutor] (no subject) In-Reply-To: References: <61174589336.20110422183800@columbus.rr.com> Message-ID: <4DB2069E.2010004@alchemy.com> On 22-Apr-11 15:48, Brad Desautels wrote: > Ya, I did try to run it and I am getting a syntax error before it runs. and the message said....? Where did it point to as the syntax error? From steve at alchemy.com Sat Apr 23 01:01:13 2011 From: steve at alchemy.com (Steve Willoughby) Date: Fri, 22 Apr 2011 16:01:13 -0700 Subject: [Tutor] Python trouble In-Reply-To: <04a801cc011e$82be2d90$883a88b0$@bowdoin.edu> References: <04a801cc011e$82be2d90$883a88b0$@bowdoin.edu> Message-ID: <4DB208B9.5030602@alchemy.com> On 22-Apr-11 11:52, Alex Butler wrote: > Ok let me try to be more clear. I am trying to write code in the IDLE > Python GUI of python 2.7. When I open the new python shell, there is a > written header as well as the three >s on the left side. I now those are > used as indents and I do not type them in. However, whenever I write any > type of code and either attempt to run or click alt + x to check module, > it says ?there is an error in your program: invalid syntax.? Then when > it goes back to the page to highlight the syntax error the second > is > highlighted in color as it is the problem. Before I deleted the header > from this program, it would highlight the 7 after the 2. In the header. Okay, that's pretty much what you said last time. What is the actual code you're trying to run? If it's really complaining about >>> being a syntax error, it sounds like you're confused about where you are in the tool or extra text is getting pasted. If you open a new source window (file->new) (not a "shell" window), and type some python code, that window won't have a header line or >>> prompts at all, just your code. So... start IDLE select File->New; new untitled window pops up type a python program, maybe this: print "hello" hit alt-X (although personally, I'd hit F5 instead). It should prompt you for a file to save your new program into, then run it back in the other window (the shell) that has the >>>s in it. How, exactly, does what I just described differ from what happened to you? -- 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 outsideme99 at live.com Sat Apr 23 01:03:37 2011 From: outsideme99 at live.com (Brad Desautels) Date: Fri, 22 Apr 2011 19:03:37 -0400 Subject: [Tutor] (no subject) In-Reply-To: <4DB2069E.2010004@alchemy.com> References: <61174589336.20110422183800@columbus.rr.com> <4DB2069E.2010004@alchemy.com> Message-ID: Hi Steve, I am getting my error on main() I think it is possibly be an indentation error -----Original Message----- From: tutor-bounces+outsideme99=live.com at python.org [mailto:tutor-bounces+outsideme99=live.com at python.org] On Behalf Of Steve Willoughby Sent: Friday, April 22, 2011 6:52 PM To: tutor at python.org Subject: Re: [Tutor] (no subject) On 22-Apr-11 15:48, Brad Desautels wrote: > Ya, I did try to run it and I am getting a syntax error before it runs. and the message said....? Where did it point to as the syntax error? _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From steve at alchemy.com Sat Apr 23 01:10:17 2011 From: steve at alchemy.com (Steve Willoughby) Date: Fri, 22 Apr 2011 16:10:17 -0700 Subject: [Tutor] (no subject) In-Reply-To: References: <61174589336.20110422183800@columbus.rr.com> <4DB2069E.2010004@alchemy.com> Message-ID: <4DB20AD9.9090006@alchemy.com> On 22-Apr-11 16:03, Brad Desautels wrote: > Hi Steve, I am getting my error on main() I think it is possibly be an > indentation error It should be easy to check. Make sure "def main():" is all the way to the left, and all the lines under it are the same level as each other but usually indentation errors say that they are indentation errors. Look carefully at your parentheses. Does every ( have a matching )? -- 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 fgrose at gmail.com Sat Apr 23 01:54:12 2011 From: fgrose at gmail.com (Frederick Grose) Date: Fri, 22 Apr 2011 19:54:12 -0400 Subject: [Tutor] Run a few Python commands from a temporary filesystem when the rootfs is halted Message-ID: With Bash, when one needs to halt the current root filesystem, to pivot to a new filesystem, one can copy some of the command files and their dependencies to a temporary file system and execute from that code base. Is there a way to accomplish the same within a Python script? Or must I chain Python and Bash together for this? --Fred -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Sat Apr 23 01:59:18 2011 From: steve at alchemy.com (Steve Willoughby) Date: Fri, 22 Apr 2011 16:59:18 -0700 Subject: [Tutor] Run a few Python commands from a temporary filesystem when the rootfs is halted In-Reply-To: References: Message-ID: <4DB21656.3020302@alchemy.com> On 22-Apr-11 16:54, Frederick Grose wrote: > With Bash, when one needs to halt the current root filesystem, to pivot > to a new filesystem, one can copy some of the command files and their > dependencies to a temporary file system and execute from that code base. I'm not sure those words mean what you think they mean, or I'm missing what you're trying to do here. halting the root filesystem? pivot? code base? You're not trying to talk about jail/chroot, perhaps? -- 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 steve at pearwood.info Sat Apr 23 02:03:12 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 23 Apr 2011 10:03:12 +1000 Subject: [Tutor] Python trouble In-Reply-To: <04a801cc011e$82be2d90$883a88b0$@bowdoin.edu> References: <04a801cc011e$82be2d90$883a88b0$@bowdoin.edu> Message-ID: <4DB21740.1090204@pearwood.info> Alex Butler wrote: > Ok let me try to be more clear. I am trying to write code in the IDLE > Python GUI of python 2.7. When I open the new python shell, there is a > written header as well as the three >s on the left side. I now those are > used as indents and I do not type them in. However, whenever I write any > type of code and either attempt to run or click alt + x to check module, it > says "there is an error in your program: invalid syntax." Then when it goes > back to the page to highlight the syntax error the second > is highlighted > in color as it is the problem. Before I deleted the header from this > program, it would highlight the 7 after the 2. In the header. The >>> is called the prompt. It is not part of the code, it is just there to prompt you that the interpreter is waiting for you. If you start a command that goes over two or more lines, the prompt will change to three dots ... to remind you that you haven't finished writing the command yet. Please COPY and PASTE an example of the system error. Do not retype it, especially not from memory, but actually copy and paste the complete error, including the line it claims is invalid, and paste it into a reply. Like this: >>> x = 1 >>> y = 2 >>> if x=y: File "", line 1 if x=y: ^ SyntaxError: invalid syntax Thank you. -- Steven From steve at pearwood.info Sat Apr 23 02:10:46 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 23 Apr 2011 10:10:46 +1000 Subject: [Tutor] (no subject) In-Reply-To: References: <61174589336.20110422183800@columbus.rr.com> Message-ID: <4DB21906.3090501@pearwood.info> Brad Desautels wrote: > Ya, I did try to run it and I am getting a syntax error before it runs. Then fix the syntax error. Do you need help understanding the error? If so, please COPY and PASTE the entire error here, do not try to re-type it, specially not from memory. One hint that a lot of beginners miss is that the syntax error includes a pointer to the first mistake: it uses a ^ on an otherwise blank line to point to the first part of the code that is wrong: >>> if x=y: File "", line 1 if x=y: ^ SyntaxError: invalid syntax This tells me that I can't say "if x=y" (assignment), but I need equality instead: "if x==y". Another thing that sometimes catches even experienced programmers: if you forget to close brackets (round, square or curly), you will often get the SyntaxError on the *following* line: >>> mylist = [1, 2, 3 ... for m in mylist: File "", line 2 for m in mylist: ^ SyntaxError: invalid syntax -- Steven From fgrose at gmail.com Sat Apr 23 02:14:03 2011 From: fgrose at gmail.com (Frederick Grose) Date: Fri, 22 Apr 2011 20:14:03 -0400 Subject: [Tutor] Run a few Python commands from a temporary filesystem when the rootfs is halted In-Reply-To: <4DB21656.3020302@alchemy.com> References: <4DB21656.3020302@alchemy.com> Message-ID: On Fri, Apr 22, 2011 at 7:59 PM, Steve Willoughby wrote: > On 22-Apr-11 16:54, Frederick Grose wrote: > >> With Bash, when one needs to halt the current root filesystem, to pivot >> to a new filesystem, one can copy some of the command files and their >> dependencies to a temporary file system and execute from that code base. >> > > I'm not sure those words mean what you think they mean, or I'm missing what > you're trying to do here. halting the root filesystem? pivot? code base? > > You're not trying to talk about jail/chroot, perhaps? > > -- > Steve Willoughby / steve at alchemy.com > The particulars are that I've rebuilt a Fedora LiveOS filesystem image from a currently running instance (incorporating the filesystem changes in the device-mapper overlay into a new base filesystem image file). I'd like to halt the active rootfs, switch to its mirror, copy over the halted filesystem image file with the refreshed version, and then switch back. --Fred -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sat Apr 23 02:22:49 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 23 Apr 2011 10:22:49 +1000 Subject: [Tutor] Run a few Python commands from a temporary filesystem when the rootfs is halted In-Reply-To: References: Message-ID: <4DB21BD9.9090908@pearwood.info> Frederick Grose wrote: > With Bash, when one needs to halt the current root filesystem, to pivot to a > new filesystem, one can copy some of the command files and their > dependencies to a temporary file system and execute from that code base. > > Is there a way to accomplish the same within a Python script? This is way off-topic for a Python tutor list. This is about learning the Python programming language, not the intricate corners of (I assume) Linux system administration. I would imagine that it would be very, very difficult in Python, because you would need somehow to end the *current* Python process and start up a *new* Python process running from executables on the new file system, without manual intervention. I strongly suggest you take this question to the main Python list, python at python.org, which is also available as a news group comp.lang.python, and show the bash code you are trying to duplicate. There's no guarantee you'll get an answer there either, but it's more likely than here. Good luck! -- Steven From steve at pearwood.info Sat Apr 23 02:33:58 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 23 Apr 2011 10:33:58 +1000 Subject: [Tutor] Reading video streams from Internet In-Reply-To: References: Message-ID: <4DB21E76.1020907@pearwood.info> Ryan J wrote: > Hello Python gurus! > I am trying to > 1) Read and decode video streams from internet. > 2) Store them in a buffer. > 3) Eventually convert them into data that can be used in Cycling '74's > Jitter. > > If anyone has any idea how to start with this, that would be great! I have > limited experience with Python, but I have a bit of exposure to the urllib > and urllib2. Do you have a URL for the video stream? Is it a http or https URL that points directly to a .mov or other video file? Then you just use urllib and/or urllib2 to connect to that URL and read data. You can write that data into either memory or directly to a file on disk. I have no idea what Cycling '74's Jitter is, or what formats it expects. I suggest you use existing tools like mencoder to convert the video into whatever format is appropriate. Re-writing a video converter tool in Python will be a huge job, and it likely too slow to be usable. If the URL is a secret, proprietary protocol like MMS or RTSP, you will need to find some library to handle the protocol, or possibly reverse engineer it yourself. Good luck with that. -- Steven From steve at alchemy.com Sat Apr 23 02:55:40 2011 From: steve at alchemy.com (Steve Willoughby) Date: Fri, 22 Apr 2011 17:55:40 -0700 Subject: [Tutor] Run a few Python commands from a temporary filesystem when the rootfs is halted In-Reply-To: References: <4DB21656.3020302@alchemy.com> Message-ID: <4DB2238C.1060206@alchemy.com> On 22-Apr-11 17:14, Frederick Grose wrote: > The particulars are that I've rebuilt a Fedora LiveOS filesystem image > from a currently running instance (incorporating the filesystem changes > in the device-mapper overlay into a new base filesystem image file). Right, so essentially you're talking about chrooting into the LiveOS image temporarily. It's not really "halting" as such, just where the OS's idea of "root" is at the moment. That involves mounting your LiveOS filesystem as well. The short answer is that if you can do it in the shell, you can do it in Python, but there's got to be more to the story than just this. What are you trying to actually do that you need Python for this? I assume you're trying to automate the process of what you're doing? Almost probably this is possible with Python, if I understand what you're doing. If you just want to know how to write a Python script around the steps you want to accomplish, as a simple beginning Python experience, we may still be of service to you. We could, for example point you to read up on the os.chroot() function in the Python standard library. If your question has more to do with the particulars of managing chroot()ed mountpoints or preparing LiveOS images, you'd need to look to a forum devoted to that. -- 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 fgrose at gmail.com Sat Apr 23 03:18:55 2011 From: fgrose at gmail.com (Frederick Grose) Date: Fri, 22 Apr 2011 21:18:55 -0400 Subject: [Tutor] Run a few Python commands from a temporary filesystem when the rootfs is halted In-Reply-To: <4DB2238C.1060206@alchemy.com> References: <4DB21656.3020302@alchemy.com> <4DB2238C.1060206@alchemy.com> Message-ID: On Fri, Apr 22, 2011 at 8:55 PM, Steve Willoughby wrote: > On 22-Apr-11 17:14, Frederick Grose wrote: > >> The particulars are that I've rebuilt a Fedora LiveOS filesystem image >> from a currently running instance (incorporating the filesystem changes >> in the device-mapper overlay into a new base filesystem image file). >> > > Right, so essentially you're talking about chrooting into the LiveOS image > temporarily. It's not really "halting" as such, just where the OS's idea of > "root" is at the moment. That involves mounting your LiveOS filesystem as > well. > > The short answer is that if you can do it in the shell, you can do it in > Python, but there's got to be more to the story than just this. What are > you trying to actually do that you need Python for this? I assume you're > trying to automate the process of what you're doing? > > Almost probably this is possible with Python, if I understand what you're > doing. If you just want to know how to write a Python script around the > steps you want to accomplish, as a simple beginning Python experience, we > may still be of service to you. > > We could, for example point you to read up on the os.chroot() function in > the Python standard library. > > If your question has more to do with the particulars of managing chroot()ed > mountpoints or preparing LiveOS images, you'd need to look to a forum > devoted to that. > > > -- > Steve Willoughby / steve at alchemy.com > Thank you Steve and Steven for your assistance! I misread this sentence in the list description, "While the list is called tutor, anyone, whether novice or expert, can answer questions." .. to include 'ask' as well as answer questions that may be instructive. I've posted in Python-list, as suggested. Steven's synopsis, "... you would need somehow to end the *current* Python process and start up a *new* Python process running from executables on the new file system, without manual intervention." is the situation I'm attempting. I have written the LiveOS rebuilding code in Python, and am working to complete the operation in Python, if possible, but don't know enough about how the Python shutdown and startup might be scripted within Python. --Fred -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sat Apr 23 03:27:45 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 23 Apr 2011 11:27:45 +1000 Subject: [Tutor] Run a few Python commands from a temporary filesystem when the rootfs is halted In-Reply-To: References: <4DB21656.3020302@alchemy.com> <4DB2238C.1060206@alchemy.com> Message-ID: <4DB22B11.8020609@pearwood.info> Frederick Grose wrote: > I misread this sentence in the list description, "While the list is called > tutor, anyone, whether novice or expert, can answer questions." .. to > include 'ask' as well as answer questions that may be instructive. Well, you can *ask*, but the number of people on this list is much smaller than the main python list, and we tend to be focused more on beginner questions and learning the language rather than the more advanced stuff. So it's more about maximising your chances of getting a good answer. -- Steven From outsideme99 at live.com Sat Apr 23 04:27:02 2011 From: outsideme99 at live.com (Brad Desautels) Date: Fri, 22 Apr 2011 22:27:02 -0400 Subject: [Tutor] python timers In-Reply-To: <566099.78584.qm@web130221.mail.mud.yahoo.com> References: <566099.78584.qm@web130221.mail.mud.yahoo.com> Message-ID: Hello, my name is Brad and I am a student at Suny Plattsburgh. and Python programming is a course I am taking this semester. I find it a bit of a challenge doing all the chapter programming exercises that are assigned. We are currently in chapter 8 but some of the basics have not completely sunk in yet. This is extra hard for me because my learning capacity isn't what it used to be, 4 years ago I was in a motorcycle accident in which I sustained a traumatic brain injury and lost my left leg .The TBI affects my ability to remember short term things and my cognitive abilities are a bit off to say the least. If what I write seems a bit off """"Please bear with me.. I need help completing my exercises, and do work very hard to absorb this material. Thank you, Brad From: tutor-bounces+outsideme99=live.com at python.org [mailto:tutor-bounces+outsideme99=live.com at python.org] On Behalf Of michael scott Sent: Thursday, April 21, 2011 12:38 AM To: tutor at python.org Subject: [Tutor] python timers Hello how do you do. Today's question has to do with the time module. I want to add a timer to my gui. As I was messing around with it I found a way to measure time... but I'm positive there is a more elegant way to deal with this than what I've thrown together. def thing(): start = time.time() while 1: now = time.time() if now == start + 10.0: print "times up" How are timers usually implemented? By the way, I'm not really asking as much about the how (because I could throw something together that will serve my purpose), I'm asking more about conventions, like is there a standard way people implement timers, like does python come with one built in? Does every programmer who wants a timer write a different one? ---- What is it about you... that intrigues me so? -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Apr 23 09:53:55 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 23 Apr 2011 08:53:55 +0100 Subject: [Tutor] python timers References: <566099.78584.qm@web130221.mail.mud.yahoo.com> Message-ID: "Brad Desautels" wrote > Hello, my name is Brad and I am a student at Suny Plattsburgh. and > Python > programming is a course I am taking this semester. Hi, Welcome to the list. It will help in future if you do NOT reply to an existing message to start a new discussion. Doing so causes your message to appear inside a thread on many mail/news readers and so it is less likely to be seen. It also esults in a single thread combining two subjects which makes it harder to find stuff in the archives later. So please start a new thread with a new message and a new subject line. > are currently in chapter 8 but some of the basics have not > completely sunk > in yet. Feel free to ask questions here. We will not do your homework for you but we will offer explanations of things you don't understand and give hints on how to address different problems. But we do expect you to tell us what you have tried yourself first and to be specific about what you ask. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Apr 23 10:03:26 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 23 Apr 2011 09:03:26 +0100 Subject: [Tutor] Python trouble References: <04a801cc011e$82be2d90$883a88b0$@bowdoin.edu> <4DB21740.1090204@pearwood.info> Message-ID: "Steven D'Aprano" wrote >> Ok let me try to be more clear. I am trying to write code in the >> IDLE >> Python GUI of python 2.7. > start a command that goes over two or more lines, the prompt will > change to three dots ... Sadly in IDLE it won't do this (I hate that feature of IDLE!) but it will indent the cursor for you, padding the line with tabs. > Please COPY and PASTE an example of the system error. Do not retype > it, especially not from memory, but actually copy and paste the > complete error, including the line it claims is invalid, and paste > it into a reply. Like this: Again IDLE makes this difficult if you are running from a New Window because it presents the error in a pop up dialog, while highlighting the "faulty line" in the edit window, but please do try to send the actual error text. Alan G. From alan.gauld at btinternet.com Sat Apr 23 10:13:43 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 23 Apr 2011 09:13:43 +0100 Subject: [Tutor] (no subject) References: <61174589336.20110422183800@columbus.rr.com> Message-ID: "Brad Desautels" wrote in message news:BLU0-SMTP18287B0B9EE400CCE65B407DE950 at phx.gbl... > Ya, I did try to run it and I am getting a syntax error before it > runs. When asking for help with errors please post the actual error. Do not summarise it and do not shorten it. Similarly with the code, if it is short enough post the code in the message, if it ios long (say > 100 lines) post it on a web site like pastebin and send a link. Programming is all about precision and detail and if we don't see the exact code and error then it is very difficult to give accurate answers. And just guessing wastes everyone's time. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Apr 23 10:19:15 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 23 Apr 2011 09:19:15 +0100 Subject: [Tutor] return values function thanks References: <000301cc013e$3e4d8690$bae893b0$@bigpond.com> Message-ID: "Lea Parker" wrote > Hi Alan > > Thanks once again for your help. > > Lea You are welcome but please when replying trim out the irrelevant stuff from the digest. Remember that some people either pay for their bandwidth or have a cap on usage (especially on mobile accounts) so sending lots of junk uses up their allowance and/or costs them money. Also by sending the entire digest it also makes it hard for readers to find which messages you are talking about. Regards, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From g.nius.ck at gmail.com Sat Apr 23 21:51:11 2011 From: g.nius.ck at gmail.com (Chris King) Date: Sat, 23 Apr 2011 15:51:11 -0400 Subject: [Tutor] (no subject) In-Reply-To: References: <61174589336.20110422183800@columbus.rr.com> Message-ID: <4DB32DAF.6090903@gmail.com> On 4/22/2011 6:48 PM, Brad Desautels wrote: > Ya, I did try to run it and I am getting a syntax error before it runs. > > > -----Original Message----- > From: tutor-bounces+outsideme99=live.com at python.org > [mailto:tutor-bounces+outsideme99=live.com at python.org] On Behalf Of R. Alan > Monroe > Sent: Friday, April 22, 2011 6:38 PM > To: tutor at python.org > Subject: Re: [Tutor] (no subject) > >> Hello, I am just learning Python 3.0 and I am working on this >> problem. I need to know what the output would be. > What happened when you ran it on your computer? You _did_ try that, > right? > > Alan > > _______________________________________________ > 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 Well first of, then the output would be a syntax error :D. But after the codes debugged, here's what should happen as long as the python 3.0 didn't completely change all its code. Creating a Boso from: 3 Creating a Boso form: 4 18 9 12 64 16 From ranceh at gmail.com Sun Apr 24 00:31:41 2011 From: ranceh at gmail.com (Rance Hall) Date: Sat, 23 Apr 2011 17:31:41 -0500 Subject: [Tutor] validating user input Message-ID: Ok, so I have this code that is working, but does little to validate user input and I don't quite yet understand that process yet. so given the following function: def buildmenu(menuchoices): for i, option in enumerate(menuchoices, 1): print('%s. %s' % (i, option)) menuchoice = int(input('\nYour Choice? ')) return menuchoice-1 Ideally before returning the menuchoice-1 there should be a check to make sure that the choice is a valid one. I know what I want to happen if the test fails, and if it passes we can just do the return and exit the function. I need help understanding how exactly we validate the input since in this case I have no idea how many menu entries there would be. Thanks for your time. Rance PS Happy Easter. From eq742 at ncf.ca Sun Apr 24 00:58:03 2011 From: eq742 at ncf.ca (pierre dagenais) Date: Sat, 23 Apr 2011 18:58:03 -0400 Subject: [Tutor] python2 vs python3 urllib Message-ID: <4DB3597B.2020109@ncf.ca> The following code works as expected with python version 2.6.5, but with version 3.1.2 I get the following error: pierre:/MyCode/mesProjets$ py3 test.py Traceback (most recent call last): File "test.py", line 3, in sock = urllib.urlopen("http://diveintopython.org/") AttributeError: 'module' object has no attribute 'urlopen' The code: #example 8.5 of diveintopython.org/ import urllib sock = urllib.urlopen("http://diveintopython.org/") htmlSource = sock.read() sock.close() print (htmlSource) What is the proper syntax in version 3? Thank you, Your help is much appreciated. From enalicho at gmail.com Sun Apr 24 01:32:13 2011 From: enalicho at gmail.com (Noah Hall) Date: Sun, 24 Apr 2011 00:32:13 +0100 Subject: [Tutor] python2 vs python3 urllib In-Reply-To: <4DB3597B.2020109@ncf.ca> References: <4DB3597B.2020109@ncf.ca> Message-ID: On Sat, Apr 23, 2011 at 11:58 PM, pierre dagenais wrote: > The following code works as expected with python version 2.6.5, but with > version 3.1.2 I get the following error: > > pierre:/MyCode/mesProjets$ py3 test.py > > Traceback (most recent call last): > ?File "test.py", line 3, in > ? ?sock = urllib.urlopen("http://diveintopython.org/") > AttributeError: 'module' object has no attribute 'urlopen' > > The code: > > #example 8.5 of diveintopython.org/ > import urllib > sock = urllib.urlopen("http://diveintopython.org/") > htmlSource = sock.read() > sock.close() > print (htmlSource) > > What is the proper syntax in version 3? The problem is described in the exception - the module "urllib" has no method urlopen. Things were moved around in 3.0. In fact, diveintopython has some information on this here - http://diveintopython3.org/porting-code-to-python-3-with-2to3.html#urllib From alan.gauld at btinternet.com Sun Apr 24 01:38:20 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 24 Apr 2011 00:38:20 +0100 Subject: [Tutor] validating user input References: Message-ID: "Rance Hall" wrote > Ok, so I have this code that is working, but does little to validate > user input and I don't quite yet understand that process yet. > > so given the following function: > > def buildmenu(menuchoices): > for i, option in enumerate(menuchoices, 1): Interesting, I didn't know enumerate could take a second argument, and help() doesn't mention it eioither.... You learn something new ... > print('%s. %s' % (i, option)) > menuchoice = int(input('\nYour Choice? ')) > return menuchoice-1 > > I need help understanding how exactly we validate the input since in > this case I have no idea how many menu entries there would be. But you have just finished enumerating them and I holds the index of the last item, or in your case the count of the last item. But even without that you can always use len() to find out how many menuchoices there are... So you can check if choice lies between 1 and len(menuchoices) or between 1 and i whichever you prefer. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sun Apr 24 01:42:50 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 24 Apr 2011 00:42:50 +0100 Subject: [Tutor] python2 vs python3 urllib References: <4DB3597B.2020109@ncf.ca> Message-ID: "pierre dagenais" wrote > sock = urllib.urlopen("http://diveintopython.org/") > AttributeError: 'module' object has no attribute 'urlopen' > > What is the proper syntax in version 3? using help() shows that urllib has become a package in v3. The request module looked promising and sure enough >>> import urllib.request as req >>> help(req) shows: urlopen(url, data=None, timeout=) urlretrieve(url, filename=None, reporthook=None, data=None) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From ranceh at gmail.com Sun Apr 24 05:15:43 2011 From: ranceh at gmail.com (Rance Hall) Date: Sat, 23 Apr 2011 22:15:43 -0500 Subject: [Tutor] validating user input In-Reply-To: References: Message-ID: On Sat, Apr 23, 2011 at 6:38 PM, Alan Gauld wrote: > > "Rance Hall" wrote > >> Ok, so I have this code that is working, but does little to validate >> user input and I don't quite yet understand that process yet. >> >> so given the following function: >> >> def buildmenu(menuchoices): >> ? for i, option in enumerate(menuchoices, 1): > > Interesting, I didn't know enumerate could take a second > argument, and help() doesn't mention it eioither.... You > learn something new ... > >> ? ? ? print('%s. %s' % (i, option)) >> ? menuchoice = int(input('\nYour Choice? ')) >> ? return menuchoice-1 >> >> I need help understanding how exactly we validate the input since in >> this case I have no idea how many menu entries there would be. > > But you have just finished enumerating them and I holds > the index of the last item, or in your case the count of > the last item. But even without that you can always > use len() to find out how many menuchoices there are... > I knew about len, but somehow didnt think of it in this context. I didn't know that the last iteration of i and option would still be around. Some loops like that in some languages sort of clean up after themselves. So at the present time I have this: def buildmenu(menuchoices): for i, option in enumerate(menuchoices, 1): print('%s. %s' % (i, option)) validdata = False while not validdata: menuchoice = int(input('\nYour Choice? ')) if menuchoice >= 1 and menuchoice <= i: return menuchoice-1 else: print("Entry not valid") Maybe the while not loop could have been avoided, but it made sense to me, and was consitent with a pattern I used in another section of code. The issue I have now is that the input might not be an integer at all. If it isnt, then the int conversion that is part of the input line will die with a fatal error. So I *think* that I should strip out the int() from the input line and let the input stand on its own. Then as part of the if logic block at a test to see IF a int type conversion would succeed. If so, do it and make sure it is within the range. If no type conversion can happen, then reask the question just as we do if the number is not in the desired range. This was the part I was stuck on. I just didnt know it till I finished this much and still wasn't happy with the results for me to put a finger on exactly what my problem was. Thanks again all. Rance From wescpy at gmail.com Sun Apr 24 06:14:05 2011 From: wescpy at gmail.com (wesley chun) Date: Sat, 23 Apr 2011 21:14:05 -0700 Subject: [Tutor] python2 vs python3 urllib In-Reply-To: <4DB3597B.2020109@ncf.ca> References: <4DB3597B.2020109@ncf.ca> Message-ID: i strongly recommend you consider using the 2to3 tool if porting apps from 2.x to 3.x... it will show you much more than you may think. here's the output from the 2.7 version of 2to3: $ 2to3 test.py RefactoringTool: Skipping implicit fixer: buffer RefactoringTool: Skipping implicit fixer: idioms RefactoringTool: Skipping implicit fixer: set_literal RefactoringTool: Skipping implicit fixer: ws_comma RefactoringTool: Refactored test.py --- test.py (original) +++ test.py (refactored) @@ -1,5 +1,5 @@ -import urllib -sock = urllib.urlopen("http://diveintopython.org/") +import urllib.request, urllib.parse, urllib.error +sock = urllib.request.urlopen("http://diveintopython.org/") htmlSource = sock.read() sock.close() print (htmlSource) RefactoringTool: Files that need to be modified: RefactoringTool: test.py it shows you the diffs, and if you use the -w option, it will overwrite (and backup) the 2.x version. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 ? ? http://corepython.com wesley.chun : wescpy-gmail.com : @wescpy python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From alan.gauld at btinternet.com Sun Apr 24 10:01:59 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sun, 24 Apr 2011 09:01:59 +0100 (BST) Subject: [Tutor] validating user input In-Reply-To: References: Message-ID: <350468.13502.qm@web86708.mail.ird.yahoo.com> > "Rance Hall" wrote > > >But you have just finished enumerating them and I holds > >the index of the last item, or in your case the count of > >the last item. But even without that you can always > >use len() to find out how many menuchoices there are... > > I knew about len, but somehow didnt think of it in this context. > > So at the present time I have this: > > def buildmenu(menuchoices): > for i, option in enumerate(menuchoices, 1): > print('%s. %s' % (i, option)) > validdata = False > while not validdata: instead of validData you could just use while True: since you never change validData anyway and use a return to break out of the loop. > menuchoice = int(input('\nYour Choice? ')) > if menuchoice >= 1 and menuchoice <= i: > return menuchoice-1 > else: > print("Entry not valid") You can tidy up the if test slightly: if ( 1 <= menuchoice <= i): return menuchoice-1 Also why bother with the minus 1? You can use the values 1-n just as easily. > Maybe the while not loop could have been avoided, No, you need some kind of loop to repeat the choice. Otherwise you just exit the program with an error, which seems a bit harsh! > The issue I have now is that the input might not be an integer at all. > If it isnt, then the int conversion that is part of the input line > will die with a fatal error. No, it will throw a ValueError which you can catch and handle exactly as you did above while True try: menuchoice = .... if (...): else.... except ValueError: except other errors HTH, Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From mast.ratna at gmail.com Sun Apr 24 12:28:22 2011 From: mast.ratna at gmail.com (Ratna Banjara) Date: Sun, 24 Apr 2011 16:13:22 +0545 Subject: [Tutor] help with this problem Message-ID: The number 124 has the property that it is the smallest number whose first three multiples contain the digit 2. Observe that 124*1 = 124, 124*2 = 248, 124*3 = 372 and that 124, 248 and 372 each contain the digit 2. It is possible to generalize this property to be the smallest number whose first n multiples each contain the digit 2. Write a function named smallest(n) that returns the smallest number whose first n multiples contain the digit 2. Hint: use modulo base 10 arithmetic to examine digits. Its signature is int smallest(int n) You may assume that such a number is computable on a 32 bit machine, i.e, you do not have to detect integer overflow in your answer. -- Regards, Ratna P Banjara From mast.ratna at gmail.com Sun Apr 24 12:32:32 2011 From: mast.ratna at gmail.com (Ratna Banjara) Date: Sun, 24 Apr 2011 16:17:32 +0545 Subject: [Tutor] How to solve this problem in python? Message-ID: Write a function named countRepresentations that returns the number of ways that an amount of money in rupees can be represented as rupee notes. For this problem we only use rupee notes in denominations of 1, 2, 5, 10 and 20 rupee notes. The signature of the function is: def countRepresentations(int numRupees) For example, countRepresentations(12) should return 15 because 12 rupees can be represented in the following 15 ways. 1. 12 one rupee notes 2. 1 two rupee note plus 10 one rupee notes 3. 2 two rupee notes plus 8 one rupee notes 4. 3 two rupee notes plus 6 one rupee notes 5. 4 two rupee notes plus 4 one rupee notes 6. 5 two rupee notes plus 2 one rupee notes 7. 6 two rupee notes 8. 1 five rupee note plus 7 one rupee notes 9. 1 five rupee note, 1 two rupee note and 5 one rupee notes 10. 1 five rupee note, 2 two rupee notes and 3 one rupee notes 11. 1 five rupee note, 3 two notes and 1 one rupee note 12. 2 five rupee notes and 2 one rupee notes 13. 2 five rupee notes and 1 two rupee note 14. 1 ten rupee note and 2 one rupee notes 15. 1 ten rupee note and 1 two rupee note Hint: Use a nested loop that looks like this. Please fill in the blanks intelligently, i.e. minimize the number of times that the if statement is executed. for (int rupee20=0; rupee20<=__; rupee20++) for (int rupee10=0; rupee10<=__; rupee10++) for (int rupee5=0; rupee5<=__; rupee5++) for (int rupee2=0; rupee2<=__; rupee2++) for (int rupee1=0; rupee1<=__; rupee1++) { if (___) count++ } -- Regards, Ratna P Banjara From daisyk82 at gmail.com Sun Apr 24 14:00:31 2011 From: daisyk82 at gmail.com (Krystal Brosz) Date: Sun, 24 Apr 2011 22:00:31 +1000 Subject: [Tutor] Fwd: Assistance In-Reply-To: References: Message-ID: Hi there, i'm struggling with a program, i feel like i am really close to getting it but i cannot find a way to use the target variables inside of a loop: I'm trying to get the program to ask the user, how many grades are you going to enter. Then i want to work out the average which is fine. But then i want the loop to print out from each grade entered the letter grade as per my if statement. All it does is print the last grade out a certain number of times. Is this even possible or am i overthinking it? Some code is: def main(): gradesEntered = 0 score = 0 numberOfGrades = 0 #get the number of grades being checked numberOfGrades = int(raw_input("Please enter the number of grades:" )) #Begin a 'for' loop to enter each score while numberOfGrades != gradesEntered: grade = int(raw_input("Please enter the grade:" )) gradesEntered += 1 score =+ grade grade = [numberOfGrades] for i in range (numberOfGrades): grade.append(i) print determine_grade(grade,i) #get the grade letter for scores print "the total number of grades entered are:", score print "The average of the scores is:", calc_average print "The number of grades entered is:", gradesEntered def determine_grade(grade,i): if grade >= 90 and grade <= 100: result = 'Your grade is A' elif grade >=80 and grade <= 89: result = 'Your grade is B' elif grade >= 70 and grade <= 79: result = 'Your grade is C' elif grade >=60 and grade <= 69: result = 'Your grade is D' elif grade < 60: result = 'Your grade is F' else: print 'Error: Invalid grade.' return result main() Thank you in advance! -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sun Apr 24 14:12:24 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 24 Apr 2011 22:12:24 +1000 Subject: [Tutor] help with this problem In-Reply-To: References: Message-ID: <4DB413A8.7010405@pearwood.info> Ratna Banjara wrote: > The number 124 has the property that it is the smallest number whose > first three multiples contain the digit 2. Observe that > 124*1 = 124, 124*2 = 248, 124*3 = 372 and that 124, 248 and 372 each > contain the digit 2. It is possible to generalize this property to be > the smallest number whose first n multiples each contain the digit 2. > Write a function named smallest(n) that returns the smallest number > whose first n multiples contain the digit 2. Hint: use modulo base 10 > arithmetic to examine digits. > > Its signature is > int smallest(int n) > > You may assume that such a number is computable on a 32 bit machine, > i.e, you do not have to detect integer overflow in your answer. Do you have a Python question, or would you just like us to do your homework for you? This is a mailing list for learning Python. Please make an attempt to solve the problem, and if you still have trouble, show us what your code is, what error you get, and we'll try to help you with Python. -- Steven From steve at pearwood.info Sun Apr 24 14:20:40 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 24 Apr 2011 22:20:40 +1000 Subject: [Tutor] Fwd: Assistance In-Reply-To: References: Message-ID: <4DB41598.8000109@pearwood.info> Krystal Brosz wrote: > Hi there, > > i'm struggling with a program, i feel like i am really close to getting it > but i cannot find a way to use the target variables inside of a loop: > I'm trying to get the program to ask the user, how many grades are you going > to enter. Then i want to work out the average which is fine. But then i > want the loop to print out from each grade entered the letter grade as per > my if statement. All it does is print the last grade out a certain number > of times. Is this even possible or am i overthinking it? No, you're not over-thinking it, but you do have a few small errors in your code: > Some code is: > def main(): > > gradesEntered = 0 > score = 0 > numberOfGrades = 0 > #get the number of grades being checked > numberOfGrades = int(raw_input("Please enter the number of grades:" )) > > #Begin a 'for' loop to enter each score > while numberOfGrades != gradesEntered: > grade = int(raw_input("Please enter the grade:" )) > gradesEntered += 1 > score =+ grade > grade = [numberOfGrades] Here you ask the user to enter a grade. Suppose they enter (say) 75. Your program will store 75 in grade, and then a moment later over-write that by storing [numberOfGrades] in grade. I believe that what you need is to have a variable "grades" (note plural), and each time around the while loop, you need to append the current grade to the grades list. Then, after you have collected all the grades, you can iterate over the list to get each grade one at a time: for grade in grades: print grade See how you go with that, and don't hesitate to ask if anything is unclear! -- Steven From daisyk82 at gmail.com Sun Apr 24 16:21:24 2011 From: daisyk82 at gmail.com (Krystal Brosz) Date: Mon, 25 Apr 2011 00:21:24 +1000 Subject: [Tutor] Fwd: Assistance Message-ID: Hi Steve, thank you so much for your prompt reply. sorry i'm sending another email as i haven't learnt how to replly to the posts properly yet. I've had a go at implementing a list, but all i get is: It looks as though it is appending all three values together rather than seperatly.. Please enter the number of grades:3 Please enter the grade:60 Please enter the grade:90 Please enter the grade:50 [60, 90, 50] [60, 90, 50] [60, 90, 50] I have added this code: Initialised the list under def main() grades = [] added under the while loop: grades.append(grade) This is now my for statement for i in range (numberOfGrades): determine_grade(grade, i) print grades I feel so close yet so far on this one! I've changed variable, i don't think its appending to the list correctly? Should i be placing the grades.append(grade) under def main()? Although it needs to add to the list after each iteration.... any advice is appreciated. Thanks again, Krystal :) Krystal Brosz wrote: > Hi there,> > i'm struggling with a program, i feel like i am really close to getting it> but i cannot find a way to use the target variables inside of a loop:> I'm trying to get the program to ask the user, how many grades are you going> to enter. Then i want to work out the average which is fine. But then i> want the loop to print out from each grade entered the letter grade as per> my if statement. All it does is print the last grade out a certain number> of times. Is this even possible or am i overthinking it? No, you're not over-thinking it, but you do have a few small errors in your code: > Some code is:> def main():> > gradesEntered = 0> score = 0> numberOfGrades = 0> #get the number of grades being checked> numberOfGrades = int(raw_input("Please enter the number of grades:" ))> > #Begin a 'for' loop to enter each score> while numberOfGrades != gradesEntered:> grade = int(raw_input("Please enter the grade:" ))> gradesEntered += 1> score =+ grade> grade = [numberOfGrades] Here you ask the user to enter a grade. Suppose they enter (say) 75. Your program will store 75 in grade, and then a moment later over-write that by storing [numberOfGrades] in grade. I believe that what you need is to have a variable "grades" (note plural), and each time around the while loop, you need to append the current grade to the grades list. Then, after you have collected all the grades, you can iterate over the list to get each grade one at a time: for grade in grades: print grade See how you go with that, and don't hesitate to ask if anything is unclear! -- Steven -------------- next part -------------- An HTML attachment was scrubbed... URL: From modulok at gmail.com Sun Apr 24 16:25:05 2011 From: modulok at gmail.com (Modulok) Date: Sun, 24 Apr 2011 08:25:05 -0600 Subject: [Tutor] How to solve this problem in python? In-Reply-To: References: Message-ID: Ratna, This list doesn't usually do your homework. However, we will help you with key issues. What have you tried already? Where are you stuck? Is there a certain aspect you don't understand? (Questions like these get lots of help around here. Informally saying "do my homework" generally doesn't.) -Modulok- On 4/24/11, Ratna Banjara wrote: > Write a function named countRepresentations that returns the number > of ways that an amount of money in rupees can be represented as rupee > notes. For this problem we only use rupee notes in denominations of > 1, 2, 5, 10 and 20 rupee notes. > > The signature of the function is: > def countRepresentations(int numRupees) > > For example, countRepresentations(12) should return 15 because 12 > rupees can be represented in the following 15 ways. > 1. 12 one rupee notes > 2. 1 two rupee note plus 10 one rupee notes > 3. 2 two rupee notes plus 8 one rupee notes > 4. 3 two rupee notes plus 6 one rupee notes > 5. 4 two rupee notes plus 4 one rupee notes > 6. 5 two rupee notes plus 2 one rupee notes > 7. 6 two rupee notes > 8. 1 five rupee note plus 7 one rupee notes > 9. 1 five rupee note, 1 two rupee note and 5 one rupee notes > 10. 1 five rupee note, 2 two rupee notes and 3 one rupee notes > 11. 1 five rupee note, 3 two notes and 1 one rupee note > 12. 2 five rupee notes and 2 one rupee notes > 13. 2 five rupee notes and 1 two rupee note > 14. 1 ten rupee note and 2 one rupee notes > 15. 1 ten rupee note and 1 two rupee note > > Hint: Use a nested loop that looks like this. Please fill in the > blanks intelligently, i.e. minimize the number of times that the if > statement is executed. > for (int rupee20=0; rupee20<=__; rupee20++) > for (int rupee10=0; rupee10<=__; rupee10++) > for (int rupee5=0; rupee5<=__; rupee5++) > for (int rupee2=0; rupee2<=__; rupee2++) > for (int rupee1=0; rupee1<=__; rupee1++) > { > if (___) > count++ > } > > -- > Regards, > Ratna P Banjara > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From daisyk82 at gmail.com Sun Apr 24 13:57:45 2011 From: daisyk82 at gmail.com (Krystal Brosz) Date: Sun, 24 Apr 2011 21:57:45 +1000 Subject: [Tutor] Assistance Message-ID: Hi there, i'm struggling with a program, i feel like i am really close to getting it but i cannot find a way to use the target variables inside of a loop: I'm trying to get the program to ask the user, how many grades are you going to enter. Then i want to work out the average which is fine. But then i want the loop to print out from each grade entered the letter grade as per my if statement. All it does is print the last grade out a certain number of times. Is this even possible or am i overthinking it? Some code is: def main(): gradesEntered = 0 score = 0 numberOfGrades = 0 #get the number of grades being checked numberOfGrades = int(raw_input("Please enter the number of grades:" )) #Begin a 'for' loop to enter each score while numberOfGrades != gradesEntered: grade = int(raw_input("Please enter the grade:" )) gradesEntered += 1 score =+ grade grade = [numberOfGrades] for i in range (numberOfGrades): grade.append(i) print determine_grade(grade,i) #get the grade letter for scores print "the total number of grades entered are:", score print "The average of the scores is:", calc_average print "The number of grades entered is:", gradesEntered def determine_grade(grade,i): if grade >= 90 and grade <= 100: result = 'Your grade is A' elif grade >=80 and grade <= 89: result = 'Your grade is B' elif grade >= 70 and grade <= 79: result = 'Your grade is C' elif grade >=60 and grade <= 69: result = 'Your grade is D' elif grade < 60: result = 'Your grade is F' else: print 'Error: Invalid grade.' return result main() Thank you in advance! -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Apr 24 17:38:41 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 24 Apr 2011 16:38:41 +0100 Subject: [Tutor] Assistance References: Message-ID: "Krystal Brosz" wrote > i'm struggling with a program, i feel like i am really close to > getting it You are not far away but you have a few little problems to fix. > but i cannot find a way to use the target variables inside of a > loop: I have no idea what you mean by "target variables". There are no variables in the code called 'target' and I don't understand what target you mean? > def main(): > gradesEntered = 0 > score = 0 > numberOfGrades = 0 > numberOfGrades = int(raw_input("Please enter the number of > grades:" )) > > #Begin a 'for' loop to enter each score The comment is confusing because you actually enter a while loop. Inaccurate comments are worse than no comments at all! > while numberOfGrades != gradesEntered: > grade = int(raw_input("Please enter the grade:" )) > gradesEntered += 1 > score =+ grade Note that += and =+ do different things. I suspect this last line is not doing what you think. Details like this are very important in programming, especially since both forms are valid code, they just do different things! > grade = [numberOfGrades] And I don't know what you think this is doing but it is in fact overwriting the value of grade that the user entered with a list of one element, numberOfGrades. You then throw this away the next time round the loop. > for i in range (numberOfGrades): > grade.append(i) > print determine_grade(grade,i) Now you append i to the list containing numberOfGrades.... So if the user said they would have 3 grades you wind up with grade being equal to [3,0,1,2] Which is almost certainly not what you want? You also pass this list to determine_grade which expects a number rather than a list so will always print an error I suspect. Although I'd also expect it to throw an NameError exception since result will not be defined... Are you sure this is the actual code you are running? > #get the grade letter for scores > print "the total number of grades entered are:", score > print "The average of the scores is:", calc_average > print "The number of grades entered is:", gradesEntered So ths prints the value of yourt last grade multiplied by +1 followed by a calc_average which is not actually set anwthere in your code. It then prints gradesEntered which should be the same as numberOfGrades. > def determine_grade(grade,i): I'm not sure why you have i in the parameter list? You don't do anything with it. > if grade >= 90 and grade <= 100: > result = 'Your grade is A' > elif grade >=80 and grade <= 89: > result = 'Your grade is B' > elif grade >= 70 and grade <= 79: > result = 'Your grade is C' > elif grade >=60 and grade <= 69: > result = 'Your grade is D' > elif grade < 60: > result = 'Your grade is F' > else: > print 'Error: Invalid grade.' > return result If you reach the last 'else', result will not have been assigned and yet, you try to return it. I'd expect that to throw an error. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From malcolm.newsome at gmail.com Mon Apr 25 04:52:42 2011 From: malcolm.newsome at gmail.com (Malcolm Newsome) Date: Sun, 24 Apr 2011 21:52:42 -0500 Subject: [Tutor] Virtualenv Error Message-ID: <006501cc02f3$d94ef280$8becd780$@gmail.com> Hey All, Does anyone have any experience creating virtualenvs that can assist me with this error. I'm running windows 7, python 2.7.1 and virtualenv 1.6. I installed virtualenv using easy_install and there were no errors. I get the following error when trying to create a virtualenv. Any assistance is appreciated! Thanks! Microsoft Windows [Version 6.1.7601] Copyright (c) 2009 Microsoft Corporation. All rights reserved. C:\Users\Malcolm>virtualenv malcery New python executable in malcery\Scripts\python.exe Installing setuptools................done. Complete output from command C:\Users\Malcolm\malcery\Scripts\python.exe C:\Users\Malcolm\mal...sy_install-script.py C:\Users\Malcolm\Pyt...pport\pip-1.0.tar.gz: Traceback (most recent call last): File "C:\Users\Malcolm\malcery\Scripts\easy_install-script.py", line 8, in load_entry_point('setuptools==0.6c11', 'console_scripts', 'easy_install')() File "C:\Users\Malcolm\malcery\lib\site-packages\setuptools-0.6c11-py2.7.egg\pkg_ resources.py", line 318, in load_entry_point return get_distribution(dist).load_entry_point(group, name) File "C:\Users\Malcolm\malcery\lib\site-packages\setuptools-0.6c11-py2.7.egg\pkg_ resources.py", line 2221, in load_entry_point return ep.load() File "C:\Users\Malcolm\malcery\lib\site-packages\setuptools-0.6c11-py2.7.egg\pkg_ resources.py", line 1954, in load entry = __import__(self.module_name, globals(),globals(), ['__name__']) File "C:\Users\Malcolm\malcery\lib\site-packages\setuptools-0.6c11-py2.7.egg\setu ptools\command\easy_install.py", line 21, in File "C:\Users\Malcolm\malcery\lib\site-packages\setuptools-0.6c11-py2.7.egg\setu ptools\package_index.py", line 2, in File "C:\Users\Malcolm\Python27\lib\urllib2.py", line 94, in import httplib File "C:\Users\Malcolm\Python27\lib\httplib.py", line 71, in import socket File "C:\Users\Malcolm\Python27\lib\socket.py", line 47, in import _socket ImportError: No module named _socket ---------------------------------------- Traceback (most recent call last): File "C:\Users\Malcolm\Python27\Scripts\virtualenv-script.py", line 8, in load_entry_point('virtualenv==1.6', 'console_scripts', 'virtualenv')() File "C:\Users\Malcolm\Python27\lib\site-packages\virtualenv-1.6-py2.7.egg\virtua lenv.py", line 745, in main prompt=options.prompt) File "C:\Users\Malcolm\Python27\lib\site-packages\virtualenv-1.6-py2.7.egg\virtua lenv.py", line 845, in create_environment install_pip(py_executable) File "C:\Users\Malcolm\Python27\lib\site-packages\virtualenv-1.6-py2.7.egg\virtua lenv.py", line 602, in install_pip filter_stdout=_filter_setup) File "C:\Users\Malcolm\Python27\lib\site-packages\virtualenv-1.6-py2.7.egg\virtua lenv.py", line 813, in call_subprocess % (cmd_desc, proc.returncode)) OSError: Command C:\Users\Malcolm\malcery\Scripts\python.exe C:\Users\Malcolm\mal...sy_install-script.py C:\Users\Malcolm\Pyt...pport\pip-1.0.tar.gz failed with error code 1 C:\Users\Malcolm> -------------- next part -------------- An HTML attachment was scrubbed... URL: From jzacsh at gmail.com Mon Apr 25 05:29:11 2011 From: jzacsh at gmail.com (Jonathan Zacsh) Date: Sun, 24 Apr 2011 23:29:11 -0400 Subject: [Tutor] Virtualenv Error In-Reply-To: <006501cc02f3$d94ef280$8becd780$@gmail.com> References: <006501cc02f3$d94ef280$8becd780$@gmail.com> Message-ID: On Sun, Apr 24, 2011 at 22:52, Malcolm Newsome wrote: > Hey All, > > > > Does anyone have any experience creating virtualenvs that can assist me with > this error.? I?m running windows 7, python 2.7.1 and virtualenv 1.6. > > > > I installed virtualenv using easy_install and there were no errors.? I get > the following error when trying to create a virtualenv. > > > > Any assistance is appreciated! Thanks! > > > > > > Microsoft Windows [Version 6.1.7601] > > Copyright (c) 2009 Microsoft Corporation.? All rights reserved. > > > > C:\Users\Malcolm>virtualenv malcery > > New python executable in malcery\Scripts\python.exe > > Installing setuptools................done. > > ? Complete output from command C:\Users\Malcolm\malcery\Scripts\python.exe > C:\Users\Malcolm\mal...sy_install-script.py > C:\Users\Malcolm\Pyt...pport\pip-1.0.tar.gz: > > ? Traceback (most recent call last): > > ? File "C:\Users\Malcolm\malcery\Scripts\easy_install-script.py", line 8, in > > > ??? load_entry_point('setuptools==0.6c11', 'console_scripts', > 'easy_install')() > > ? File > "C:\Users\Malcolm\malcery\lib\site-packages\setuptools-0.6c11-py2.7.egg\pkg_resources.py", > line 318, in load_entry_point > > ??? return get_distribution(dist).load_entry_point(group, name) > > ? File > "C:\Users\Malcolm\malcery\lib\site-packages\setuptools-0.6c11-py2.7.egg\pkg_resources.py", > line 2221, in load_entry_point > > ??? return ep.load() > > ? File > "C:\Users\Malcolm\malcery\lib\site-packages\setuptools-0.6c11-py2.7.egg\pkg_resources.py", > line 1954, in load > > ??? entry = __import__(self.module_name, globals(),globals(), ['__name__']) > > ? File > "C:\Users\Malcolm\malcery\lib\site-packages\setuptools-0.6c11-py2.7.egg\setuptools\command\easy_install.py", > line 21, in > > > > ? File > "C:\Users\Malcolm\malcery\lib\site-packages\setuptools-0.6c11-py2.7.egg\setuptools\package_index.py", > line 2, in > > ? File "C:\Users\Malcolm\Python27\lib\urllib2.py", line 94, in > > ??? import httplib > > ? File "C:\Users\Malcolm\Python27\lib\httplib.py", line 71, in > > ??? import socket > > ? File "C:\Users\Malcolm\Python27\lib\socket.py", line 47, in > > ??? import _socket > > ImportError: No module named _socket > > ---------------------------------------- > > Traceback (most recent call last): > > ? File "C:\Users\Malcolm\Python27\Scripts\virtualenv-script.py", line 8, in > > > ??? load_entry_point('virtualenv==1.6', 'console_scripts', 'virtualenv')() > > ? File > "C:\Users\Malcolm\Python27\lib\site-packages\virtualenv-1.6-py2.7.egg\virtualenv.py", > line 745, in main > > ??? prompt=options.prompt) > > ? File > "C:\Users\Malcolm\Python27\lib\site-packages\virtualenv-1.6-py2.7.egg\virtualenv.py", > line 845, in create_environment > > ??? install_pip(py_executable) > > ? File > "C:\Users\Malcolm\Python27\lib\site-packages\virtualenv-1.6-py2.7.egg\virtualenv.py", > line 602, in install_pip > > ??? filter_stdout=_filter_setup) > > ? File > "C:\Users\Malcolm\Python27\lib\site-packages\virtualenv-1.6-py2.7.egg\virtualenv.py", > line 813, in call_subprocess > > ??? % (cmd_desc, proc.returncode)) > > OSError: Command C:\Users\Malcolm\malcery\Scripts\python.exe > C:\Users\Malcolm\mal...sy_install-script.py > C:\Users\Malcolm\Pyt...pport\pip-1.0.tar.gz failed with error code 1 > > > > C:\Users\Malcolm> > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > Have you tried using pip instead of easy_install? Its supposed to the "newer, better" approach. http://www.pip-installer.org/ I don't know that it matters. I'm new to python myself. -- Jonathan Zacsh From eq742 at ncf.ca Mon Apr 25 03:14:52 2011 From: eq742 at ncf.ca (pierre dagenais) Date: Sun, 24 Apr 2011 21:14:52 -0400 Subject: [Tutor] python2 vs python3 urllib In-Reply-To: <4DB3597B.2020109@ncf.ca> References: <4DB3597B.2020109@ncf.ca> Message-ID: <4DB4CB0C.3050404@ncf.ca> On 11-04-23 06:58 PM, pierre dagenais wrote: > The following code works as expected with python version 2.6.5, but > with version 3.1.2 I get the following error: > > pierre:/MyCode/mesProjets$ py3 test.py > > Traceback (most recent call last): > File "test.py", line 3, in > sock = urllib.urlopen("http://diveintopython.org/") > AttributeError: 'module' object has no attribute 'urlopen' > > > > > The code: > > #example 8.5 of diveintopython.org/ > import urllib > sock = urllib.urlopen("http://diveintopython.org/") > htmlSource = sock.read() > sock.close() > print (htmlSource) > > What is the proper syntax in version 3? > > Thank you, > Your help is much appreciated. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Thank you everybody, The short answer was of course: import urllib.request instead of : import urllib I realize I'm still confused about packages, libraries, modules, classes, etc... Right now they're all more or less the same to me. I've got some reading to do. Thanks again, Pierre From alan.gauld at btinternet.com Mon Apr 25 09:31:25 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 25 Apr 2011 08:31:25 +0100 Subject: [Tutor] Virtualenv Error References: <003d01cbf70b$4b7d87d0$e2789770$@gmail.com> Message-ID: "Malcolm Newsome" wrote > I installed virtualenv and am getting this error when trying to > create one. > I'm running Windows 7. Can anyone help?? I've no idea what virtuialenv is or does but it doesn't sound like a Python beginners questuion.... You might get more success asking on the general python mailing list/nesgroup comp.lang.python. Or even better on a virtualenv list or forum is such a thing exists. Alan G. From gollumgreg407366 at gmail.com Mon Apr 25 09:56:39 2011 From: gollumgreg407366 at gmail.com (Greg Nielsen) Date: Mon, 25 Apr 2011 02:56:39 -0500 Subject: [Tutor] Unbound Method Error Message-ID: Because of the limited Python 3 support, I've decided to attempt to push my over 600 lines of code back to Python 2.6. Surprisingly, it worked well for the most part, except for the following section of code. crash = pygame.sprite.spritecollide(playerCar, computerSprites, False) if crash: for BlueCarSprite in crash: redracersprites26.BlueCarSprite.collide(BlueCarSprite, playerCar) for GreenCarSprite in crash: redracersprites26.GreenCarSprite.collide(GreenCarSprite, playerCar) for TruckSprite in crash: redracersprites26.TruckSprite.collide(TruckSprite, playerCar) This is a perfectly good piece of code in Python 3.1.3 which checks to see if a user controlled sprite collides with one or more computer controlled sprites, then passes the data off to the proper class method to handle the details. In Python 2.6.6, this section of code returns the following error TypeError: unbound method collide() must be called with BlueCarSprite instance as first argument (got GreenCarSprite instance instead) I have several questions as to what exactly is going on and what I should do, if you have any sort of answer to any of these questions, please respond. 1) What exactly is an "unbound method" error? I have been programming (in other languages) for several years on and off and have never heard of something like this. 2) What changes between 3.1.3 and 2.6.6 that makes this section of code not work? My best guess is that I'm missing something that lets the computer know that BlueCarSprite is an object type, but even if that's true, I wouldn't know what to do to fix it. 3) What would be a legit fix to my code to make it run? Sure, I guess I could write a Collide class and use that rather than my collide method, or perhaps a class that could act as a middle man between bits of code that I know work, but I know that there has to be a better way to fix this. Thank you to any and all who take the time to read this message, and especially to those who respond with any sort of feedback Greg -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Mon Apr 25 10:22:46 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 25 Apr 2011 18:22:46 +1000 Subject: [Tutor] Unbound Method Error In-Reply-To: References: Message-ID: <4DB52F56.30500@pearwood.info> Greg Nielsen wrote: > In Python 2.6.6, this section of code returns the following error > > TypeError: unbound method collide() must be called with BlueCarSprite > instance as first argument (got GreenCarSprite instance instead) Please copy and paste the actual traceback, as that will show the *actual* line of code (and not just "this section"). > 1) What exactly is an "unbound method" error? I have been programming (in > other languages) for several years on and off and have never heard of > something like this. When you retrieve an attribute from an instance: instance.name Python looks up "name" on the instance, then class, then any parent classes, etc. The same mechanism is used for methods: the method object just happens to be callable. When you retrieve instance.method, you get back a method-wrapper object which wraps the function you defined in the class. The method-wrapper ensures that the special "self" argument is supplied, so that this syntax: instance.method(x, y, z) calls the actual function object like this: type(instance).method(instance, x, y, z) Some people find it hard to wrap their head around this, but remember that you have defined an ordinary function inside the class, using the same def key word that gets used for making other functions. You write a function, and the class wraps it in code to make it a method. Now, when you call instance.method, the object you get back is a "bound method", so-called because it is bound to an instance and can supply the self argument. But when you call the method on the class object instead: Class.method you get an *unbound* method, which is still a wrapper around the actual function you defined. Remember the parameter list you defined in the function? It starts with self. If you call it via the instance, you get a bound method and self if automatically provided. But if you call it from the class, there is no instance supplied and you have to supply it by hand. You can easily experiment with this using built-ins such as str: >>> "spam".upper >>> "spam".upper() # self is set to "spam" 'SPAM' >>> str.upper >>> str.upper() Traceback (most recent call last): File "", line 1, in TypeError: descriptor 'upper' of 'str' object needs an argument >>> str.upper("spam") 'SPAM' Some of the implementation details (such as error messages) may differ between methods in Python classes and methods in built-in types, but the broad details are the same. > 2) What changes between 3.1.3 and 2.6.6 that makes this section of code not > work? My best guess is that I'm missing something that lets the computer > know that BlueCarSprite is an object type, but even if that's true, I > wouldn't know what to do to fix it. I suspect that you're running into a small semantic difference between Python 2 and 3. In Python 2, method objects know what their type is, and they enforce that the self argument has the same type. In Python 3, unbound methods are gone, and instance you get an ordinary function. This ordinary function has no clue about what class it is attached to, and so it can't enforce that the self parameter has the right class. You can pass anything that works. > 3) What would be a legit fix to my code to make it run? Sure, I guess I > could write a Collide class and use that rather than my collide method, or > perhaps a class that could act as a middle man between bits of code that I > know work, but I know that there has to be a better way to fix this. Perhaps you can make GreenCarSprite a subclass of BlueCarSprite, or both Blue* and Green* to be subclasses of a CarSprite class that owns all the methods. But without knowing more about your code, it's hard to say exactly. -- Steven From gollumgreg407366 at gmail.com Mon Apr 25 11:36:33 2011 From: gollumgreg407366 at gmail.com (Greg Nielsen) Date: Mon, 25 Apr 2011 04:36:33 -0500 Subject: [Tutor] Unbound Method Error In-Reply-To: <4DB52F56.30500@pearwood.info> References: <4DB52F56.30500@pearwood.info> Message-ID: First and foremost, thank you Steven for your quick and well written response. It means a lot to me that you took the time out of your day to answer my question, and it has really helped me better understand what it going on. So the full trace back for my error is as follows: Traceback (most recent call last): File "C:\Users\Greg\Documents\NetBeansProjects\Red Racer 26\src\redracer26.py", line 19, in main() File "C:\Users\Greg\Documents\NetBeansProjects\Red Racer 26\src\redracer26.py", line 16, in main redracerstates26.game(startLives) File "C:\Users\Greg\Documents\NetBeansProjects\Red Racer 26\src\redracerstates26.py", line 87, in game redracersprites26.BlueCarSprite.collide(BlueCarSprite, playerCar) TypeError: unbound method collide() must be called with BlueCarSprite instance as first argument (got GreenCarSprite instance instead) After reading through your explanation of unbound methods (and wrapping my head around the concept), I came up with a quick fix that lead to a new issue in my code. Here is what I think should work: crash = pygame.sprite.spritecollide(playerCar, computerSprites, False) if crash: for BlueCarSprite in crash: redracersprites26.BlueCarSprite.collide(crash, playerCar) for GreenCarSprite in crash: redracersprites26.GreenCarSprite.collide(crash, playerCar) for TruckSprite in crash: redracersprites26.TruckSprite.collide(crash, playerCar) However, the spritecollide method returns a list, which my collide method isn't expecting. The list should only contain the name of the sprite the player hit. In Python 3, the method would just pull the variable out of the list and work with it, but in Python 2, it's not expecting a list, causing an error similar to the one seen previously: Traceback (most recent call last): File "C:\Users\Greg\Documents\NetBeansProjects\Red Racer 26\src\redracer26.py", line 19, in main() File "C:\Users\Greg\Documents\NetBeansProjects\Red Racer 26\src\redracer26.py", line 16, in main redracerstates26.game(startLives) File "C:\Users\Greg\Documents\NetBeansProjects\Red Racer 26\src\redracerstates26.py", line 87, in game redracersprites26.BlueCarSprite.collide(crash, playerCar) TypeError: unbound method collide() must be called with BlueCarSprite instance as first argument (got list instance instead) So what really has to happen now (I think) is that the list needs to be unpacked into just a simple variable containing the name of the sprite in question. This way the method receives the name of the instance (self) in the way it was expecting to receive it. In your opinion, should I unpacked the list before passing the data into the method, or attempt to define "self" as a list? Is the latter even possible? I would think it would have to be because otherwise Python could pick a variable type which you don't want or aren't expecting it to pick and need to force it to take a certain type of input. And thank you for pointing out the fact I could just make a CarSprite class and have subclasses (basically just a different sprite image) work with the details. You just removed over 150 lines of redundant code from my program. And once again, thank you Steven for taking the time to help me better understand the whole unbound method concept. Greg -------------- next part -------------- An HTML attachment was scrubbed... URL: From samudhio at gmail.com Mon Apr 25 14:49:02 2011 From: samudhio at gmail.com (Edgar Almonte) Date: Mon, 25 Apr 2011 08:49:02 -0400 Subject: [Tutor] voluntary work Message-ID: someboy have some project where can take a very noob and with very little knowledgement of python in the arm where i can work voluntary of course ? the thing is i want learn i read a bit and do some exercises but i am the kind of ppl that need saw the path that will walk so need a route and a little of guide to keep going , thanks pd: i ask the same question at #python in freenode that somebody recommend me the book http://learnpythonthehardway.org/static/LearnPythonTheHardWay.pdf and i check it it righ now. From ramit.prasad at jpmchase.com Mon Apr 25 16:59:24 2011 From: ramit.prasad at jpmchase.com (Prasad, Ramit) Date: Mon, 25 Apr 2011 10:59:24 -0400 Subject: [Tutor] Assistance In-Reply-To: References: Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA2AD9109@EMARC112VS01.exchad.jpmchase.net> >> while numberOfGrades != gradesEntered: >> grade = int(raw_input("Please enter the grade:" )) >> gradesEntered += 1 >> score =+ grade >Note that += and =+ do different things. I suspect this last line is >not doing what you think. Details like this are very important in >programming, especially since both forms are valid code, they >just do different things! Could you please expand on that? From playing around on the shell it looks like 'B =+ 2 ' always sets B to 2. At first, I thought it was taking it as 'B=None+2' but that gave me the error "TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'" So what is actually going on behind the scenes? Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase & Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase & Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities. From ramit.prasad at jpmchase.com Mon Apr 25 17:17:20 2011 From: ramit.prasad at jpmchase.com (Prasad, Ramit) Date: Mon, 25 Apr 2011 11:17:20 -0400 Subject: [Tutor] Unbound Method Error In-Reply-To: References: <4DB52F56.30500@pearwood.info> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA2AD919B@EMARC112VS01.exchad.jpmchase.net> Disclaimer: I have no knowledge of PyGame. I think your original is a lack of checking types. You are calling BlueCar/GreenCar/Truck.collide regardless of the car type. If you pass a TruckSprite to BlueCarSprite.collide it makes sense (without knowledge of PyGame) that it would fail because it expects a BlueCarSprite not a TruckSprite. You do: crash = pygame.sprite.spritecollide(playerCar, computerSprites, False) if crash: for BlueCarSprite in crash: # This loops through crash redracersprites26.BlueCarSprite.collide(crash, playerCar) for GreenCarSprite in crash: # This loops through crash again redracersprites26.GreenCarSprite.collide(crash, playerCar) for TruckSprite in crash: # This loops through crash for the third time redracersprites26.TruckSprite.collide(crash, playerCar) There are two other problems with this: 1) this is sending the entire list of collisions to each of these functions. 2) The way you are looping seems odd to me. I would think you want something more like the following (UNTESTED): crash = pygame.sprite.spritecollide(playerCar, computerSprites, False) if crash: for car in crash: if isinstance(car, BlueCar): redracersprices26.BlueCarSprite.collide(car, playerCar) if isinstance(car, GreenCar): redracersprices26.GreenCarSprite.collide(car, playerCar) if isinstance(car, TruckCar): redracersprices26.TruckCarSprite.collide(car, playerCar) If you really want to call all 3 collide statements, then just remove the 'if isinstance(car, \w*):' line and it will call the collide for each. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 From: tutor-bounces+ramit.prasad=jpmchase.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmchase.com at python.org] On Behalf Of Greg Nielsen Sent: Monday, April 25, 2011 4:37 AM To: Steven D'Aprano Cc: tutor at python.org Subject: Re: [Tutor] Unbound Method Error First and foremost, thank you Steven for your quick and well written response. It means a lot to me that you took the time out of your day to answer my question, and it has really helped me better understand what it going on. So the full trace back for my error is as follows: Traceback (most recent call last): File "C:\Users\Greg\Documents\NetBeansProjects\Red Racer 26\src\redracer26.py", line 19, in main() File "C:\Users\Greg\Documents\NetBeansProjects\Red Racer 26\src\redracer26.py", line 16, in main redracerstates26.game(startLives) File "C:\Users\Greg\Documents\NetBeansProjects\Red Racer 26\src\redracerstates26.py", line 87, in game redracersprites26.BlueCarSprite.collide(BlueCarSprite, playerCar) TypeError: unbound method collide() must be called with BlueCarSprite instance as first argument (got GreenCarSprite instance instead) After reading through your explanation of unbound methods (and wrapping my head around the concept), I came up with a quick fix that lead to a new issue in my code. Here is what I think should work: crash = pygame.sprite.spritecollide(playerCar, computerSprites, False) if crash: for BlueCarSprite in crash: redracersprites26.BlueCarSprite.collide(crash, playerCar) for GreenCarSprite in crash: redracersprites26.GreenCarSprite.collide(crash, playerCar) for TruckSprite in crash: redracersprites26.TruckSprite.collide(crash, playerCar) However, the spritecollide method returns a list, which my collide method isn't expecting. The list should only contain the name of the sprite the player hit. In Python 3, the method would just pull the variable out of the list and work with it, but in Python 2, it's not expecting a list, causing an error similar to the one seen previously: Traceback (most recent call last): File "C:\Users\Greg\Documents\NetBeansProjects\Red Racer 26\src\redracer26.py", line 19, in main() File "C:\Users\Greg\Documents\NetBeansProjects\Red Racer 26\src\redracer26.py", line 16, in main redracerstates26.game(startLives) File "C:\Users\Greg\Documents\NetBeansProjects\Red Racer 26\src\redracerstates26.py", line 87, in game redracersprites26.BlueCarSprite.collide(crash, playerCar) TypeError: unbound method collide() must be called with BlueCarSprite instance as first argument (got list instance instead) So what really has to happen now (I think) is that the list needs to be unpacked into just a simple variable containing the name of the sprite in question. This way the method receives the name of the instance (self) in the way it was expecting to receive it. In your opinion, should I unpacked the list before passing the data into the method, or attempt to define "self" as a list? Is the latter even possible? I would think it would have to be because otherwise Python could pick a variable type which you don't want or aren't expecting it to pick and need to force it to take a certain type of input. And thank you for pointing out the fact I could just make a CarSprite class and have subclasses (basically just a different sprite image) work with the details. You just removed over 150 lines of redundant code from my program. And once again, thank you Steven for taking the time to help me better understand the whole unbound method concept. Greg This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase & Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase & Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities. -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Mon Apr 25 17:41:41 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Mon, 25 Apr 2011 10:41:41 -0500 Subject: [Tutor] Assistance In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA2AD9109@EMARC112VS01.exchad.jpmchase.net> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA2AD9109@EMARC112VS01.exchad.jpmchase.net> Message-ID: On Mon, Apr 25, 2011 at 9:59 AM, Prasad, Ramit wrote: > >> while numberOfGrades != gradesEntered: > >> grade = int(raw_input("Please enter the grade:" )) > >> gradesEntered += 1 > >> score =+ grade > > >Note that += and =+ do different things. I suspect this last line is > >not doing what you think. Details like this are very important in > >programming, especially since both forms are valid code, they > >just do different things! > > Could you please expand on that? From playing around on the shell it looks > like 'B =+ 2 ' always sets B to 2. At first, I thought it was taking it as > 'B=None+2' but that gave me the error "TypeError: unsupported operand > type(s) for +: 'NoneType' and 'int'" So what is actually going on behind the > scenes? > > Ramit > += is a single operator that is equivalent to typing b = b + 2 =+ is two operators put together: b+=2 is equivalent to b += 2 is equivalent to b = b + 2 b=+2 is equivalent to b = +2 is equivalent to b = 2 b = + 2 is legal syntax, while b + = 2 is not. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Apr 25 19:33:07 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 25 Apr 2011 18:33:07 +0100 Subject: [Tutor] voluntary work References: Message-ID: "Edgar Almonte" wrote > is i want learn i read a bit and do some exercises but i am the kind > of ppl that need saw the path that will walk so > need a route and a little of guide to keep going , Have you looked at the python web site? There is a whole section dedicated to tutorials for people who have never programmed before. Take a look at a few and choose the one you like - ie the one that aseems to make most sense to you.. HTH, From waynejwerner at gmail.com Mon Apr 25 20:19:35 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Mon, 25 Apr 2011 13:19:35 -0500 Subject: [Tutor] Assistance In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA2AD96BC@EMARC112VS01.exchad.jpmchase.net> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA2AD9109@EMARC112VS01.exchad.jpmchase.net> <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA2AD96BC@EMARC112VS01.exchad.jpmchase.net> Message-ID: On Mon, Apr 25, 2011 at 1:13 PM, Prasad, Ramit wrote: > b = + 2 is legal syntax, while b + = 2 is not. > > Why do you 'b += 2' is not legal syntax? It seems to work in python 2.x and > 3.x. Is this deprecated or looked down upon? Is it better to use 'b = b + 2' > ? > > For the +2, it did not even occur to me that it was referring to a positive > number and not some kind of addition/concatenation. Whoops! b +space= 2, where there is a space between + and = += is perfectly legal, and (I would argue) the better choice. -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmchase.com Mon Apr 25 20:13:11 2011 From: ramit.prasad at jpmchase.com (Prasad, Ramit) Date: Mon, 25 Apr 2011 14:13:11 -0400 Subject: [Tutor] Assistance In-Reply-To: References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA2AD9109@EMARC112VS01.exchad.jpmchase.net> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA2AD96BC@EMARC112VS01.exchad.jpmchase.net> b = + 2 is legal syntax, while b + = 2 is not. Why do you 'b += 2' is not legal syntax? It seems to work in python 2.x and 3.x. Is this deprecated or looked down upon? Is it better to use 'b = b + 2' ? For the +2, it did not even occur to me that it was referring to a positive number and not some kind of addition/concatenation. Whoops! Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase & Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase & Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities. From samudhio at gmail.com Mon Apr 25 20:41:38 2011 From: samudhio at gmail.com (Edgar Almonte) Date: Mon, 25 Apr 2011 14:41:38 -0400 Subject: [Tutor] voluntary work In-Reply-To: References: Message-ID: Thanks , but i still are looking for some small project to get work that let me learn in a more interesting way. i not that kind of person that can start app from zero so is hard for me learn new things without some kind of goal. thanks again. On Mon, Apr 25, 2011 at 1:33 PM, Alan Gauld wrote: > > "Edgar Almonte" wrote > >> is i want learn i read a bit and do some exercises but i am the kind >> of ppl that need saw the path that will walk so >> need a route and a little of guide to keep going , > > Have you looked at the python web site? There is a > whole section dedicated to tutorials for people who > have never programmed before. Take a look at a few > and choose the one you like - ie the one that aseems > to make most sense to you.. > > HTH, > > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From wolf.halton at gmail.com Mon Apr 25 20:42:36 2011 From: wolf.halton at gmail.com (Wolf Halton) Date: Mon, 25 Apr 2011 14:42:36 -0400 Subject: [Tutor] voluntary work In-Reply-To: References: Message-ID: "Learn Python the Hard Way" is pretty cool. I am always looking for books that lay it out well. Thanks for mentioning it, and good luck with your studies. I find that having a project that is a little beyond me helps me get better at coding. -Wolf On Mon, Apr 25, 2011 at 1:33 PM, Alan Gauld wrote: > > "Edgar Almonte" wrote > > > is i want learn i read a bit and do some exercises but i am the kind >> of ppl that need saw the path that will walk so >> need a route and a little of guide to keep going , >> > > Have you looked at the python web site? There is a > whole section dedicated to tutorials for people who > have never programmed before. Take a look at a few > and choose the one you like - ie the one that aseems > to make most sense to you.. > > HTH, > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- This Apt Has Super Cow Powers - http://sourcefreedom.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From rafadurancastaneda at gmail.com Mon Apr 25 21:09:02 2011 From: rafadurancastaneda at gmail.com (=?UTF-8?B?UmFmYWVsIER1csOhbiBDYXN0YcOxZWRh?=) Date: Mon, 25 Apr 2011 21:09:02 +0200 Subject: [Tutor] voluntary work In-Reply-To: References: Message-ID: <4DB5C6CE.8020702@gmail.com> I recommend you visit www.pythonchallenge.com On 25/04/11 20:42, Wolf Halton wrote: > "Learn Python the Hard Way" is pretty cool. I am always looking for > books that lay it out well. Thanks for mentioning it, and good luck > with your studies. I find that having a project that is a little > beyond me helps me get better at coding. > -Wolf > > On Mon, Apr 25, 2011 at 1:33 PM, Alan Gauld > wrote: > > > "Edgar Almonte" > > wrote > > > is i want learn i read a bit and do some exercises but i am > the kind > of ppl that need saw the path that will walk so > need a route and a little of guide to keep going , > > > Have you looked at the python web site? There is a > whole section dedicated to tutorials for people who > have never programmed before. Take a look at a few > and choose the one you like - ie the one that aseems > to make most sense to you.. > > HTH, > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > > > -- > This Apt Has Super Cow Powers - http://sourcefreedom.com > > > _______________________________________________ > 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 gollumgreg407366 at gmail.com Mon Apr 25 22:19:23 2011 From: gollumgreg407366 at gmail.com (Greg Nielsen) Date: Mon, 25 Apr 2011 15:19:23 -0500 Subject: [Tutor] Unbound Method Error In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA2AD919B@EMARC112VS01.exchad.jpmchase.net> References: <4DB52F56.30500@pearwood.info> <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA2AD919B@EMARC112VS01.exchad.jpmchase.net> Message-ID: Ramit, First, thank you for your input and insight into my problem, I believe that the code you came up with should not only be more efficient, but also clear up the last of my issues. I just have a quick question on the isinstance command you called. How exactly do I get the code to recognize it as a class I wrote sitting in an imported library file? I would guess that it would look sort of like this: if crash: for car in crash: if isinstance(car, redracersprites26.BlueCarSprite()): redracersprites26.BlueCarSprite.collide(car, playerCar) However, worded as it the follow error and call back happens: Traceback (most recent call last): File "C:\Users\Greg\Documents\NetBeansProjects\Red Racer 26\src\redracer26.py", line 19, in main() File "C:\Users\Greg\Documents\NetBeansProjects\Red Racer 26\src\redracer26.py", line 16, in main redracerstates26.game(startLives) File "C:\Users\Greg\Documents\NetBeansProjects\Red Racer 26\src\redracerstates26.py", line 87, in game if isinstance(car, redracersprites26.BlueCarSprite()): TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types I must be using the wrong syntax in the second argument. I think I should be able to find the documentation for this (extremely cool) method you showed me, but if you know the proper way to cite my object, could you send me what you think will work. This way I can have something to double check my work against if I don't get it right first time round. Thank you again for your time and assistance Ramit. Greg -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmchase.com Mon Apr 25 22:39:02 2011 From: ramit.prasad at jpmchase.com (Prasad, Ramit) Date: Mon, 25 Apr 2011 16:39:02 -0400 Subject: [Tutor] Unbound Method Error In-Reply-To: References: <4DB52F56.30500@pearwood.info> <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA2AD919B@EMARC112VS01.exchad.jpmchase.net> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA2AD9ABB@EMARC112VS01.exchad.jpmchase.net> Hi Greg, You must use the class definition not an instance/object of it. If the class is called CarClass from some_lib_a.sub_lib_b import CarClass [...] isinstance(car, CarClass) OR import some_lib_a [...] isinstance(car, some_lib_a.sub_lib_b.CarClass) The following does NOT work: isinstance(car, CarClass()) if you want to check multiple classes use isinstance(car, (Class1, Class2)) Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 From: Greg Nielsen [mailto:gollumgreg407366 at gmail.com] Sent: Monday, April 25, 2011 3:19 PM To: Prasad, Ramit Cc: Steven D'Aprano; tutor at python.org Subject: Re: [Tutor] Unbound Method Error Ramit, First, thank you for your input and insight into my problem, I believe that the code you came up with should not only be more efficient, but also clear up the last of my issues. I just have a quick question on the isinstance command you called. How exactly do I get the code to recognize it as a class I wrote sitting in an imported library file? I would guess that it would look sort of like this: if crash: for car in crash: if isinstance(car, redracersprites26.BlueCarSprite()): redracersprites26.BlueCarSprite.collide(car, playerCar) However, worded as it the follow error and call back happens: Traceback (most recent call last): File "C:\Users\Greg\Documents\NetBeansProjects\Red Racer 26\src\redracer26.py", line 19, in main() File "C:\Users\Greg\Documents\NetBeansProjects\Red Racer 26\src\redracer26.py", line 16, in main redracerstates26.game(startLives) File "C:\Users\Greg\Documents\NetBeansProjects\Red Racer 26\src\redracerstates26.py", line 87, in game if isinstance(car, redracersprites26.BlueCarSprite()): TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types I must be using the wrong syntax in the second argument. I think I should be able to find the documentation for this (extremely cool) method you showed me, but if you know the proper way to cite my object, could you send me what you think will work. This way I can have something to double check my work against if I don't get it right first time round. Thank you again for your time and assistance Ramit. Greg This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase & Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase & Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities. -------------- next part -------------- An HTML attachment was scrubbed... URL: From paradox at pobox.com Tue Apr 26 00:56:38 2011 From: paradox at pobox.com (Thomas C. Hicks) Date: Tue, 26 Apr 2011 06:56:38 +0800 Subject: [Tutor] voluntary work :p: In-Reply-To: <4DB5C6CE.8020702@gmail.com> References: <4DB5C6CE.8020702@gmail.com> Message-ID: <20110426065638.2c34f0bd@midgel> On Mon, 25 Apr 2011 15:09:02 -0400 Rafael Dur?n Casta?eda wrote: > I recommend you visit > www.pythonchallenge.com > > On 25/04/11 20:42, Wolf Halton wrote: > "Learn Python the Hard Way" is pretty cool. I am always looking for > books that lay it out well. Thanks for mentioning it, and good luck > with your studies. I find that having a project that is a little > beyond me helps me get better at coding. > > -Wolf > > On Mon, Apr 25, 2011 at 1:33 PM, Alan Gauld > > wrote: > > "Edgar Almonte" > wrote > > > is i want learn i read a bit and do some exercises but i am the kind > of ppl that need saw the path that will walk so > need a route and a little of guide to keep going , > > Have you looked at the python web site? There is a > whole section dedicated to tutorials for people who > have never programmed before. Take a look at a few > and choose the one you like - ie the one that aseems > to make most sense to you.. > > HTH, > > I second the recommendation to try out Python Challenge - outstanding way to learn (at least for me). Another option is to visit Sourceforge.net and look for python projects still in development. Open source pojects seem to always need bug finders and smashers as well as beta testers and I suspect most any of them would appreciate free help! tom From samudhio at gmail.com Tue Apr 26 01:29:40 2011 From: samudhio at gmail.com (Edgar Almonte) Date: Mon, 25 Apr 2011 19:29:40 -0400 Subject: [Tutor] voluntary work :p: In-Reply-To: <20110426065638.2c34f0bd@midgel> References: <4DB5C6CE.8020702@gmail.com> <20110426065638.2c34f0bd@midgel> Message-ID: Thanks all for the answer, python challenge is cool but i think need more python and programing level that i current have, ( i ended looking for the answer at google ) i will continue reading "Learn Python the Hard Way" 2011/4/25 Thomas C. Hicks : > On Mon, 25 Apr 2011 15:09:02 -0400 > Rafael Dur?n Casta?eda wrote: > >> I recommend you visit >> www.pythonchallenge.com >> >> On 25/04/11 20:42, Wolf Halton wrote: >> "Learn Python the Hard Way" is pretty cool. ?I am always looking for >> books that lay it out well. ?Thanks for mentioning it, and good luck >> with your studies. ?I find that having a project that is a little >> beyond me helps me get better at coding. >> >> -Wolf >> >> On Mon, Apr 25, 2011 at 1:33 PM, Alan Gauld >> > wrote: >> >> "Edgar Almonte" > wrote >> >> >> is i want learn i read a bit and do some exercises but i am the kind >> of ppl that need saw the path that will walk so >> need a route and a little of guide to keep going , >> >> Have you looked at the python web site? There is a >> whole section dedicated to tutorials for people who >> have never programmed before. Take a look at a few >> and choose the one you like - ie the one that aseems >> to make most sense to you.. >> >> HTH, >> >> > > I second the recommendation to try out Python Challenge - outstanding > way to learn (at least for me). ?Another option is to visit > Sourceforge.net and look for python projects still in development. > Open source pojects seem to always need bug finders and smashers as > well as beta testers and I suspect most any of them would appreciate > free help! > > tom > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From jigenbakuda at yahoo.com Tue Apr 26 02:36:38 2011 From: jigenbakuda at yahoo.com (michael scott) Date: Mon, 25 Apr 2011 17:36:38 -0700 (PDT) Subject: [Tutor] after(), how do I use it? Message-ID: <934553.86561.qm@web130207.mail.mud.yahoo.com> Hello, I asked for help in another location and it solved my problem, but the only problem is I don't fully understand the after function. Here is part of the code that was given to me. def print_label_slowly(self, message): '''Print a label one character at a time using the event loop''' t = self.label.cget("text") t += message[0] self.label.config(text=t) if len(message) > 1: self.after(500, self.print_label_slowly, message[1:]) I understand it, and the gist of how it works, but the self.after... I can not find any documentation on it (because after is such a common word), so can you guys tell me how it works. Is this a built in function (didn't see it on the built in function list)? Does it always take 3 arguements? Is this a user made function and I'm just overlooking where it was defined at? ---- What is it about you... that intrigues me so? -------------- next part -------------- An HTML attachment was scrubbed... URL: From adam.jtm30 at gmail.com Tue Apr 26 02:50:16 2011 From: adam.jtm30 at gmail.com (Adam Bark) Date: Tue, 26 Apr 2011 01:50:16 +0100 Subject: [Tutor] after(), how do I use it? In-Reply-To: <934553.86561.qm@web130207.mail.mud.yahoo.com> References: <934553.86561.qm@web130207.mail.mud.yahoo.com> Message-ID: <4DB616C8.8010104@gmail.com> On 26/04/11 01:36, michael scott wrote: > Hello, I asked for help in another location and it solved my problem, > but the only problem is I don't fully understand the after function. > Here is part of the code that was given to me. > > > def print_label_slowly(self, message): > '''Print a label one character at a time using the event loop''' > t = self.label.cget("text") > t += message[0] > self.label.config(text=t) > if len(message) > 1: > self.after(500, self.print_label_slowly, message[1:]) > > I understand it, and the gist of how it works, but the self.after... I > can not find any documentation on it (because after is such a common > word), so can you guys tell me how it works. Is this a built in > function (didn't see it on the built in function list)? Does it always > take 3 arguements? Is this a user made function and I'm just > overlooking where it was defined at? The function you have shown there appears to be a class method. self.after means you are calling another method of the same function that print_label_slowly is a part of. Do you have the rest of the code? If you're still confused post it and hopefully we can clear it up for you. HTH, Adam. From steve at pearwood.info Tue Apr 26 03:01:37 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 26 Apr 2011 11:01:37 +1000 Subject: [Tutor] Unbound Method Error In-Reply-To: References: <4DB52F56.30500@pearwood.info> <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA2AD919B@EMARC112VS01.exchad.jpmchase.net> Message-ID: <4DB61971.8060008@pearwood.info> Greg Nielsen wrote: > if isinstance(car, redracersprites26.BlueCarSprite()): > TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and > types Don't instantiate the class. Instead of redracersprites26.BlueCarSprite() # makes a new instance just refer to the class object without calling it: redracersprites26.BlueCarSprite -- Steven From jigenbakuda at yahoo.com Tue Apr 26 03:02:35 2011 From: jigenbakuda at yahoo.com (michael scott) Date: Mon, 25 Apr 2011 18:02:35 -0700 (PDT) Subject: [Tutor] after(), how do I use it? In-Reply-To: <4DB616C8.8010104@gmail.com> References: <934553.86561.qm@web130207.mail.mud.yahoo.com> <4DB616C8.8010104@gmail.com> Message-ID: <805368.30991.qm@web130209.mail.mud.yahoo.com> Here is the code in its entirety, it works although I don't see after() defined, so I assumed it was a built in function. I can just copy and paste parts of this code into my project, so its not imperative that I understand, but I prefer to use the weapons I've been given. So I hope that you guys can understand it a bit better after I post this. import Tkinter as tk class App(tk.Tk): def __init__(self,*args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) self.label = tk.Label(self, text="", width=20, anchor="w") self.label.pack(side="top",fill="both",expand=True) self.print_label_slowly("Hello, world!") def print_label_slowly(self, message): '''Print a label one character at a time using the event loop''' t = self.label.cget("text") t += message[0] self.label.config(text=t) if len(message) > 1: self.after(500, self.print_label_slowly, message[1:]) app = App() app.mainloop() ---- What is it about you... that intrigues me so? ________________________________ From: Adam Bark To: tutor at python.org Sent: Mon, April 25, 2011 8:50:16 PM Subject: Re: [Tutor] after(), how do I use it? On 26/04/11 01:36, michael scott wrote: > Hello, I asked for help in another location and it solved my problem, but the >only problem is I don't fully understand the after function. Here is part of the >code that was given to me. > > > def print_label_slowly(self, message): > '''Print a label one character at a time using the event loop''' > t = self.label.cget("text") > t += message[0] > self.label.config(text=t) > if len(message) > 1: > self.after(500, self.print_label_slowly, message[1:]) > > I understand it, and the gist of how it works, but the self.after... I can not >find any documentation on it (because after is such a common word), so can you >guys tell me how it works. Is this a built in function (didn't see it on the >built in function list)? Does it always take 3 arguements? Is this a user made >function and I'm just overlooking where it was defined at? The function you have shown there appears to be a class method. self.after means you are calling another method of the same function that print_label_slowly is a part of. Do you have the rest of the code? If you're still confused post it and hopefully we can clear it up for you. HTH, Adam. _______________________________________________ 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 waynejwerner at gmail.com Tue Apr 26 03:15:10 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Mon, 25 Apr 2011 20:15:10 -0500 Subject: [Tutor] after(), how do I use it? In-Reply-To: <805368.30991.qm@web130209.mail.mud.yahoo.com> References: <934553.86561.qm@web130207.mail.mud.yahoo.com> <4DB616C8.8010104@gmail.com> <805368.30991.qm@web130209.mail.mud.yahoo.com> Message-ID: On Mon, Apr 25, 2011 at 8:02 PM, michael scott wrote: > Here is the code in its entirety, it works although I don't see after() > defined, so I assumed it was a built in function. I can just copy and paste > parts of this code into my project, so its not imperative that I understand, > but I prefer to use the weapons I've been given. So I hope that you guys can > understand it a bit better after I post this. > That it is indeed. Do you understand classes and subclassing in Python? App is a subclass of tk.Tk. If you have done any of your own programming in Tkinter, you should know that Tk is the "main" class in Tkinter. If you do a Google search for "Tkinter after", the top two results will answer your question: http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=tkinter+after HTH, Wayne > > import Tkinter as tk > > class App(tk.Tk): > def __init__(self,*args, **kwargs): > tk.Tk.__init__(self, *args, **kwargs) > self.label = tk.Label(self, text="", width=20, anchor="w") > self.label.pack(side="top",fill="both",expand=True) > self.print_label_slowly("Hello, world!") > > > def print_label_slowly(self, message): > '''Print a label one character at a time using the event loop''' > t = self.label.cget("text") > t += message[0] > self.label.config(text=t) > if len(message) > 1: > self.after(500, self.print_label_slowly, message[1:]) > > app = App() > app.mainloop() > > > > ---- > What is it about you... that intrigues me so? > > > ------------------------------ > *From:* Adam Bark > *To:* tutor at python.org > *Sent:* Mon, April 25, 2011 8:50:16 PM > *Subject:* Re: [Tutor] after(), how do I use it? > > On 26/04/11 01:36, michael scott wrote: > > Hello, I asked for help in another location and it solved my problem, but > the only problem is I don't fully understand the after function. Here is > part of the code that was given to me. > > > > > > def print_label_slowly(self, message): > > '''Print a label one character at a time using the event loop''' > > t = self.label.cget("text") > > t += message[0] > > self.label.config(text=t) > > if len(message) > 1: > > self.after(500, self.print_label_slowly, message[1:]) > > > > I understand it, and the gist of how it works, but the self.after... I > can not find any documentation on it (because after is such a common word), > so can you guys tell me how it works. Is this a built in function (didn't > see it on the built in function list)? Does it always take 3 arguements? Is > this a user made function and I'm just overlooking where it was defined at? > > The function you have shown there appears to be a class method. self.after > means you are calling another method of the same function that > print_label_slowly is a part of. > Do you have the rest of the code? If you're still confused post it and > hopefully we can clear it up for you. > > HTH, > Adam. > _______________________________________________ > 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 > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From samudhio at gmail.com Tue Apr 26 03:22:37 2011 From: samudhio at gmail.com (Edgar Almonte) Date: Mon, 25 Apr 2011 21:22:37 -0400 Subject: [Tutor] after(), how do I use it? In-Reply-To: References: <934553.86561.qm@web130207.mail.mud.yahoo.com> <4DB616C8.8010104@gmail.com> <805368.30991.qm@web130209.mail.mud.yahoo.com> Message-ID: after(delay_ms, callback=None, *args) [#] Registers an alarm callback that is called after a given time. This method registers a callback function that will be called after a given number of milliseconds. Tkinter only guarantees that the callback will not be called earlier than that; if the system is busy, the actual delay may be much longer. The callback is only called once for each call to this method. To keep calling the callback, you need to reregister the callback inside itself: class App: def __init__(self, master): self.master = master self.poll() # start polling def poll(self): ... do something ... self.master.after(100, self.poll) after_cancel to cancel the callback. On Mon, Apr 25, 2011 at 9:15 PM, Wayne Werner wrote: > On Mon, Apr 25, 2011 at 8:02 PM, michael scott > wrote: >> >> Here is the code in its entirety, it works although I don't see after() >> defined, so I assumed it was a built in function. I can just copy and paste >> parts of this code into my project, so its not imperative that I understand, >> but I prefer to use the weapons I've been given. So I hope that you guys can >> understand it a bit better after I post this. > > That it is indeed. Do you understand classes and subclassing in Python? App > is a subclass of tk.Tk. If you have done any of your own programming in > Tkinter, you should know that Tk is the "main" class in Tkinter. If you do a > Google search for "Tkinter after", the top two results will answer your > question: > http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=tkinter+after > HTH, > Wayne > >> >> import Tkinter as tk >> >> class App(tk.Tk): >> ??? def __init__(self,*args, **kwargs): >> ??????? tk.Tk.__init__(self, *args, **kwargs) >> ??????? self.label = tk.Label(self, text="", width=20, anchor="w") >> ??????? self.label.pack(side="top",fill="both",expand=True) >> ??????? self.print_label_slowly("Hello, world!") >> >> ??? def print_label_slowly(self, message): >> ??????? '''Print a label one character at a time using the event loop''' >> ??????? t = self.label.cget("text") >> ??????? t += message[0] >> ??????? self.label.config(text=t) >> ??????? if len(message) > 1: >> ??????????? self.after(500, self.print_label_slowly, message[1:]) >> >> app = App() >> app.mainloop() >> >> >> ---- >> What is it about you... that intrigues me so? >> >> ________________________________ >> From: Adam Bark >> To: tutor at python.org >> Sent: Mon, April 25, 2011 8:50:16 PM >> Subject: Re: [Tutor] after(), how do I use it? >> >> On 26/04/11 01:36, michael scott wrote: >> > Hello, I asked for help in another location and it solved my problem, >> > but the only problem is I don't fully understand the after function. Here is >> > part of the code that was given to me. >> > >> > >> >? ? def print_label_slowly(self, message): >> >? ? ? ? '''Print a label one character at a time using the event loop''' >> >? ? ? ? t = self.label.cget("text") >> >? ? ? ? t += message[0] >> >? ? ? ? self.label.config(text=t) >> >? ? ? ? if len(message) > 1: >> >? ? ? ? ? ? self.after(500, self.print_label_slowly, message[1:]) >> > >> > I understand it, and the gist of how it works, but the self.after... I >> > can not find any documentation on it (because after is such a common word), >> > so can you guys tell me how it works. Is this a built in function (didn't >> > see it on the built in function list)? Does it always take 3 arguements? Is >> > this a user made function and I'm just overlooking where it was defined at? >> >> The function you have shown there appears to be a class method. self.after >> means you are calling another method of the same function that >> print_label_slowly is a part of. >> Do you have the rest of the code? If you're still confused post it and >> hopefully we can clear it up for you. >> >> HTH, >> Adam. >> _______________________________________________ >> 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 >> > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > From jigenbakuda at yahoo.com Tue Apr 26 03:34:00 2011 From: jigenbakuda at yahoo.com (michael scott) Date: Mon, 25 Apr 2011 18:34:00 -0700 (PDT) Subject: [Tutor] after(), how do I use it? In-Reply-To: References: <934553.86561.qm@web130207.mail.mud.yahoo.com> <4DB616C8.8010104@gmail.com> <805368.30991.qm@web130209.mail.mud.yahoo.com> Message-ID: <235732.59133.qm@web130203.mail.mud.yahoo.com> Now I understand what I misunderstood. Well he imported Tkinter as tk, so I thought if it belonged to Tkinter it would be tk.after(), but the after was attached to the app, so it was in actuality app.after() . app inherits from the tk class (taking with it all its methods), so its a built in function of tkinter. I read the whole thread of the first google response, but I still wasn't sure if it was a Tkinter function or a python function. I searched the actual python documentation quite extensively, but briefly glanced at the tkinter effbot page, after not seeing it I came here. I was just looking for the documentation on after(). But yea, this is what I needed id = w.after(time, callback) So I know it takes 2 arguments, and I know to use it recursively in my problem, so now I understand enough about this function to put it to good use :) Thank you. ---- What is it about you... that intrigues me so? ________________________________ From: Wayne Werner To: michael scott Cc: tutor at python.org Sent: Mon, April 25, 2011 9:15:10 PM Subject: Re: [Tutor] after(), how do I use it? On Mon, Apr 25, 2011 at 8:02 PM, michael scott wrote: Here is the code in its entirety, it works although I don't see after() defined, so I assumed it was a built in function. I can just copy and paste parts of this code into my project, so its not imperative that I understand, but I prefer to use the weapons I've been given. So I hope that you guys can understand it a bit better after I post this. > That it is indeed. Do you understand classes and subclassing in Python? App is a subclass of tk.Tk. If you have done any of your own programming in Tkinter, you should know that Tk is the "main" class in Tkinter. If you do a Google search for "Tkinter after", the top two results will answer your question: http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=tkinter+after HTH, Wayne >import Tkinter as tk > >class App(tk.Tk): > def __init__(self,*args, **kwargs): > tk.Tk.__init__(self, *args, **kwargs) > self.label = tk.Label(self, text="", width=20, anchor="w") > self.label.pack(side="top",fill="both",expand=True) > self.print_label_slowly("Hello, world!") > > > def print_label_slowly(self, message): > '''Print a label one character at a time using the event loop''' > t = self.label.cget("text") > t += message[0] > self.label.config(text=t) > if len(message) > 1: > self.after(500, self.print_label_slowly, message[1:]) > >app = App() >app.mainloop() > > > > ---- >What is it about you... that intrigues me so? > > > > > ________________________________ From: Adam Bark >To: tutor at python.org >Sent: Mon, April 25, 2011 8:50:16 PM >Subject: Re: [Tutor] after(), how do I use it? > > >On 26/04/11 01:36, michael scott wrote: >> Hello, I asked for help in another location and it solved my problem, but the >>only problem is I don't fully understand the after function. Here is part of the >>code that was given to me. >> >> >> def print_label_slowly(self, message): >> '''Print a label one character at a time using the event loop''' >> t = self.label.cget("text") >> t += message[0] >> self.label.config(text=t) >> if len(message) > 1: >> self.after(500, self.print_label_slowly, message[1:]) >> >> I understand it, and the gist of how it works, but the self.after... I can not >>find any documentation on it (because after is such a common word), so can you >>guys tell me how it works. Is this a built in function (didn't see it on the >>built in function list)? Does it always take 3 arguements? Is this a user made >>function and I'm just overlooking where it was defined at? > >The function you have shown there appears to be a class method. self.after means >you are calling another method of the same function that print_label_slowly is a >part of. >Do you have the rest of the code? If you're still confused post it and hopefully >we can clear it up for you. > >HTH, >Adam. >_______________________________________________ >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 > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Tue Apr 26 03:49:03 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Mon, 25 Apr 2011 20:49:03 -0500 Subject: [Tutor] after(), how do I use it? In-Reply-To: <235732.59133.qm@web130203.mail.mud.yahoo.com> References: <934553.86561.qm@web130207.mail.mud.yahoo.com> <4DB616C8.8010104@gmail.com> <805368.30991.qm@web130209.mail.mud.yahoo.com> <235732.59133.qm@web130203.mail.mud.yahoo.com> Message-ID: On Mon, Apr 25, 2011 at 8:34 PM, michael scott wrote: > So I know it takes 2 arguments, and I know to use it recursively in my problem, so now I understand enough about this function to put it to good use :) Thank you. > > Technically speaking it's not a recursive function call, it registers itself as a callback with the Tkinter mainloop. For more about recursion: http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=recursion HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From gollumgreg407366 at gmail.com Tue Apr 26 04:10:49 2011 From: gollumgreg407366 at gmail.com (Greg Nielsen) Date: Mon, 25 Apr 2011 21:10:49 -0500 Subject: [Tutor] Unbound Method Error In-Reply-To: <4DB61971.8060008@pearwood.info> References: <4DB52F56.30500@pearwood.info> <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA2AD919B@EMARC112VS01.exchad.jpmchase.net> <4DB61971.8060008@pearwood.info> Message-ID: And it works! Thank you once again to both Steven and Ramit for your peerless insight into the workings of Python and for taking time out of you day to help me work my code back to Python 2. I have learned much by talking with both of you over the last day or so. Greg -------------- next part -------------- An HTML attachment was scrubbed... URL: From wolf.halton at gmail.com Tue Apr 26 05:59:56 2011 From: wolf.halton at gmail.com (Wolf Halton) Date: Mon, 25 Apr 2011 23:59:56 -0400 Subject: [Tutor] voluntary work :p: In-Reply-To: References: <4DB5C6CE.8020702@gmail.com> <20110426065638.2c34f0bd@midgel> Message-ID: I didn't get anything out of pythonchallenge. All seems static. Do you need flash or something to make the magic happen? On Mon, Apr 25, 2011 at 7:29 PM, Edgar Almonte wrote: > Thanks all for the answer, python challenge is cool but i think need > more python and programing level that i current have, ( i ended > looking for the answer at google ) > > i will continue reading "Learn Python the Hard Way" > > > 2011/4/25 Thomas C. Hicks : > > On Mon, 25 Apr 2011 15:09:02 -0400 > > Rafael Dur?n Casta?eda wrote: > > > >> I recommend you visit > >> www.pythonchallenge.com > >> > >> On 25/04/11 20:42, Wolf Halton wrote: > >> "Learn Python the Hard Way" is pretty cool. I am always looking for > >> books that lay it out well. Thanks for mentioning it, and good luck > >> with your studies. I find that having a project that is a little > >> beyond me helps me get better at coding. > >> > >> -Wolf > >> > >> On Mon, Apr 25, 2011 at 1:33 PM, Alan Gauld > >> > wrote: > >> > >> "Edgar Almonte" > wrote > >> > >> > >> is i want learn i read a bit and do some exercises but i am the kind > >> of ppl that need saw the path that will walk so > >> need a route and a little of guide to keep going , > >> > >> Have you looked at the python web site? There is a > >> whole section dedicated to tutorials for people who > >> have never programmed before. Take a look at a few > >> and choose the one you like - ie the one that aseems > >> to make most sense to you.. > >> > >> HTH, > >> > >> > > > > I second the recommendation to try out Python Challenge - outstanding > > way to learn (at least for me). Another option is to visit > > Sourceforge.net and look for python projects still in development. > > Open source pojects seem to always need bug finders and smashers as > > well as beta testers and I suspect most any of them would appreciate > > free help! > > > > tom > > _______________________________________________ > > 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 > -- This Apt Has Super Cow Powers - http://sourcefreedom.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Tue Apr 26 06:19:55 2011 From: bgailer at gmail.com (bob gailer) Date: Tue, 26 Apr 2011 00:19:55 -0400 Subject: [Tutor] voluntary work :p: In-Reply-To: References: <4DB5C6CE.8020702@gmail.com> <20110426065638.2c34f0bd@midgel> Message-ID: <4DB647EB.3060506@gmail.com> On 4/25/2011 11:59 PM, Wolf Halton wrote: > I didn't get anything out of pythonchallenge. Nothing? No web pages? > All seems static. Now you say All instead of nothing. Did you get more than 1 web page? > Do you need flash or something to make the magic happen? What are you expecting? What magic? Did you see an image of a monitor with 2 to the 38 on it? Did you see "Hint: try to change the URL address."? Did you try that? -- Bob Gailer 919-636-4239 Chapel Hill NC From ladymcse2000 at gmail.com Tue Apr 26 09:14:24 2011 From: ladymcse2000 at gmail.com (Becky Mcquilling) Date: Tue, 26 Apr 2011 00:14:24 -0700 Subject: [Tutor] Equivalent of Set in PtO Message-ID: I have a code snippet that I have used to count the duplicates in a list as such: from sets import Set def countDups(duplicateList): uniqueSet = Set(item for item in duplicateList) return[(item, duplicateList.count(item)) for item in uniqueSet] lst = ['word', 'word', 'new', 'new', 'new'] print countDups(lst) The result is: [('new', 3), ('word', 2)], which is what is expected. This was using python version 2.7. I want to do the same thing in Python 3.1, but I'm not sure what has replaced Set in the newer version, can someone give me an idea here? Becky -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Tue Apr 26 09:40:43 2011 From: __peter__ at web.de (Peter Otten) Date: Tue, 26 Apr 2011 09:40:43 +0200 Subject: [Tutor] Unbound Method Error References: <4DB52F56.30500@pearwood.info> <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA2AD919B@EMARC112VS01.exchad.jpmchase.net> Message-ID: Greg Nielsen wrote: > if crash: > for BlueCarSprite in crash: > redracersprites26.BlueCarSprite.collide(crash, playerCar) > for GreenCarSprite in crash: > redracersprites26.GreenCarSprite.collide(crash, playerCar) > for TruckSprite in crash: > redracersprites26.TruckSprite.collide(crash, playerCar) > if crash: > for car in crash: > if isinstance(car, redracersprites26.BlueCarSprite()): > redracersprites26.BlueCarSprite.collide(car, playerCar) That's too little of your code to be sure, but I have a hunch that you can avoid the if-crash test and all if-isinstance(...) tests and just write for car in crash: car.collide(playerCar) You rarely need to invoke an unbound method outside of a subclass method. From alan.gauld at btinternet.com Tue Apr 26 09:40:41 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 26 Apr 2011 08:40:41 +0100 Subject: [Tutor] after(), how do I use it? References: <934553.86561.qm@web130207.mail.mud.yahoo.com><4DB616C8.8010104@gmail.com><805368.30991.qm@web130209.mail.mud.yahoo.com> <235732.59133.qm@web130203.mail.mud.yahoo.com> Message-ID: "michael scott" wrote > Now I understand what I misunderstood. Well he imported Tkinter as > tk, so I > thought if it belonged to Tkinter it would be tk.after(), but the > after was > attached to the app, so it was in actuality app.after() . app > inherits from the > tk class (taking with it all its methods), so its a built in > function of > tkinter. To be pedantic its a method of tkinter since its part of a class definition. For the distinction between a function and a method see yesterday's thread "Unbound Method Error" One pragmatic difference between them is that help on functions is located in module level documentation, help on methods is located in class level documentation. So recognising a method call helps in directing the search for help! HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Apr 26 09:46:05 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 26 Apr 2011 08:46:05 +0100 Subject: [Tutor] Equivalent of Set in PtO References: Message-ID: "Becky Mcquilling" wrote > from sets import Set > > def countDups(duplicateList): > uniqueSet = Set(item for item in duplicateList) > return[(item, duplicateList.count(item)) for item in uniqueSet] Can be abbreviated to: def countDups(duplicateList): return [(item, duplicateList.count(item)) for item in set(duplicateList)] > was using python version 2.7. I want to do the same thing in Python > 3.1, > but I'm not sure what has replaced Set in the newer version, can > someone > give me an idea here? set() It has become a native type in v3. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Tue Apr 26 09:50:20 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 26 Apr 2011 17:50:20 +1000 Subject: [Tutor] Equivalent of Set in PtO In-Reply-To: References: Message-ID: <4DB6793C.4080503@pearwood.info> Becky Mcquilling wrote: > I have a code snippet that I have used to count the duplicates in a list as > such: > > from sets import Set Since Python 2.4, you no longer need to import module "sets" (note plural) to get Set (note capital letter). You can just use the built-in name "set" (note lower-case letter). > def countDups(duplicateList): > uniqueSet = Set(item for item in duplicateList) > return[(item, duplicateList.count(item)) for item in uniqueSet] This becomes: uniqueSet = set(item for item in duplicateList) Another advantage is that the built-in set is much faster than sets.Set. -- Steven From __peter__ at web.de Tue Apr 26 10:10:42 2011 From: __peter__ at web.de (Peter Otten) Date: Tue, 26 Apr 2011 10:10:42 +0200 Subject: [Tutor] Equivalent of Set in PtO References: Message-ID: Becky Mcquilling wrote: > I have a code snippet that I have used to count the duplicates in a list > as such: > > from sets import Set > > def countDups(duplicateList): > uniqueSet = Set(item for item in duplicateList) > return[(item, duplicateList.count(item)) for item in uniqueSet] > > > lst = ['word', 'word', 'new', 'new', 'new'] > print countDups(lst) > > The result is: [('new', 3), ('word', 2)], which is what is expected. This > was using python version 2.7. I want to do the same thing in Python 3.1, > but I'm not sure what has replaced Set in the newer version, can someone > give me an idea here? Note that your countDups() function has to iterate len(set(duplicateList))+1 times over the duplicateList, once to build the set and then implicitly in the count() method for every item in the set. If you use a dictionary instead you can find the word frequencies in a single pass: >>> lst = ['word', 'word', 'new', 'new', 'new'] >>> freq = {} >>> for item in lst: ... freq[item] = freq.get(item, 0) + 1 ... >>> freq.items() dict_items([('new', 3), ('word', 2)]) There is also a ready-to-use class that implements this efficient approach: >>> from collections import Counter >>> Counter(lst).items() dict_items([('new', 3), ('word', 2)]) From samudhio at gmail.com Tue Apr 26 13:43:36 2011 From: samudhio at gmail.com (Edgar Almonte) Date: Tue, 26 Apr 2011 07:43:36 -0400 Subject: [Tutor] voluntary work :p: In-Reply-To: <4DB647EB.3060506@gmail.com> References: <4DB5C6CE.8020702@gmail.com> <20110426065638.2c34f0bd@midgel> <4DB647EB.3060506@gmail.com> Message-ID: you need solve the problem and so far the solution of the problem is the name of the next url example: .html , you need get the result and change in the url bar On Tue, Apr 26, 2011 at 12:19 AM, bob gailer wrote: > On 4/25/2011 11:59 PM, Wolf Halton wrote: >> >> I didn't get anything out of pythonchallenge. > > Nothing? No web pages? > >> All seems static. > > Now you say All instead of nothing. Did you get more than 1 web page? > >> Do you need flash or something to make the magic happen? > > What are you expecting? What magic? > > Did you see an image of a monitor with 2 to the 38 on it? > > Did you see "Hint: try to change the URL address."? > > Did you try that? > > > -- > 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 > From s.charonis at gmail.com Tue Apr 26 13:54:54 2011 From: s.charonis at gmail.com (Spyros Charonis) Date: Tue, 26 Apr 2011 14:54:54 +0300 Subject: [Tutor] Deleting strings from a line Message-ID: Hello, I've written a script that scans a biological database and extracts some information. A sample of output from my script is as follows: LYLGILLSHAN AA3R_SHEEP 263 31 LYMGILLSHAN AA3R_HUMAN 264 31 MCLGILLSHAN AA3R_RAT 266 31 LLVGILLSHAN AA3R_RABIT 265 31 The leftmost strings are the ones I want to keep, while I would like to get rid of the ones to the right (AA3R_SHEEP, 263 61) which are just indicators of where the sequence came from and genomic coordinates. Is there any way to do this with a string processing command? The loop which builds my list goes like this: for line in query_lines: if line.startswith('fd;'): # find motif sequences #print "Found an FD for your query!", line.rstrip().lstrip('fd;') print line.lstrip('fd;') motif.append(line.rstrip().lstrip('fd;')) Is there a del command I can use to preserve only the actual sequences themselves. Many thanks in advance! -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at linux-ip.net Tue Apr 26 14:14:54 2011 From: martin at linux-ip.net (Martin A. Brown) Date: Tue, 26 Apr 2011 14:14:54 +0200 Subject: [Tutor] Deleting strings from a line In-Reply-To: References: Message-ID: Greetings, : I've written a script that scans a biological database and extracts some : information. A sample of output from my script is as follows: : : LYLGILLSHAN AA3R_SHEEP 263 31 : : LYMGILLSHAN AA3R_HUMAN 264 31 : : MCLGILLSHAN AA3R_RAT 266 31 : : LLVGILLSHAN AA3R_RABIT 265 31 : : The leftmost strings are the ones I want to keep, while I would : like to get rid of the ones to the right (AA3R_SHEEP, 263 61) : which are just indicators of where the sequence came from and : genomic coordinates. Is there any way to do this with a string : processing command? The loop which builds my list goes like this: Yes, of course. I would suggest a casual walk through: http://docs.python.org/library/stdtypes.html#typesseq This should give you some ideas of the sorts of things you can do with strings (and other similar such types). I think what you are looking for is the split() method. : for line in query_lines: : if line.startswith('fd;'): # find motif sequences : #print "Found an FD for your query!", line.rstrip().lstrip('fd;') : print line.lstrip('fd;') : motif.append(line.rstrip().lstrip('fd;')) : : Is there a del command I can use to preserve only the actual sequences : themselves. Many thanks in advance! I see (though it's commented out) that you want to get the result of line.rstrip().lstrip('fd;') several times. Rather than calculate this several times, why not store that in a variable. Additionally, then you can perform other tasks on the intermediate result. Anyway, try out the following: line.rstrip().lstrip('fd;').split()[0] Which, if I were writing in code, I would do, like this: # -- strip off motif sequences (whatever the heck they are) # line = line.rstrip().lstrip('fd;') # -- break the data into individual, well, units # parts = line.split() # -- print out the sequence # print parts[0] # -- And, here, I still have the various other bits, so I can # store them in case I want to perform some other sort of # calculations... # my_dict[ parts[0] ] = tuple( parts[1:] ) So, in short, the answer is yes. I think you would benefit from looking at what sort of string methods there are and what they do. The strip() method is one of the first to learn. The split() should be your second. Keep on going, and you'll find all sorts of goodies in there. And, enjoy Python! -Martin -- Martin A. Brown http://linux-ip.net/ From __peter__ at web.de Tue Apr 26 14:22:40 2011 From: __peter__ at web.de (Peter Otten) Date: Tue, 26 Apr 2011 14:22:40 +0200 Subject: [Tutor] Deleting strings from a line References: Message-ID: Spyros Charonis wrote: > Hello, > > I've written a script that scans a biological database and extracts some > information. A sample of output from my script is as follows: > > LYLGILLSHAN AA3R_SHEEP 263 31 > > LYMGILLSHAN AA3R_HUMAN 264 31 > > MCLGILLSHAN AA3R_RAT 266 31 > > LLVGILLSHAN AA3R_RABIT 265 31 > > The leftmost strings are the ones I want to keep, while I would like to > get rid of the ones to the right (AA3R_SHEEP, 263 61) which are just > indicators of where the sequence came from and genomic coordinates. Is > there any way to do this with a string processing command? The loop which > builds my list goes like this: > > for line in query_lines: > if line.startswith('fd;'): # find motif sequences > #print "Found an FD for your query!", > line.rstrip().lstrip('fd;') > print line.lstrip('fd;') > motif.append(line.rstrip().lstrip('fd;')) > > Is there a del command I can use to preserve only the actual sequences > themselves. Many thanks in advance! You don't have to delete; instead extract the piece you are interested in: with open("prints41_1.kdat") as instream: for line in instream: if line.startswith("fd;"): print line.split()[1] To see what the last line does, lets perform it in two steps >>> line = 'fd; RVNIENPSRADSYNPRAG A1YQH4_ORYSJ 310 310\n' >>> parts = line.split() >>> parts ['fd;', 'RVNIENPSRADSYNPRAG', 'A1YQH4_ORYSJ', '310', '310'] >>> wanted = parts[1] >>> wanted 'RVNIENPSRADSYNPRAG' From steve at pearwood.info Tue Apr 26 14:25:01 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 26 Apr 2011 22:25:01 +1000 Subject: [Tutor] Deleting strings from a line In-Reply-To: References: Message-ID: <4DB6B99D.7000605@pearwood.info> Spyros Charonis wrote: > Hello, > > I've written a script that scans a biological database and extracts some > information. A sample of output from my script is as follows: > > LYLGILLSHAN AA3R_SHEEP 263 31 > > LYMGILLSHAN AA3R_HUMAN 264 31 > > MCLGILLSHAN AA3R_RAT 266 31 > > LLVGILLSHAN AA3R_RABIT 265 31 > > The leftmost strings are the ones I want to keep, while I would like to get > rid of the ones to the right (AA3R_SHEEP, 263 61) Split each line in multiple words, keeping only the first: line = "LYLGILLSHAN AA3R_SHEEP 263 31" # split on any whitespace, a maximum of 1 time head, tail = line.split(None, 1) head will be "LYLGILLSHAN" and tail will be "AA3R_SHEEP 263 31". Or, if the text is fixed-width, you can use string slice to extract the characters you care about: head = line[0:11] -- Steven From wprins at gmail.com Tue Apr 26 14:54:04 2011 From: wprins at gmail.com (Walter Prins) Date: Tue, 26 Apr 2011 13:54:04 +0100 Subject: [Tutor] voluntary work :p: In-Reply-To: References: <4DB5C6CE.8020702@gmail.com> <20110426065638.2c34f0bd@midgel> Message-ID: On 26 April 2011 04:59, Wolf Halton wrote: > I didn't get anything out of pythonchallenge. All seems static. Do you > need flash or something to make the magic happen? > > To add to what the others have said and explain the "flow" a bit more: Each challenge is a puzzle, with hints present in various places, either in the displayed image and/or text, sometimes in the page source, sometimes hidden inside an image or a file that you must download etc, and so on. The general goal for solving each puzzle is to find the next puzzle's solution URL and the next puzzle URL by modifying the page URL of the current puzzle based on your detective work on the current puzzle. In several instances (especially in the beginning) it's actually possible to solve a puzzle without using Python, but obviously the idea is really to solve or perform whatever calculations are required using Python, and thereby in the process learn something about Python as you go. Now, the very first puzzle presents you with a number, 2^38, and a hint "Try to change the URL address". Now, with a bit of research you'll find that Python's way to expressing exponentiation is with the ** operator. Thus, one might as a first try, attempt changing the URL to simply that, e.g.: http://www.pythonchallenge.com/pc/def/2**38.html Attempting that, takes you to a page that says: "give the answer, not the question." ... Hmmm.... OK. So that should lead you to the conclusion that you need to actually calculate the answer to 2^38, and then try that in the URL instead... Now after a bit of reading you should find out about the interactive aspects of the Python interpreter and that you can use it as a calculator, and that you can calculate the answer by simply typing 2**38 into the Python interpreter. Doing all that then teaches you something about the Python interpreter, and the fact that Python copes easily with very large numbers, which in many other languages would be problematic. And so it goes. You'll quickly get to places where you e.g. have to interact with the website quite a number of times to figure out what the next puzzle URL should be, and thereby be pushed to learn about urllib and Python's wonderful web modules in order to automate the interaction, places where you have to do some relatively involved (if you tried to do the same in other languages) text processing in order to get the answer and so on. Every puzzle pushes you to learn about a specific aspect of Python, and impresses upon you (especially if you have any prior programming experience) just how elegant and powerful Python really is. As an aside, The Python Challenge was one of the things that originally impressed on me just how good and useful a language Python really is, and how wide the variety of contexts are where it can be usefully applied. Best regards, Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From bodsda at googlemail.com Tue Apr 26 17:34:52 2011 From: bodsda at googlemail.com (bodsda at googlemail.com) Date: Tue, 26 Apr 2011 15:34:52 +0000 Subject: [Tutor] Gtk - relational data display and edit Message-ID: <539054980-1303832138-cardhu_decombobulator_blackberry.rim.net-1511176242-@b18.c12.bise7.blackberry> Hi, I am reading in data from a csv file which will be in a format like this User1, attrib1, attrib2 User2, attrib1, attrib2 Etc. And need to display this in a window. My initial thought was to use gtk.Entry widgets because I will need to edit this data, but I don't think this will work as I will also need to read the data back, in relation to the user column, e.g I will have something like [Psuedocode] For I in entries: A = usercolumn B = attrib1column C = attrib2column Somefunction(A,B,C) [/psuedocode] I don't think I could use this method with entry boxes as I have no idea how many entries there will be (column length will be fixed) so I can't create the entry widgets beforehand Anyone have any suggestions? Thanks, Bodsda Sent from my BlackBerry? wireless device From wprins at gmail.com Tue Apr 26 17:55:36 2011 From: wprins at gmail.com (Walter Prins) Date: Tue, 26 Apr 2011 16:55:36 +0100 Subject: [Tutor] Gtk - relational data display and edit In-Reply-To: <539054980-1303832138-cardhu_decombobulator_blackberry.rim.net-1511176242-@b18.c12.bise7.blackberry> References: <539054980-1303832138-cardhu_decombobulator_blackberry.rim.net-1511176242-@b18.c12.bise7.blackberry> Message-ID: On 26 April 2011 16:34, wrote: > Hi, > > I am reading in data from a csv file which will be in a format like this > > User1, attrib1, attrib2 > User2, attrib1, attrib2 > Etc. > Why would the data be in this format? Are you defining it? Reason I ask is that, relationally speaking, (e.g. database design-wise) this is a denormalised representation and you'd do better to store a single attribute per record. E.g. have entities, User, Attrib, and have relationship table User_Attrib that contains only user, attrib pairs. But, maybe such ideas are overkill for your app. > And need to display this in a window. My initial thought was to use > gtk.Entry widgets because I will need to edit this data, but I don't think > this will work as I will also need to read the data back, in relation to the > user column, e.g I will have something like > > [Psuedocode] > For I in entries: > A = usercolumn > B = attrib1column > C = attrib2column > > Somefunction(A,B,C) > [/psuedocode] > > I don't think I could use this method with entry boxes as I have no idea > how many entries there will be (column length will be fixed) so I can't > create the entry widgets beforehand > > Anyone have any suggestions? > Well if you can count the number of entries on reading the file (whatever the shape of the file) then in principle you can dynamically create the correct number of entry boxes on the fly. Of course, if you store one attribe per record, then counting the number of attributes (records) for a given user becomes quite easy of course. But even if you don't do this, and you have the file structure you described, you can code reader code that would internally store the attributes and the number of attributes for each user, enabling you to write code to create the UI with the appropriate number of entry widgets. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From timomlists at gmail.com Tue Apr 26 19:00:28 2011 From: timomlists at gmail.com (Timo) Date: Tue, 26 Apr 2011 19:00:28 +0200 Subject: [Tutor] Gtk - relational data display and edit In-Reply-To: <539054980-1303832138-cardhu_decombobulator_blackberry.rim.net-1511176242-@b18.c12.bise7.blackberry> References: <539054980-1303832138-cardhu_decombobulator_blackberry.rim.net-1511176242-@b18.c12.bise7.blackberry> Message-ID: <4DB6FA2C.606@gmail.com> On 26-04-11 17:34, bodsda at googlemail.com wrote: > Hi, > > I am reading in data from a csv file which will be in a format like this > > User1, attrib1, attrib2 > User2, attrib1, attrib2 > Etc. > > And need to display this in a window. My initial thought was to use gtk.Entry widgets because I will need to edit this data, but I don't think this will work as I will also need to read the data back, in relation to the user column, e.g I will have something like > > [Psuedocode] > For I in entries: > A = usercolumn > B = attrib1column > C = attrib2column > > Somefunction(A,B,C) > [/psuedocode] > > I don't think I could use this method with entry boxes as I have no idea how many entries there will be (column length will be fixed) so I can't create the entry widgets beforehand Use a gtk.Treeview for displaying this kind of data. You can also have editable cells inside a treeview so the user can change the data. Cheers, Timo > Anyone have any suggestions? > > Thanks, > Bodsda > Sent from my BlackBerry? wireless device > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From knacktus at googlemail.com Tue Apr 26 19:21:41 2011 From: knacktus at googlemail.com (Knacktus) Date: Tue, 26 Apr 2011 19:21:41 +0200 Subject: [Tutor] Gtk - relational data display and edit In-Reply-To: <539054980-1303832138-cardhu_decombobulator_blackberry.rim.net-1511176242-@b18.c12.bise7.blackberry> References: <539054980-1303832138-cardhu_decombobulator_blackberry.rim.net-1511176242-@b18.c12.bise7.blackberry> Message-ID: <4DB6FF25.1010807@googlemail.com> Am 26.04.2011 17:34, schrieb bodsda at googlemail.com: > Hi, > > I am reading in data from a csv file which will be in a format like this > > User1, attrib1, attrib2 > User2, attrib1, attrib2 > Etc. > > And need to display this in a window. My initial thought was to use gtk.Entry widgets because I will need to edit this data, but I don't think this will work as I will also need to read the data back, in relation to the user column, e.g I will have something like > > [Psuedocode] > For I in entries: > A = usercolumn > B = attrib1column > C = attrib2column > > Somefunction(A,B,C) > [/psuedocode] > > I don't think I could use this method with entry boxes as I have no idea how many entries there will be (column length will be fixed) so I can't create the entry widgets beforehand > You could use a table widget. I'm sure GTK has something like that (I'm using Qt). Otherwise, creating a "dynamic" widget for one set of your data is not as hard as it might sound. You need to keeping references to the composing widgets, for example in a dict. Here's some PyQt Pseudocode: # You can retrieve the dictionary and the fieldnames with help of the # csv module att_name_to_value = {"User": "User1", "Att1": "attrib1", "Att1": "attrib1"} fieldnames = ["User", "Att1", "Att2"] att_name_to_line_edit = {} # This is Qt specific layout = QtGui.QGridLayout() for row, fieldname in enumerate(fieldnames): label = QtGui.QLabel(fieldname) line_edit = QtGui.QLineEdit(att_name_to_value[fieldname] att_name_to_line_edit[fieldname] = line_edit # add the label to the first col layout.addWidget(label, row, 0) # add the line_edit to the second col layout.addWidget(line_edit, row, 1) my_main_widget = QtGui.QWidget() my_main_widget.setLayout(layout) Now, if you need to read the changed data from the widget (triggered by a button_clicked event or what ever) you can call a function to read the data like this: def read_data_from_widget(att_name_to_line_edit): for att_name, line_edit in att_name_to_line_edit.items(): # do the conversion, e.g. PyQt new_text = str(line_edit.text()) # do whatever you wish with the new data ... HTH, Jan > Anyone have any suggestions? > > Thanks, > Bodsda > Sent from my BlackBerry? wireless device > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From bodsda at googlemail.com Tue Apr 26 18:52:24 2011 From: bodsda at googlemail.com (bodsda at googlemail.com) Date: Tue, 26 Apr 2011 16:52:24 +0000 Subject: [Tutor] Gtk - relational data display and edit In-Reply-To: References: <539054980-1303832138-cardhu_decombobulator_blackberry.rim.net-1511176242-@b18.c12.bise7.blackberry> Message-ID: <1284120337-1303836741-cardhu_decombobulator_blackberry.rim.net-985116887-@b18.c12.bise7.blackberry> Thanks for your reply. Unfortunately I can't change the data format because it is output from a closed source app. I can't figure out a way to create the entry widgets on the fly because they need to be bound to a variable to attach them to a gtk.Table and to be able to read the data from them Bodsda Sent from my BlackBerry? wireless device -----Original Message----- From: Walter Prins Date: Tue, 26 Apr 2011 16:55:36 To: Cc: Subject: Re: [Tutor] Gtk - relational data display and edit On 26 April 2011 16:34, wrote: > Hi, > > I am reading in data from a csv file which will be in a format like this > > User1, attrib1, attrib2 > User2, attrib1, attrib2 > Etc. > Why would the data be in this format? Are you defining it? Reason I ask is that, relationally speaking, (e.g. database design-wise) this is a denormalised representation and you'd do better to store a single attribute per record. E.g. have entities, User, Attrib, and have relationship table User_Attrib that contains only user, attrib pairs. But, maybe such ideas are overkill for your app. > And need to display this in a window. My initial thought was to use > gtk.Entry widgets because I will need to edit this data, but I don't think > this will work as I will also need to read the data back, in relation to the > user column, e.g I will have something like > > [Psuedocode] > For I in entries: > A = usercolumn > B = attrib1column > C = attrib2column > > Somefunction(A,B,C) > [/psuedocode] > > I don't think I could use this method with entry boxes as I have no idea > how many entries there will be (column length will be fixed) so I can't > create the entry widgets beforehand > > Anyone have any suggestions? > Well if you can count the number of entries on reading the file (whatever the shape of the file) then in principle you can dynamically create the correct number of entry boxes on the fly. Of course, if you store one attribe per record, then counting the number of attributes (records) for a given user becomes quite easy of course. But even if you don't do this, and you have the file structure you described, you can code reader code that would internally store the attributes and the number of attributes for each user, enabling you to write code to create the UI with the appropriate number of entry widgets. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From aznjonn at me.com Wed Apr 27 14:32:31 2011 From: aznjonn at me.com (Johnson Tran) Date: Wed, 27 Apr 2011 05:32:31 -0700 Subject: [Tutor] Just started Python Message-ID: <0D64237F-47A8-4EF5-9932-7FC213BC7E19@me.com> Hi All, I am a complete beginner so my question will probably be pretty noob but: I started out with a short program below and I thought it was working although I cannot seem to figure out how to use the except ValueError so that when the user puts an invalid answer the program does not read with an error. Although according to the error message, it seems to be saying that my line 4 "number1 = float (number_string1)" is incorrect. Thanks in advance for any advice. Cheers, Noob Program::: model=raw_input("What kind of car do you drive?") number_string1=raw_input("How many gallons have you driven?") number1 = float (number_string1) number_string2=raw_input("How many miles have you driven?") number2 = float (number_string2) try: model=float(model) except ValueError: pass print "Your average number of miles to gallons is", print number1 / number2 What kind of car do you drive?firebird How many gallons have you driven?test Output of Program:: T>>> ================================ RESTART ================================ >>> What kind of car do you drive?firebird How many gallons have you driven?30 How many miles have you driven?60 Your average number of miles to gallons is 0.5 >>> ================================ RESTART ================================ >>> What kind of car do you drive?firebird How many gallons have you driven?test Traceback (most recent call last): File "/Users/JT/Desktop/test", line 4, in number1 = float (number_string1) ValueError: invalid literal for float(): test From enalicho at gmail.com Wed Apr 27 16:20:21 2011 From: enalicho at gmail.com (Noah Hall) Date: Wed, 27 Apr 2011 15:20:21 +0100 Subject: [Tutor] Just started Python In-Reply-To: <0D64237F-47A8-4EF5-9932-7FC213BC7E19@me.com> References: <0D64237F-47A8-4EF5-9932-7FC213BC7E19@me.com> Message-ID: On Wed, Apr 27, 2011 at 1:32 PM, Johnson Tran wrote: > Program::: > model=raw_input("What kind of car do you drive?") > number_string1=raw_input("How many gallons have you driven?") > number1 = float (number_string1) There's no validation for the variables when you try to convert them (see bottom) > number_string2=raw_input("How many miles have you driven?") > number2 = float (number_string2) > > > try: > ? ?model=float(model) > except ValueError: > ? ?pass Well, I'm not sure why you're trying to do this. You've obviously come up with the error of it always raising exception due to the fact that model is always going to be a string, so you've come up with a way to avoid that. Why on earth would you want to always try to convert something to float that you want as a string anyway? Think about it, and see if you can figure out why this bit is all wrong. > print "Your average number of miles to gallons is", > print number1 / number2 > What kind of car do you drive?firebird > How many gallons have you driven?30 > How many miles have you driven?60 > Your average number of miles to gallons is 0.5 > What kind of car do you drive?firebird > How many gallons have you driven?test > > Traceback (most recent call last): > ?File "/Users/JT/Desktop/test", line 4, in > ? ?number1 = float (number_string1) > ValueError: invalid literal for float(): test Your problem is that you're passing the string 'test' to the float function. The string 'test' is not a valid value for the function float, so it raises a ValueError - the Value that you're passing to the function is wrong. In order to get around this, you'll want to make sure that whatever you pass to the float function is a valid value. From alan.gauld at btinternet.com Wed Apr 27 19:02:17 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 27 Apr 2011 18:02:17 +0100 Subject: [Tutor] Just started Python References: <0D64237F-47A8-4EF5-9932-7FC213BC7E19@me.com> Message-ID: "Johnson Tran" wrote > I started out with a short program below and I thought > it was working although I cannot seem to figure out > how to use the except ValueError so that when > the user puts an invalid answer the program does > not read with an error. You have to replace the line that says 'pass' with code that does something to make the value correct. Asking the user to try again with a more sensible value would be a start. > Although according to the error message, it > seems to be saying that my line 4 > "number1 = float (number_string1)" is incorrect. Its not saying its incorrect, its saying thats where the ValueError occured. Which is true because you entered 'test' which cannot be converted to a float - its an invalid value. > model=raw_input("What kind of car do you drive?") > number_string1=raw_input("How many gallons have you driven?") > number1 = float (number_string1) > number_string2=raw_input("How many miles have you driven?") > number2 = float (number_string2) You will fin it easier if you use descriptive names for your variables. gallons and miles would seem reasonable here... > try: > model=float(model) > except ValueError: > pass This says if you get an error ignore it (ie pass). But you don't want to ignore it, you want to get a valid value. > print "Your average number of miles to gallons is", > print number1 / number2 HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From aznjonn at me.com Wed Apr 27 22:17:53 2011 From: aznjonn at me.com (Johnson Tran) Date: Wed, 27 Apr 2011 13:17:53 -0700 Subject: [Tutor] Just started Python In-Reply-To: References: <0D64237F-47A8-4EF5-9932-7FC213BC7E19@me.com> Message-ID: <04FEC6B4-308B-4004-9A86-7B1BC9402181@me.com> Thanks for the reply Alan and Noah, I really appreciate the help. I am really trying to understand this although still cannot seem to grasp it all. I have modified my program although now it seems to be giving me the wrong answer with the correct answer when I input any value. I have program: model=raw_input("What kind of car do you drive?") gallons=raw_input("How many gallons have you driven?") number1 = float (gallons) miles=raw_input("How many miles have you driven?") number2 = float (miles) try: model=float(model) except ValueError: print "I cannot compute your total miles to gallon with those values." else: print "Your average number of miles to gallons is", print number1 / number2 Output: What kind of car do you drive?fire How many gallons have you driven?10 How many miles have you driven?5 I cannot compute your total miles to gallon with those values. On Apr 27, 2011, at 10:02 AM, Alan Gauld wrote: > > "Johnson Tran" wrote > >> I started out with a short program below and I thought it was working although I cannot seem to figure out how to use the except ValueError so that when the user puts an invalid answer the program does not read with an error. > > You have to replace the line that says 'pass' with code that does something to make the value correct. Asking the user to try again with a more sensible value would be a start. > >> Although according to the error message, it seems to be saying that my line 4 "number1 = float (number_string1)" is incorrect. > > Its not saying its incorrect, its saying thats where the ValueError occured. Which is true because you entered 'test' which cannot be converted to a float - its an invalid value. > >> model=raw_input("What kind of car do you drive?") >> number_string1=raw_input("How many gallons have you driven?") >> number1 = float (number_string1) >> number_string2=raw_input("How many miles have you driven?") >> number2 = float (number_string2) > > You will fin it easier if you use descriptive names for your variables. > > gallons and miles > would seem reasonable here... > >> try: >> model=float(model) >> except ValueError: >> pass > > This says if you get an error ignore it (ie pass). > But you don't want to ignore it, you want to get a valid value. > >> print "Your average number of miles to gallons is", >> print number1 / number2 > > HTH, > > > -- > Alan Gauld > 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 enalicho at gmail.com Wed Apr 27 23:11:00 2011 From: enalicho at gmail.com (Noah Hall) Date: Wed, 27 Apr 2011 22:11:00 +0100 Subject: [Tutor] Just started Python In-Reply-To: <04FEC6B4-308B-4004-9A86-7B1BC9402181@me.com> References: <0D64237F-47A8-4EF5-9932-7FC213BC7E19@me.com> <04FEC6B4-308B-4004-9A86-7B1BC9402181@me.com> Message-ID: On Wed, Apr 27, 2011 at 9:17 PM, Johnson Tran wrote: > Thanks for the reply Alan and Noah, I really appreciate the help. I am really trying to understand this although still cannot seem to grasp it all. I have modified my program although now it seems to be giving me the wrong answer with the correct answer when I input any value. > > I have program: > > model=raw_input("What kind of car do you drive?") > gallons=raw_input("How many gallons have you driven?") > number1 = float (gallons) > miles=raw_input("How many miles have you driven?") > number2 = float (miles) > > > try: > ? model=float(model) > except ValueError: > ? print "I cannot compute your total miles to gallon with those values." > else: > ? print "Your average number of miles to gallons is", > print number1 / number2 > > Output: > > What kind of car do you drive?fire > How many gallons have you driven?10 > How many miles have you driven?5 > I cannot compute your total miles to gallon with those values. Again, it's because you're "validating" the wrong variable. model is _not_ what you want to validate - it needs to be a string! gallons and miles are what you want to validate. So try moving your try: except: somewhere else, where it will validate the gallons and miles. From samudhio at gmail.com Wed Apr 27 23:35:04 2011 From: samudhio at gmail.com (Edgar Almonte) Date: Wed, 27 Apr 2011 17:35:04 -0400 Subject: [Tutor] Just started Python In-Reply-To: References: <0D64237F-47A8-4EF5-9932-7FC213BC7E19@me.com> <04FEC6B4-308B-4004-9A86-7B1BC9402181@me.com> Message-ID: try this : model=raw_input("What kind of car do you drive?") gallons=raw_input("How many gallons have you driven?") number1 = float (gallons) miles=raw_input("How many miles have you driven?") number2 = float (miles) try: number1 = float (gallons) number2 = float (miles) except ValueError: print "some values are wrong type." else: print "Your average number of miles to gallons is", print number1 / number2 On Wed, Apr 27, 2011 at 5:11 PM, Noah Hall wrote: > On Wed, Apr 27, 2011 at 9:17 PM, Johnson Tran wrote: >> Thanks for the reply Alan and Noah, I really appreciate the help. I am really trying to understand this although still cannot seem to grasp it all. I have modified my program although now it seems to be giving me the wrong answer with the correct answer when I input any value. >> >> I have program: >> >> model=raw_input("What kind of car do you drive?") >> gallons=raw_input("How many gallons have you driven?") >> number1 = float (gallons) >> miles=raw_input("How many miles have you driven?") >> number2 = float (miles) >> >> >> try: >> ? model=float(model) >> except ValueError: >> ? print "I cannot compute your total miles to gallon with those values." >> else: >> ? print "Your average number of miles to gallons is", >> print number1 / number2 >> >> Output: >> >> What kind of car do you drive?fire >> How many gallons have you driven?10 >> How many miles have you driven?5 >> I cannot compute your total miles to gallon with those values. > > Again, it's because you're "validating" the wrong variable. model is > _not_ what you want to validate - it needs to be a string! gallons and > miles are what you want to validate. So try moving your try: except: > somewhere else, where it will validate the gallons and miles. > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From steve at alchemy.com Wed Apr 27 23:39:00 2011 From: steve at alchemy.com (Steve Willoughby) Date: Wed, 27 Apr 2011 14:39:00 -0700 Subject: [Tutor] Just started Python In-Reply-To: References: <0D64237F-47A8-4EF5-9932-7FC213BC7E19@me.com> <04FEC6B4-308B-4004-9A86-7B1BC9402181@me.com> Message-ID: <4DB88CF4.8030109@alchemy.com> On 27-Apr-11 14:35, Edgar Almonte wrote: > try this : > > > > model=raw_input("What kind of car do you drive?") > gallons=raw_input("How many gallons have you driven?") > number1 = float (gallons) > miles=raw_input("How many miles have you driven?") > number2 = float (miles) > > > try: > number1 = float (gallons) > number2 = float (miles) Indentation error aside, you'll never reach that exception because the previous number1 = float(gallons) would raise one if the input was wrong. Either move the try..except block to enclose the first one, or wait until the try...except block to do the typecast. -- 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 alan.gauld at btinternet.com Thu Apr 28 00:13:37 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 27 Apr 2011 23:13:37 +0100 Subject: [Tutor] Just started Python References: <0D64237F-47A8-4EF5-9932-7FC213BC7E19@me.com> <04FEC6B4-308B-4004-9A86-7B1BC9402181@me.com> Message-ID: "Johnson Tran" wrote > Thanks for the reply Alan and Noah, I really appreciate > the help. I am really trying to understand this although > still cannot seem to grasp it all. Lets step back a stage. Do you understand what float() does? > I have modified my program although now it seems > to be giving me the wrong answer with the correct > answer when I input any value. > > model=raw_input("What kind of car do you drive?") > gallons=raw_input("How many gallons have you driven?") > number1 = float (gallons) This is taking the value typede by the user and trying to convert it from a string to a floating point number - that is, a decimal value > miles=raw_input("How many miles have you driven?") > number2 = float (miles) Similarly this converts the input string to a decimal value, if possible. > try: > model=float(model) But what is this doing? It is trying to convert the model of car to a decimal value. Unless trhe car is a Porche 911 or similar its unlikely to succeed! If its a Toyota Prius it will fail with a ValueError exception. > except ValueError: > print "I cannot compute your total miles to gallon with those > values." And therefore print this message > else: > print "Your average number of miles to gallons is", > print number1 / number2 The second print needs to be inside the else too. > What kind of car do you drive?fire > How many gallons have you driven?10 > How many miles have you driven?5 > I cannot compute your total miles to gallon with those values. Because it cannot convert 'fire' to a decimal value. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From samudhio at gmail.com Thu Apr 28 00:23:37 2011 From: samudhio at gmail.com (Edgar Almonte) Date: Wed, 27 Apr 2011 18:23:37 -0400 Subject: [Tutor] Just started Python In-Reply-To: <4DB88CF4.8030109@alchemy.com> References: <0D64237F-47A8-4EF5-9932-7FC213BC7E19@me.com> <04FEC6B4-308B-4004-9A86-7B1BC9402181@me.com> <4DB88CF4.8030109@alchemy.com> Message-ID: yes i just forget remove the previous one On Wed, Apr 27, 2011 at 5:39 PM, Steve Willoughby wrote: > On 27-Apr-11 14:35, Edgar Almonte wrote: >> >> try this : >> >> >> >> ?model=raw_input("What kind of car do you drive?") >> ?gallons=raw_input("How many gallons have you driven?") >> ?number1 = float (gallons) >> ?miles=raw_input("How many miles have you driven?") >> ?number2 = float (miles) >> >> >> ?try: >> number1 = float (gallons) >> number2 = float (miles) > > Indentation error aside, you'll never reach that exception because the > previous number1 = float(gallons) would raise one if the input was wrong. > ?Either move the try..except block to enclose the first one, or wait until > the try...except block to do the typecast. > -- > 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 > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From aznjonn at me.com Thu Apr 28 00:51:10 2011 From: aznjonn at me.com (Johnson Tran) Date: Wed, 27 Apr 2011 15:51:10 -0700 Subject: [Tutor] Just started Python In-Reply-To: References: <0D64237F-47A8-4EF5-9932-7FC213BC7E19@me.com> <04FEC6B4-308B-4004-9A86-7B1BC9402181@me.com> Message-ID: <2016D017-6D34-49ED-87CF-8AD11A92D5E1@me.com> Yeah, I'll be honest I did not really understand the float concept, thanks for explaining that =). So basically model does not have to be defined in try: because it does not need to be told to be put into point number? Okay so my final program is: model=raw_input("What kind of car do you drive?") gallons=raw_input("How many gallons have you driven?") miles=raw_input("How many miles have you driven?") try: number1 = float(gallons) number2 = float(miles) except ValueError: print "some values are wrong type." else: print "Your average number of miles to gallons is", print number1 / number2 Thanks guys created my first successful program ! =D On Apr 27, 2011, at 3:13 PM, Alan Gauld wrote: > > "Johnson Tran" wrote > >> Thanks for the reply Alan and Noah, I really appreciate >> the help. I am really trying to understand this although >> still cannot seem to grasp it all. > > Lets step back a stage. > > Do you understand what float() does? > >> I have modified my program although now it seems >> to be giving me the wrong answer with the correct >> answer when I input any value. >> >> model=raw_input("What kind of car do you drive?") >> gallons=raw_input("How many gallons have you driven?") >> number1 = float (gallons) > > This is taking the value typede by the user and trying > to convert it from a string to a floating point number - that is, > a decimal value > >> miles=raw_input("How many miles have you driven?") >> number2 = float (miles) > > Similarly this converts the input string to a decimal value, > if possible. > >> try: >> model=float(model) > > But what is this doing? > > It is trying to convert the model of car to a decimal value. > Unless trhe car is a Porche 911 or similar its unlikely > to succeed! If its a Toyota Prius it will fail with a ValueError > exception. > >> except ValueError: >> print "I cannot compute your total miles to gallon with those values." > > And therefore print this message > >> else: >> print "Your average number of miles to gallons is", >> print number1 / number2 > > The second print needs to be inside the else too. > >> What kind of car do you drive?fire >> How many gallons have you driven?10 >> How many miles have you driven?5 >> I cannot compute your total miles to gallon with those values. > > Because it cannot convert 'fire' to a decimal value. > > HTH, > > > -- > Alan Gauld > 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 alan.gauld at btinternet.com Thu Apr 28 02:05:55 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 28 Apr 2011 01:05:55 +0100 Subject: [Tutor] Just started Python References: <0D64237F-47A8-4EF5-9932-7FC213BC7E19@me.com><04FEC6B4-308B-4004-9A86-7B1BC9402181@me.com> <2016D017-6D34-49ED-87CF-8AD11A92D5E1@me.com> Message-ID: "Johnson Tran" wrote > Okay so my final program is: It works but you can improve it slightly with a simple change. > model=raw_input("What kind of car do you drive?") > gallons=raw_input("How many gallons have you driven?") > miles=raw_input("How many miles have you driven?") > > try: > number1 = float(gallons) > number2 = float(miles) Combine these two groups of lines so that you detect the errors as soon as possible.: try: model=raw_input("What kind of car do you drive?") gallons=raw_input("How many gallons have you driven?") number1 = float(gallons) miles=raw_input("How many miles have you driven?") number2 = float(miles) Now the user gets prompted as soon as they enter a wrong number, they don't need to guess which one was wrong... except ValueError: print "That value is the wrong type, please use a number." And so we can make the message more specific too. > else: > print "Your average number of miles to gallons is", > print number1 / number2 HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From aznjonn at me.com Thu Apr 28 02:13:39 2011 From: aznjonn at me.com (Johnson Tran) Date: Wed, 27 Apr 2011 17:13:39 -0700 Subject: [Tutor] Just started Python In-Reply-To: References: <0D64237F-47A8-4EF5-9932-7FC213BC7E19@me.com> <04FEC6B4-308B-4004-9A86-7B1BC9402181@me.com> <2016D017-6D34-49ED-87CF-8AD11A92D5E1@me.com> Message-ID: <847F12E2-08D1-4F61-90ED-32959D53FE7B@me.com> Ahh, I was wondering about why it didn't show the error message on the first variable. Makes sense, thanks again. Sent from my iPhone On Apr 27, 2011, at 5:05 PM, Alan Gauld wrote: > > "Johnson Tran" wrote >> Okay so my final program is: > > It works but you can improve it slightly with a simple change. > >> model=raw_input("What kind of car do you drive?") >> gallons=raw_input("How many gallons have you driven?") >> miles=raw_input("How many miles have you driven?") >> try: >> number1 = float(gallons) >> number2 = float(miles) > > Combine these two groups of lines so that you detect the errors as soon as possible.: > > try: > model=raw_input("What kind of car do you drive?") > gallons=raw_input("How many gallons have you driven?") > number1 = float(gallons) > miles=raw_input("How many miles have you driven?") > number2 = float(miles) > > Now the user gets prompted as soon as they enter a wrong number, they don't need to guess which one was wrong... > > except ValueError: > print "That value is the wrong type, please use a number." > > And so we can make the message more specific too. > >> else: >> print "Your average number of miles to gallons is", >> print number1 / number2 > > HTH, > > -- > Alan Gauld > 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 outsideme99 at live.com Thu Apr 28 03:25:28 2011 From: outsideme99 at live.com (Brad Desautels) Date: Wed, 27 Apr 2011 21:25:28 -0400 Subject: [Tutor] NameError? Message-ID: Hello, I am working on a problem for my computer science class. This program is supposed to change the expression of the face when the appropriate button is clicked. It seems logical that it should work, however, when I click one of the buttons, I get "NameError: global name 'window' is not defined". # face.py from graphics import * class Face: """A class to display a face in a graphics window and change expression""" def __init__(self, window, center, size): """Defines the method for creating a face""" eyeSize = .15 * size eyeOff = size/3 mouthSize = .8 * size mouthOff = size/2 self.head = Circle(center, size) self.head.draw(window) self.leftEye = Circle(center, eyeSize) self.leftEye.move(-eyeOff, -eyeOff) self.rightEye = Circle(center, eyeSize) self.rightEye.move(eyeOff, -eyeOff) self.leftEye.draw(window) self.rightEye.draw(window) p1 = center.clone() p1.move(-mouthSize/2, mouthOff) p2 = center.clone() p2.move(mouthSize/2, mouthOff) self.mouth = Line(p1,p2) self.mouth.draw(window) def makeOpen(self): """Defines the method for making the mouth open""" self.mouth.undraw() self.mouth = Oval(Point(170,375),Point(330,325)) self.mouth.draw(window) def makeWow(self): """Defines the method for making the face frown""" self.mouth.undraw() self.mouth = Circle(Point(250,350),50) self.mouth.draw(window) def makeWink(self): """Defines the method for making the face wink""" self.rightEye.undraw() self.rightEye=Line(Point(290,190),Point(334,190)) self.rightEye.draw(window) def makeDefault(self): """Defines the methof for returning the face to default position""" self.mouth.undraw() self.rightEye.undraw() self.mouth = Line(Point(170,350),Point(330,350)) self.rightEye = Circle(Point((250+(200/3)),(250-(200/3))), 30) self.mouth.draw(window) self.rightEye.draw(window) class Button: """Creates buttons to activate methods""" def __init__(self,window,center,width,height,label): """Creates button""" w,h = width/2.0, height/2.0 x,y = center.getX(), center.getY() self.xmax, self.xmin = x+w,x-w self.ymax, self.ymin = y+h,y-h p1 = Point(self.xmin, self.ymin) p2 = Point(self.xmax, self.ymax) self.rect = Rectangle(p1,p2) self.rect.setFill('gray') self.rect.draw(window) self.label = Text(center,label) self.label.draw(window) def clicked(self, p): return(self.xmin<=p.getX()<=self.xmax and self.ymin<=p.getY()<=self.ymax) def main(): window = GraphWin("Face Window",500,500) face = Face(window, Point(250,250), 200) button1 = Button(window,Point(50,400),90,25,"Open Mouth") button2 = Button(window,Point(50,425),90,25,"Wow") button3 = Button(window,Point(50,450),90,25,"Wink") button4 = Button(window,Point(50,475),90,25,"Default") button5 = Button(window,Point(50,25),90,25,"Close") click = window.getMouse() while not button5.clicked(click): if button1.clicked(click): face.makeOpen() elif button2.clicked(click): face.makeWow() elif button3.clicked(click): face.makeWink() elif button4.clicked(click): face.makeDefault() elif button5.clicked(click): break window.close() main() -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Thu Apr 28 04:49:26 2011 From: davea at ieee.org (Dave Angel) Date: Wed, 27 Apr 2011 22:49:26 -0400 Subject: [Tutor] NameError? In-Reply-To: References: Message-ID: <4DB8D5B6.1040707@ieee.org> On 01/-10/-28163 02:59 PM, Brad Desautels wrote: > Hello, I am working on a problem for my computer science class. This program > is supposed to change the expression of the face when the appropriate button > is clicked. It seems logical that it should work, however, when I click one > of the buttons, I get "NameError: global name 'window' is not defined". > > # face.py > > from graphics import * > > class Face: > """A class to display a face in a graphics window and change > expression""" > def __init__(self, window, center, size): > """Defines the method for creating a face""" > eyeSize = .15 * size > eyeOff = size/3 > mouthSize = .8 * size > mouthOff = size/2 > self.head = Circle(center, size) > self.head.draw(window) > self.leftEye = Circle(center, eyeSize) > self.leftEye.move(-eyeOff, -eyeOff) > self.rightEye = Circle(center, eyeSize) > self.rightEye.move(eyeOff, -eyeOff) > self.leftEye.draw(window) > self.rightEye.draw(window) > p1 = center.clone() > p1.move(-mouthSize/2, mouthOff) > p2 = center.clone() > p2.move(mouthSize/2, mouthOff) > self.mouth = Line(p1,p2) > self.mouth.draw(window) > def makeOpen(self): > """Defines the method for making the mouth open""" > self.mouth.undraw() > self.mouth = Oval(Point(170,375),Point(330,325)) > self.mouth.draw(window) > def makeWow(self): > """Defines the method for making the face frown""" > self.mouth.undraw() > self.mouth = Circle(Point(250,350),50) > self.mouth.draw(window) > def makeWink(self): > """Defines the method for making the face wink""" > self.rightEye.undraw() > self.rightEye=Line(Point(290,190),Point(334,190)) > self.rightEye.draw(window) > def makeDefault(self): > """Defines the methof for returning the face to default position""" > self.mouth.undraw() > self.rightEye.undraw() > self.mouth = Line(Point(170,350),Point(330,350)) > self.rightEye = Circle(Point((250+(200/3)),(250-(200/3))), 30) > self.mouth.draw(window) > self.rightEye.draw(window) > > class Button: > """Creates buttons to activate methods""" > def __init__(self,window,center,width,height,label): > """Creates button""" > w,h = width/2.0, height/2.0 > x,y = center.getX(), center.getY() > self.xmax, self.xmin = x+w,x-w > self.ymax, self.ymin = y+h,y-h > p1 = Point(self.xmin, self.ymin) > p2 = Point(self.xmax, self.ymax) > self.rect = Rectangle(p1,p2) > self.rect.setFill('gray') > self.rect.draw(window) > self.label = Text(center,label) > self.label.draw(window) > def clicked(self, p): > return(self.xmin<=p.getX()<=self.xmax and > self.ymin<=p.getY()<=self.ymax) > > def main(): > window = GraphWin("Face Window",500,500) > face = Face(window, Point(250,250), 200) > button1 = Button(window,Point(50,400),90,25,"Open Mouth") > button2 = Button(window,Point(50,425),90,25,"Wow") > button3 = Button(window,Point(50,450),90,25,"Wink") > button4 = Button(window,Point(50,475),90,25,"Default") > button5 = Button(window,Point(50,25),90,25,"Close") > click = window.getMouse() > while not button5.clicked(click): > if button1.clicked(click): > face.makeOpen() > elif button2.clicked(click): > face.makeWow() > elif button3.clicked(click): > face.makeWink() > elif button4.clicked(click): > face.makeDefault() > elif button5.clicked(click): > break > window.close() > main() > To begin with, you should actually post the error message, including its traceback. But in this case, you have many instances of the same error, so it doesn't really matter. Next, you should mention where you get this foreign import, "graphics". It's not standard Python, nor one of the common ones discussed here all the time. Anyway, the error will occur when you call any method on the Face class, since they all refer to window, without being passed such a name as a parameter. I can only guess what your graphics library wants, but assuming it's the same as the argument passed to __init__(), then you could save it there, and use the saved instance attribute whenever your other methods need it. To the __init__() method, add self.window = window and in the other methods, when you want to refer to it, use self.window, rather than window. For example, the last line in makeOpen might become self.mouth.draw(self.window) HTH DaveA From l.leichtnam at gmail.com Thu Apr 28 05:41:02 2011 From: l.leichtnam at gmail.com (l.leichtnam at gmail.com) Date: Thu, 28 Apr 2011 03:41:02 +0000 Subject: [Tutor] Pictures Message-ID: <1669823197-1303962063-cardhu_decombobulator_blackberry.rim.net-2126492393-@bda740.bisx.prod.on.blackberry> Hello, I'm still quite new at this but I'm trying to get a list of the pictures adress (... .jpg) of a page of a website. I thought of using the import urllib and import re, trying to fetch the website, parse it, and collect the adresses but I don't know how to do it... Can you help me? Thanks Sent from my BlackBerry? on the MetroPCS Network From waynejwerner at gmail.com Thu Apr 28 07:02:43 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Thu, 28 Apr 2011 00:02:43 -0500 Subject: [Tutor] Pictures In-Reply-To: <1669823197-1303962063-cardhu_decombobulator_blackberry.rim.net-2126492393-@bda740.bisx.prod.on.blackberry> References: <1669823197-1303962063-cardhu_decombobulator_blackberry.rim.net-2126492393-@bda740.bisx.prod.on.blackberry> Message-ID: On Wed, Apr 27, 2011 at 10:41 PM, wrote: > Hello, > > I'm still quite new at this but I'm trying to get a list of the pictures > adress (... .jpg) of a page of a website. > > I thought of using the import urllib and import re, trying to fetch the > website, parse it, and collect the adresses but I don't know how to do it... > > Can you help me? > You should take a look at the lxml and or BeautifulSoup modules (I recommend lxml as it's still being developed on). You also might search for "image scraping with python" in your favorite search engine. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From rsachdev at usc.edu Thu Apr 28 10:26:54 2011 From: rsachdev at usc.edu (Rohan Sachdeva) Date: Thu, 28 Apr 2011 01:26:54 -0700 Subject: [Tutor] Python 3.2 Install Not Responding To Python Command!! In-Reply-To: References: <4DA08CE7.3060606@bellsouth.net> <4DA0A93A.6080806@bellsouth.net> Message-ID: I know this was a while ago but you can add the ppa by going to the terminal and typing: sudo add-apt-repository ppa:irie/python3.2 then sudo apt-get update and sudo apt-get install python3.2 Rohan On Sun, Apr 10, 2011 at 1:33 PM, Walter Prins wrote: > > > On 9 April 2011 19:45, Nevins Duret wrote: > >> I can't thank you enough for your help. Yes, I usually use the Synaptic >> Package Manager, however in this case, Python version 3.2 is not on the >> Synaptic package Manager. This is why I chose to build it from source. As >> far as what I think is causing this when I go in the >> > > No problem. > > >> Terminal and type: >> >> sudo update-alternatives --install /usr/bin/python/python3.2 python >> /opt/py32/bin/python3.2 1 >> >> I get this as an error message: >> >> update-alternatives: renaming python link from /usr/bin/python to >> /usr/bin/python/python3.2. >> update-alternatives: warning: forcing reinstallation of alternative >> /opt/py32/bin because link group python is broken. >> update-alternatives: error: unable to make >> /usr/bin/python/python3.2.dpkg-tmp a symlink to /etc/alternatives/python: No >> such file or directory >> > > I would expect that "update-alternatives" would have trouble (on the first > line) because /usr/bin/python is not a link anymore (but instead a folder) > based on your previous posts. > > So, please go and inspect the /usr/bin/python folder and see what if > anything's inside. If it's not empty you need to see what is in fact in it > and hopefully get rid of it or move it out of the way. Once it's empty, then > just delete the /usr/bin/python folder (you'll have to be root or use > "sudo") and afterwards either recreate a link to the default python > interpreter and/or try the update-alternatives command again. (To manually > restore the default python link, first execute "which python2.6" which > should output "/usr/bin/python2.6", then execute "sudo ln -s > /usr/bin/python2.6 /usr/bin/python" which should restore the link to the > default python. After doing this "update-alternatives" should have less > trouble redirecting the /usr/bin/python link. > > I however want to reiterate that your problems, especially fixing your OS, > will be better dealt with on the Ubuntu community forums. > > Rohan, thanks for posting about that PPA, wasn't aware of it! > > Walter > > > > _______________________________________________ > 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 Thu Apr 28 14:48:00 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 28 Apr 2011 08:48:00 -0400 Subject: [Tutor] Pictures In-Reply-To: <1669823197-1303962063-cardhu_decombobulator_blackberry.rim.net-2126492393-@bda740.bisx.prod.on.blackberry> References: <1669823197-1303962063-cardhu_decombobulator_blackberry.rim.net-2126492393-@bda740.bisx.prod.on.blackberry> Message-ID: On Wed, Apr 27, 2011 at 11:41 PM, wrote: > Hello, > > I'm still quite new at this but I'm trying to get a list of the pictures > adress (... .jpg) of a page of a website. > > I thought of using the import urllib and import re, trying to fetch the > website, parse it, and collect the adresses but I don't know how to do it... > > Can you help me? > > Thanks > Sent from my BlackBerry? on the MetroPCS Network > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > What have you tried? First try to learn how to read a web page. You are right to look into urlib and urlib2. Its only a handful of lines of code to open a web page and retrieve it to your system. Once you do that there is a package called beautiful soup that is a good tool to read through the tags in the page Let us know how you are doing. -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From naheedcse at gmail.com Thu Apr 28 15:18:55 2011 From: naheedcse at gmail.com (naheed arafat) Date: Thu, 28 Apr 2011 19:18:55 +0600 Subject: [Tutor] Pictures In-Reply-To: References: <1669823197-1303962063-cardhu_decombobulator_blackberry.rim.net-2126492393-@bda740.bisx.prod.on.blackberry> Message-ID: On Thu, Apr 28, 2011 at 6:48 PM, Joel Goldstick wrote: > > > On Wed, Apr 27, 2011 at 11:41 PM, wrote: > >> Hello, >> >> I'm still quite new at this but I'm trying to get a list of the pictures >> adress (... .jpg) of a page of a website. >> >> I thought of using the import urllib and import re, trying to fetch the >> website, parse it, and collect the adresses but I don't know how to do it... >> >> Can you help me? >> >> may i know the url of that page? and give a try? > -------------- next part -------------- An HTML attachment was scrubbed... URL: From naheedcse at gmail.com Thu Apr 28 17:03:58 2011 From: naheedcse at gmail.com (naheed arafat) Date: Thu, 28 Apr 2011 21:03:58 +0600 Subject: [Tutor] Pictures In-Reply-To: <1669823197-1303962063-cardhu_decombobulator_blackberry.rim.net-2126492393-@bda740.bisx.prod.on.blackberry> References: <1669823197-1303962063-cardhu_decombobulator_blackberry.rim.net-2126492393-@bda740.bisx.prod.on.blackberry> Message-ID: Observing the page source i think : page=urllib.urlopen('http://finance.blog.lemonde.fr').read() x=re.findall(r" From bill at celestial.net Thu Apr 28 22:24:16 2011 From: bill at celestial.net (Bill Campbell) Date: Thu, 28 Apr 2011 13:24:16 -0700 Subject: [Tutor] distutils site.cfg variable expansion Message-ID: <20110428202416.GA30235@ayn.mi.celestial.com> I'm learning my way around package building using setuptools, and would like to have scripts for a system administration package installed under $(prefix)/sbin instead of under the default $(prefix)/bin directory without requiring the installer to use the manual 'python setup.py install --install-scripts=...'. I would like to have something in the setup.cfg file like this which would be handled by the normal ConfigParser expansion. Either I have the syntax wrong, or the setuptools/distutils configuration parsing is different. [global] prefix=/path/to/prefix [install] install-scripts=%(prefix)s/sbin Better yet would be for the prefix to be available from the command line or taken from sys.prefix if not specified. Is there a way to do this other than fiddling the site.cfg file? Bill -- INTERNET: bill at celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax: (206) 232-9186 Skype: jwccsllc (206) 855-5792 In a nation ruled by swine, all pigs are upwardly mobile. -- Hunter S. Thompson From goodpotatoes at yahoo.com Thu Apr 28 23:18:38 2011 From: goodpotatoes at yahoo.com (GoodPotatoes) Date: Thu, 28 Apr 2011 14:18:38 -0700 (PDT) Subject: [Tutor] Calling a python script using subprocess Message-ID: <402662.28730.qm@web39308.mail.mud.yahoo.com> I am trying to execute a python script using the subprocess module.? I am feeding parameters into the script, which reads them using argparse and returns a list. The script simply returns a list when called.? When I execute my script from my prompt, I get the following: H:\pythonscripts>installModule.pyc --mods mod1 mod2 mod3 ['mod1', 'mod2', 'mod3'] # This is the result I would like ? ? When I call the script from within another script using subprocess I get an error: ? p = subprocess.Popen(r'installModule.py --mods mod1 mod2 mod3', executable = sys.executable, stdout = subprocess.PIPE, stderr = subprocess.STDOUT) ? 'Unknown option: --\r\n' 'usage: installModule.py [option] ... [-c cmd | -m mod | file | -] [arg] ...\r\n' ? Is the subprocess module the best thing for me to use?? Is there a better way to call this script? -------------- next part -------------- An HTML attachment was scrubbed... URL: From prologic at shortcircuit.net.au Fri Apr 29 02:41:32 2011 From: prologic at shortcircuit.net.au (James Mills) Date: Fri, 29 Apr 2011 10:41:32 +1000 Subject: [Tutor] Calling a python script using subprocess In-Reply-To: <402662.28730.qm@web39308.mail.mud.yahoo.com> References: <402662.28730.qm@web39308.mail.mud.yahoo.com> Message-ID: On Fri, Apr 29, 2011 at 7:18 AM, GoodPotatoes wrote: > > p = subprocess.Popen(r'installModule.py --mods mod1 mod2 mod3', executable = sys.executable, stdout = subprocess.PIPE, stderr = subprocess.STDOUT) Try this (untested): p = subprocess.Popen(["/usr/bin/env python", "installModule.py", "--mods", "mod1", "mod2", "mod3"], stdout = subprocess.PIPE, stderr = subprocess.STDOUT) cheers James -- -- James Mills -- -- "Problems are solved by method" From monkey415 at aim.com Fri Apr 29 02:08:19 2011 From: monkey415 at aim.com (monkey415 at aim.com) Date: Thu, 28 Apr 2011 20:08:19 -0400 Subject: [Tutor] Help with sys.argv Message-ID: <8CDD418ADE8BC19-17A8-6616@webmail-m101.sysops.aol.com> Hello, I am trying to learn how to use python with Facebook's Open Graph API. I am getting my feet wet with the following code authored by Matthew A. Russell. I copied it line for line for learning purposes, but I am getting the following error: Traceback (most recent call last): File "C:\Python27\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 325, in RunScript exec codeObject in __main__.__dict__ File "C:\Python27\Scripts\facebook__query.py", line 20, in Q = sys.argv[1] IndexError: list index out of range Here is the code that this error is resulting from: #Querying the Open Graph for "programming" groups import sys import json import facebook import urllib2 from facebook__login import login try: ACCESS_TOKEN = open('C:\Users\Jon\Documents\FacebookApps\facebook.access_token').read() except IOError, e: try: #Page 283 in Mining... for notes ACCESS_TOKEN = sys.argv[1] Q = sys.argv[2] except: print >> sys.stderr, \ "Could not either find access token in 'C:\Users\Jon\Documents\FacebookApps\facebook.access_token' or parse args." ACCESS_TOKEN = login() Q = sys.argv[1] LIMIT = 100 gapi = facebook.GraphAPI(ACCESS_TOKEN) ... ... Clearly this has something to do with sys.argv[1], and I think I'm getting an IOError somewhere along the line. I have tried quite hard to figure this out on my own using the Python tutorial, Google, and the book in which the code was found to no avail. Please help! Thanks, Jon -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Fri Apr 29 12:47:16 2011 From: davea at ieee.org (Dave Angel) Date: Fri, 29 Apr 2011 06:47:16 -0400 Subject: [Tutor] Help with sys.argv In-Reply-To: <8CDD418ADE8BC19-17A8-6616@webmail-m101.sysops.aol.com> References: <8CDD418ADE8BC19-17A8-6616@webmail-m101.sysops.aol.com> Message-ID: <4DBA9734.50106@ieee.org> On 01/-10/-28163 02:59 PM, monkey415 at aim.com wrote: > Hello, > > I am trying to learn how to use python with Facebook's Open Graph API. I am getting my feet wet with the following code authored by Matthew A. Russell. I copied it line for line for learning purposes, but I am getting the following error: > > Traceback (most recent call last): > File "C:\Python27\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 325, in RunScript > exec codeObject in __main__.__dict__ > File "C:\Python27\Scripts\facebook__query.py", line 20, in > Q = sys.argv[1] > IndexError: list index out of range > > > Here is the code that this error is resulting from: > > #Querying the Open Graph for "programming" groups > > import sys > import json > import facebook > import urllib2 > from facebook__login import login > > try: > ACCESS_TOKEN = open('C:\Users\Jon\Documents\FacebookApps\facebook.access_token').read() > except IOError, e: > try: > #Page 283 in Mining... for notes > ACCESS_TOKEN = sys.argv[1] > Q = sys.argv[2] > except: > print>> sys.stderr, \ > "Could not either find access token in 'C:\Users\Jon\Documents\FacebookApps\facebook.access_token' or parse args." > ACCESS_TOKEN = login() > Q = sys.argv[1] > > LIMIT = 100 > > gapi = facebook.GraphAPI(ACCESS_TOKEN) > ... > ... > > > Clearly this has something to do with sys.argv[1], and I think I'm getting an IOError somewhere along the line. > > I have tried quite hard to figure this out on my own using the Python tutorial, Google, and the book in which the code was found to no avail. Please help! > > Thanks, > Jon > > > Usually, the first thing to do is to print sys.argv and see what it looks like. If it has only one element in it, then you'd expect that sys.argv[1] would give exactly that error. sys.argv[0] is the only element. Next, look up argv in the Python docs. See http://docs.python.org/library/sys.html?highlight=argv#sys.argv for a description. In particular, if you didn't pass any arguments to the script, then argv will be of size 1, and you'll get the error you saw. Fix is to add a check for len(sys.argv) to be greater than or equal to however many arguments you need, and display an error and exit if not. DaveA From duretn at bellsouth.net Fri Apr 29 14:38:17 2011 From: duretn at bellsouth.net (Nevins Duret) Date: Fri, 29 Apr 2011 08:38:17 -0400 Subject: [Tutor] Python 3.2 Install Not Responding To Python Command!! In-Reply-To: References: <4DA08CE7.3060606@bellsouth.net> <4DA0A93A.6080806@bellsouth.net> Message-ID: <62688680-7034-44E0-8867-328869C9C4D6@bellsouth.net> Hello Rohan, I can't thank you enough but believe it or not, you guys helped me tremendously on the last posting. It was basically a symbolic link issue that was reeked havoc on my system. After reinstating the symbolic link to where I had it as before and deleting the file that the symbolic link created I was able to update, as I was not able to do this before, as a result of python being broken, and then adding the repository link graphically using the update manager!! Thanks so much for all your help, now I know how to do it through the Terminal!!! Sent from Nevins Duret's Mobile On Apr 28, 2011, at 4:26 AM, Rohan Sachdeva wrote: > I know this was a while ago but you can add the ppa by going to the terminal and typing: > > sudo add-apt-repository ppa:irie/python3.2 > > then sudo apt-get update and sudo apt-get install python3.2 > > Rohan > > On Sun, Apr 10, 2011 at 1:33 PM, Walter Prins wrote: > > > On 9 April 2011 19:45, Nevins Duret wrote: > I can't thank you enough for your help. Yes, I usually use the Synaptic Package Manager, however in this case, Python version 3.2 is not on the Synaptic package Manager. This is why I chose to build it from source. As far as what I think is causing this when I go in the > > No problem. > > Terminal and type: > > sudo update-alternatives --install /usr/bin/python/python3.2 python /opt/py32/bin/python3.2 1 > > I get this as an error message: > > update-alternatives: renaming python link from /usr/bin/python to /usr/bin/python/python3.2. > update-alternatives: warning: forcing reinstallation of alternative /opt/py32/bin because link group python is broken. > update-alternatives: error: unable to make /usr/bin/python/python3.2.dpkg-tmp a symlink to /etc/alternatives/python: No such file or directory > > I would expect that "update-alternatives" would have trouble (on the first line) because /usr/bin/python is not a link anymore (but instead a folder) based on your previous posts. > > So, please go and inspect the /usr/bin/python folder and see what if anything's inside. If it's not empty you need to see what is in fact in it and hopefully get rid of it or move it out of the way. Once it's empty, then just delete the /usr/bin/python folder (you'll have to be root or use "sudo") and afterwards either recreate a link to the default python interpreter and/or try the update-alternatives command again. (To manually restore the default python link, first execute "which python2.6" which should output "/usr/bin/python2.6", then execute "sudo ln -s /usr/bin/python2.6 /usr/bin/python" which should restore the link to the default python. After doing this "update-alternatives" should have less trouble redirecting the /usr/bin/python link. > > I however want to reiterate that your problems, especially fixing your OS, will be better dealt with on the Ubuntu community forums. > > Rohan, thanks for posting about that PPA, wasn't aware of it! > > Walter > > > > _______________________________________________ > 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: