From hugo.yoshi at gmail.com Wed Jun 1 00:02:22 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Wed, 1 Jun 2011 00:02:22 +0200 Subject: [Tutor] checking if a variable is an integer? In-Reply-To: References: <4DE561B0.9090306@solderintheveins.co.uk> Message-ID: ---------- Forwarded message ---------- From: Hugo Arts Date: Wed, Jun 1, 2011 at 12:01 AM Subject: Re: [Tutor] checking if a variable is an integer? To: Peter Lavelle On Tue, May 31, 2011 at 11:46 PM, Peter Lavelle wrote: > I think you could also use the type() function. See example below: > > if type(yourvar) == int: > ??? #Do stuff here if it is an integer > > else: > ???? #Do something here if it is not an integer > I think the isinstance() function is preferred since it also catches subclasses: http://docs.python.org/library/functions.html#isinstance Hugo From steve at pearwood.info Wed Jun 1 00:13:28 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 01 Jun 2011 08:13:28 +1000 Subject: [Tutor] checking if a variable is an integer? In-Reply-To: <4DE561B0.9090306@solderintheveins.co.uk> References: <4DE561B0.9090306@solderintheveins.co.uk> Message-ID: <4DE56808.9020300@pearwood.info> Peter Lavelle wrote: > I think you could also use the type() function. See example below: > > if type(yourvar) == int: > #Do stuff here if it is an integer You can do that, but that will miss out on subclasses of int. It is better to use isinstance(yourvar, int) which will accept an int, or a subclass of int. In Python 2.x (but not 3) you should also test for long: isinstance(yourvar, (int, long)) But for some purposes, it might be even better to use duck typing ("if it quacks like a duck, swims like a duck, and looks like a duck, it probably is a duck"): def is_int_value(obj): try: return int(x) == x except (TypeError, ValueError): return False This will accept as an integer values like Fraction(5, 1), Decimal("23.0") or 42.0, as well as the usual ints 5, 23 or 42 ... -- Steven From steve at pearwood.info Wed Jun 1 00:22:18 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 01 Jun 2011 08:22:18 +1000 Subject: [Tutor] checking if a variable is an integer? In-Reply-To: References: Message-ID: <4DE56A1A.1020801@pearwood.info> Rachel-Mikel ArceJaeger wrote: > Isn't one of the unsolved millenium prize problems one that includes the ability to find all of the prime numbers? I'm not sure if your program is possible if the input number is large. Finding all the prime numbers isn't hard. Well, it's not hard if you have an infinite amount of memory and time :) But the process for finding them, as many as you want, has been well-known since ancient Greece. For big primes, with hundreds of digits, it gets a bit slow, but there are tricks to speed it up. However, discovering a formula that generates the primes and nothing but the primes, fast, would be worthy of the Fields Medal (like the Nobel Prize for mathematics). -- Steven From alan.gauld at btinternet.com Wed Jun 1 00:48:11 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 31 May 2011 23:48:11 +0100 Subject: [Tutor] checking if a variable is an integer? References: Message-ID: "Hans Barkei" wrote >I want to make a program that finds all the prime numbers up to a >number > inputed by the user. > I want to know if it is an integer because that will tell me if it > is > divisible by that number or not. I assume you meant the result of the division? If so it is better to use the modulo operator as Hugo suggested. There are several algorithms for this, search the internet (wikipedia under primes is a good start). Otherwise you will write a lot of unnecessary code and perform even more unnecessary calculations.... -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From karim.liateni at free.fr Wed Jun 1 01:00:35 2011 From: karim.liateni at free.fr (Karim) Date: Wed, 01 Jun 2011 01:00:35 +0200 Subject: [Tutor] Strategy to read a redirecting html page Message-ID: <4DE57313.3040808@free.fr> Hello, I am having issue in reading a html page which is redirected to a new page. I get the first warning/error message page and not the redirection one. Should I request a second time the same url page or Should I loop forever until the page content is the correct (by parsing it) one? Do you have a better strategy or perhaps some modules deal w/ that issue? I am using python 2.7.1 on Linux ubuntu 11.04 and the modules urllib2, urllib, etc... The webpage is secured but I registered a password manager. cheers karim From hugo.yoshi at gmail.com Wed Jun 1 01:34:26 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Wed, 1 Jun 2011 01:34:26 +0200 Subject: [Tutor] Strategy to read a redirecting html page In-Reply-To: <4DE57313.3040808@free.fr> References: <4DE57313.3040808@free.fr> Message-ID: On Wed, Jun 1, 2011 at 1:00 AM, Karim wrote: > > Hello, > > I am having issue in reading a html page which is redirected to a new page. > I get the first warning/error message page and not the redirection one. > Should I request a second time the same url page or Should I loop forever > until the > page content is the correct (by parsing it) one? > Do you have a better strategy or perhaps some modules deal w/ that issue? > I am using python 2.7.1 on Linux ubuntu 11.04 and the modules urllib2, > urllib, etc... > The webpage is secured but I registered a password manager. > urllib2 works at the HTTP level, so it can't catch redirects that happen at the HTML level unfortunately. You'll have to parse the page, look for a References: <4DE57313.3040808@free.fr> Message-ID: <4DE57C48.3030508@iandouglas.com> On 05/31/2011 04:34 PM, Hugo Arts wrote: > On Wed, Jun 1, 2011 at 1:00 AM, Karim wrote: >> Hello, >> >> I am having issue in reading a html page which is redirected to a new page. >> I get the first warning/error message page and not the redirection one. >> Should I request a second time the same url page or Should I loop forever >> until the >> page content is the correct (by parsing it) one? >> Do you have a better strategy or perhaps some modules deal w/ that issue? >> I am using python 2.7.1 on Linux ubuntu 11.04 and the modules urllib2, >> urllib, etc... >> The webpage is secured but I registered a password manager. >> > urllib2 works at the HTTP level, so it can't catch redirects that > happen at the HTML level unfortunately. You'll have to parse the page, > look for a That's a pretty simple parsing job, probably doable with regexes. But > you're free to use a proper html parser of course. > Also, given that the 301/302 redirect you get in that response could ALSO redirect, I'd suggest looping until a counter is exhausted, so you don't end up in an infinite loop if pages redirect to each other. -id From alexandre.conrad at gmail.com Wed Jun 1 01:41:02 2011 From: alexandre.conrad at gmail.com (Alexandre Conrad) Date: Tue, 31 May 2011 16:41:02 -0700 Subject: [Tutor] Strategy to read a redirecting html page In-Reply-To: <4DE57313.3040808@free.fr> References: <4DE57313.3040808@free.fr> Message-ID: Hi Karim, When you hit the page and you get an HTTP redirect code back (say, 302), you will need to make another call to the URL specified in the "Location" parameter in the response headers. Then you retrieve that new page and you can check you got an acceptable HTTP response code (such as 200) and read the page's body (or whatever you want to do with it). Otherwise, keep looping until you get an expected HTTP response code. Note: you may get stuck in an infinite loop if two URLs redirect to each other. You might want to take a look at the higher level httplib module: http://docs.python.org/library/httplib.html Although I don't think it can automatically follow redirects for you. You'll have to implement the loop yourself. If you can rely on 3rd party packages (not part of the standard Python library), take a look at httplib2: https://httplib2.googlecode.com/hg/doc/html/libhttplib2.html This one can follow redirects. HTH, 2011/5/31 Karim : > > Hello, > > I am having issue in reading a html page which is redirected to a new page. > I get the first warning/error message page and not the redirection one. > Should I request a second time the same url page or Should I loop forever > until the > page content is the correct (by parsing it) one? > Do you have a better strategy or perhaps some modules deal w/ that issue? > I am using python 2.7.1 on Linux ubuntu 11.04 and the modules urllib2, > urllib, etc... > The webpage is secured but I registered a password manager. > > cheers > karim > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Alex | twitter.com/alexconrad From marilyn at pythontrainer.com Wed Jun 1 01:44:53 2011 From: marilyn at pythontrainer.com (Marilyn Davis) Date: Tue, 31 May 2011 16:44:53 -0700 (PDT) Subject: [Tutor] __init__.py question Message-ID: <39060.67.169.189.143.1306885493.squirrel@mail.tigertech.net> I don't really understand why __init__.py is necessary -- except that it makes the packaging scheme work. The Python Manual by Guido van Rossum and Fred L. Drake says: ... this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on in the module search path. An example would probably set me straight. Can anyone help with that? Marilyn Davis From sulinet at postafiok.hu Wed Jun 1 09:18:25 2011 From: sulinet at postafiok.hu (=?ISO-8859-1?Q?V=E1las_P=E9ter?=) Date: Wed, 1 Jun 2011 09:18:25 +0200 Subject: [Tutor] checking if a variable is an integer? In-Reply-To: References: Message-ID: Hi guys, do you think, Hans, who wants to write his first prime number program, still understands what we are talking about? :-) -------------- next part -------------- An HTML attachment was scrubbed... URL: From sulinet at postafiok.hu Wed Jun 1 09:26:01 2011 From: sulinet at postafiok.hu (=?ISO-8859-1?Q?V=E1las_P=E9ter?=) Date: Wed, 1 Jun 2011 09:26:01 +0200 Subject: [Tutor] __init__.py question In-Reply-To: <39060.67.169.189.143.1306885493.squirrel@mail.tigertech.net> References: <39060.67.169.189.143.1306885493.squirrel@mail.tigertech.net> Message-ID: I think it means that you may have a subdirectory named "string" in your actual directory where you store e.g. your string-related scripts, and you have a Python package named "string" _somewhere_else_, but in the module search path. The subdirectory of the actual directory will have priority bacause of its place, and will prevent you of importing the string package. 2011/6/1 Marilyn Davis > I don't really understand why __init__.py is necessary -- except that it > makes the packaging scheme work. > > The Python Manual by Guido van Rossum and Fred L. Drake says: > > ... this is done to prevent directories with a common name, such as > string, from unintentionally hiding valid modules that occur later on in > the module search path. > > An example would probably set me straight. Can anyone help with that? > > Marilyn Davis > > _______________________________________________ > 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 marilyn at pythontrainer.com Wed Jun 1 19:37:29 2011 From: marilyn at pythontrainer.com (Marilyn Davis) Date: Wed, 1 Jun 2011 10:37:29 -0700 (PDT) Subject: [Tutor] __init__.py question In-Reply-To: References: <39060.67.169.189.143.1306885493.squirrel@mail.tigertech.net> Message-ID: <33743.67.169.189.143.1306949849.squirrel@mail.tigertech.net> Thank you V?las P?ter. I still don't get it, or how __init__.py alters the scenario you describe. I know that sometimes I'm really dense so please be patient with me. If I have a string.py in my local directory, it will be imported when I "import string" because the search path, sys.path, (which I have control of), has my local directory as the first place to search by default, and no __init__.py is involved. If my string is not a .py but package/directory itself, it will be imported and searched into if it has a __init__.py. In either case, how can I get to the system's string.py by putting __init__.py somewhere? If my string.py is in a package, I have to put its parent directory on my sys.path for it to be found, and the parent directory won't need an __init__.py There's something I'm missing because I think you simply can't call something string.py unless you are willing to give up the library string.py. I can see that a person could have a local string directory that they don't want imported because it has some non-code in it, or something. But the __init__.py facility is a big deal to be there for the purpose of allowing this when it is, IMHO, an architectural mistake. There must be something I'm missing or some wrong thinking described here because Guido is so smart, and it's still in 3.x. If anyone has an insight, I would really appreciate some help on this point, which has bothered me a bit for years. Marilyn Davis On Wed, June 1, 2011 12:26 am, V?las P?ter wrote: > I think it means that you may have a subdirectory named "string" in your > actual directory where you store e.g. your string-related scripts, and you > have a Python package named "string" _somewhere_else_, but in the module > search path. The subdirectory of the actual directory will have priority > bacause of its place, and will prevent you of importing the string > package. > > 2011/6/1 Marilyn Davis > > >> I don't really understand why __init__.py is necessary -- except that >> it makes the packaging scheme work. >> >> The Python Manual by Guido van Rossum and Fred L. Drake says: >> >> >> ... this is done to prevent directories with a common name, such as >> string, from unintentionally hiding valid modules that occur later on in >> the module search path. >> >> An example would probably set me straight. Can anyone help with that? >> >> >> Marilyn Davis >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> From ramit.prasad at jpmchase.com Wed Jun 1 20:22:35 2011 From: ramit.prasad at jpmchase.com (Prasad, Ramit) Date: Wed, 1 Jun 2011 14:22:35 -0400 Subject: [Tutor] __init__.py question In-Reply-To: <33743.67.169.189.143.1306949849.squirrel@mail.tigertech.net> References: <39060.67.169.189.143.1306885493.squirrel@mail.tigertech.net> <33743.67.169.189.143.1306949849.squirrel@mail.tigertech.net> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2E340ED22F@EMARC112VS01.exchad.jpmchase.net> I wonder if this is so that it can ignore directories on sys.path. I assume that the path passed to python can be quite verbose depending on the OS's handling of path and environment variables. This is also a way to have Python ignore Python scripts in directories on the path that are not meant to be imported but run from command-line (like a bash script). To be honest, I am just stabbing at possible solutions because I am not sure myself. If you do find the definitive reason (that makes more sense than the excerpt included in this thread) do post on here for the rest of us. :) 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 alexandre.conrad at gmail.com Wed Jun 1 20:33:32 2011 From: alexandre.conrad at gmail.com (Alexandre Conrad) Date: Wed, 1 Jun 2011 11:33:32 -0700 Subject: [Tutor] __init__.py question In-Reply-To: <39060.67.169.189.143.1306885493.squirrel@mail.tigertech.net> References: <39060.67.169.189.143.1306885493.squirrel@mail.tigertech.net> Message-ID: 2011/5/31 Marilyn Davis : > I don't really understand why __init__.py is necessary -- except that it > makes the packaging scheme work. > > The Python Manual by Guido van Rossum and Fred L. Drake says: > > ... this is done to prevent directories with a common name, such as > string, from unintentionally hiding valid modules that occur later on in > the module search path. I think it is just to avoids unexpected conflicting namespaces that could happen by accidentally importing non-Python directories. By explicitly putting a __init__.py module in your directory, you are telling Python you want your directory to be considered as a Python package and to be imported in your namespace. If you have a conflicting namespace, it means you explicitly wanted this to happen, then you have to deal with it (or fix it if unintended). -- Alex | twitter.com/alexconrad From alexandre.conrad at gmail.com Wed Jun 1 20:52:44 2011 From: alexandre.conrad at gmail.com (Alexandre Conrad) Date: Wed, 1 Jun 2011 11:52:44 -0700 Subject: [Tutor] __init__.py question In-Reply-To: References: <39060.67.169.189.143.1306885493.squirrel@mail.tigertech.net> Message-ID: As a side note, remember that imported modules are cached under sys.modules. If you import something, it will be looked up in sys.modules and use the one in memory if it exists. If it doesn't exist, it will iterate over sys.path and look for your module/package. If it doesn't find it, you will get an ImportError. If it finds it, it will add it to sys.modules. So any future imports for the same namespace won't be re-imported from disk, it's already here in memory. Say I *do* have a local package called string. After I import it, say I want to import the "logging" module. Well, it will break: $ python Python 2.6.6 (r266:84292, Sep 15 2010, 16:22:56) [GCC 4.4.5] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import string # my local string package >>> print string >>> import logging Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.6/logging/__init__.py", line 62, in elif string.lower(__file__[-4:]) in ['.pyc', '.pyo']: AttributeError: 'module' object has no attribute 'lower' When "logging" is being imported, internally it also imports standard Python "string" module, which is *already* in sys.modules (your own). So imagine if Python also imported any directory without a __init__.py file, system wide, you might have random surprises. 2011/6/1 Alexandre Conrad : > 2011/5/31 Marilyn Davis : >> I don't really understand why __init__.py is necessary -- except that it >> makes the packaging scheme work. >> >> The Python Manual by Guido van Rossum and Fred L. Drake says: >> >> ... this is done to prevent directories with a common name, such as >> string, from unintentionally hiding valid modules that occur later on in >> the module search path. > > I think it is just to avoids unexpected conflicting namespaces that > could happen by accidentally importing non-Python directories. By > explicitly putting a __init__.py module in your directory, you are > telling Python you want your directory to be considered as a Python > package and to be imported in your namespace. If you have a > conflicting namespace, it means you explicitly wanted this to happen, > then you have to deal with it (or fix it if unintended). > > -- > Alex | twitter.com/alexconrad > -- Alex | twitter.com/alexconrad From marilyn at pythontrainer.com Wed Jun 1 21:26:55 2011 From: marilyn at pythontrainer.com (Marilyn Davis) Date: Wed, 1 Jun 2011 12:26:55 -0700 (PDT) Subject: [Tutor] __init__.py question In-Reply-To: References: <39060.67.169.189.143.1306885493.squirrel@mail.tigertech.net> Message-ID: <45760.67.169.189.143.1306956415.squirrel@mail.tigertech.net> Maybe I'm getting what you say, Alexandre and Ramit. When you import logging, it imports string, but it won't if you have a string of your own already imported. So, when logging depends on string, it'll get mine and crash. But __init__.py helps what in this scenario? The only scenario it helps, that I can understand so far, is if I make a string directory that isn't part of a package that I'm making, but is in its directory structure, accidentally using a library name that I want. I guess I don't feel very satisfied because I would be happy with the crash so that I can fix up my naming/architecture mistake rather than depend on, and struggle with, the __init__.py scheme. I teach Python and this is always a hard part for people. It might help if I understand it better. Marilyn Davis On Wed, June 1, 2011 11:52 am, Alexandre Conrad wrote: > As a side note, remember that imported modules are cached under > sys.modules. If you import something, it will be looked up in sys.modules > and use the one in memory if it exists. If it doesn't exist, it will > iterate over sys.path and look for your module/package. If it doesn't find > it, you will get an ImportError. If it finds it, it will add it to > sys.modules. So any future imports for the same namespace won't be > re-imported from disk, it's already here in memory. > > Say I *do* have a local package called string. After I import it, say > I want to import the "logging" module. Well, it will break: > > > $ python > Python 2.6.6 (r266:84292, Sep 15 2010, 16:22:56) > [GCC 4.4.5] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>>> import string # my local string package print string > > >>>> import logging > Traceback (most recent call last): > File "", line 1, in > File "/usr/lib/python2.6/logging/__init__.py", line 62, in > elif string.lower(__file__[-4:]) in ['.pyc', '.pyo']: AttributeError: > 'module' object has no attribute 'lower' > > > When "logging" is being imported, internally it also imports standard > Python "string" module, which is *already* in sys.modules (your own). > > > So imagine if Python also imported any directory without a __init__.py > file, system wide, you might have random surprises. > > > 2011/6/1 Alexandre Conrad : > >> 2011/5/31 Marilyn Davis : >> >>> I don't really understand why __init__.py is necessary -- except that >>> it makes the packaging scheme work. >>> >>> The Python Manual by Guido van Rossum and Fred L. Drake says: >>> >>> >>> ... this is done to prevent directories with a common name, such as >>> string, from unintentionally hiding valid modules that occur later on >>> in the module search path. >> >> I think it is just to avoids unexpected conflicting namespaces that >> could happen by accidentally importing non-Python directories. By >> explicitly putting a __init__.py module in your directory, you are >> telling Python you want your directory to be considered as a Python >> package and to be imported in your namespace. If you have a conflicting >> namespace, it means you explicitly wanted this to happen, then you have >> to deal with it (or fix it if unintended). >> >> -- >> Alex | twitter.com/alexconrad >> >> > > > > -- > Alex | twitter.com/alexconrad From eire1130 at gmail.com Wed Jun 1 21:49:44 2011 From: eire1130 at gmail.com (James Reynolds) Date: Wed, 1 Jun 2011 15:49:44 -0400 Subject: [Tutor] Python Extensions in C In-Reply-To: References: <1907EE83-B790-42E3-A6C6-0538D29F8035@gmail.com> Message-ID: So I've been continuing with my experiment above, and I've made some good progress and learned some new things as I've been going. I've expanded it out a little bit, and you can see the code here: http://pastebin.com/gnW4xQNv I've tried to incorporate most of your suggestions (although, the code itself looks more condensed in my editor than what it appears there). Unfortunately, I am stuck and I have no clue how to free myself from the mud. On line 370, you will notice I have "*return_varp" as the return value and not "skew". This is because I am trying to figure out why the variance function is not working properly from this function call. Earlier today it was working fine, so I know it works at least in theory. When variance is called from stats.var it works just fine and the output is as expected. so for example, a = [1,2,3,4,4,5] stats.var(a) = 2.16 (correct) stats.skew(a) = -0.74 (not correct) Again, for this I have the return value of skew set to show me the the second moment. Skew is calling the same exact function as var and with the same exact same inputs as var(), or should be. I've looked at every single variable in variance to see what is going on and here is what I know for now: 1. sumall is adding up to the wrong number when called from skew (or kurt). 2. avg, count, and moment all are what they should be. 3. The sequence passed is always the same from Python (a = [1,2,3,4,4,5]) I'm guessing this is some nuance of C code dealing static variables or something to do with memory, but again, I no even less about C than I do about Python (which is my objective here - learning some of this should make me better at both, hopefully) A couple other points: There are three parameters now, not one. The later two are optional. they are (list, avg, and sample) sample is True by default. So you can pass it an average already. Lastly, any other pointers would be greatly appreciated. James On Thu, May 26, 2011 at 7:50 PM, Alan Gauld wrote: > > "James Reynolds" wrote > > > As far as the null point goes, it shouldn't be null at all once it gets to >> the point Alan pointed out. The pointer is set in (for example) stat_avg >> >> seq = PySequence_Fast(obj, "Expected a Sequence"); >> > > Can the function fail? If so what does it return? That was > my point. Can seq ever still be NULL after the function call? > For example if the function is allocating memory it could fail > to grab enough and then return a NULL.... > > But it depends on how reliable the Python function is in > its return value... > > > But maybe I am missing something that you have seen? >> > > Don't rely on functio returns being valid values. > It is common practice in industrial strength C to return a NULL > and expect the user to check. Manyb of the standard library > functions work that way too. > > So you often see code like > > if (foo = someFunction() ){ // notice it is an assignment not equality > test > process(foo); > } > > 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 alexandre.conrad at gmail.com Wed Jun 1 21:50:06 2011 From: alexandre.conrad at gmail.com (Alexandre Conrad) Date: Wed, 1 Jun 2011 12:50:06 -0700 Subject: [Tutor] __init__.py question In-Reply-To: <45760.67.169.189.143.1306956415.squirrel@mail.tigertech.net> References: <39060.67.169.189.143.1306885493.squirrel@mail.tigertech.net> <45760.67.169.189.143.1306956415.squirrel@mail.tigertech.net> Message-ID: 2011/6/1 Marilyn Davis : > Maybe I'm getting what you say, Alexandre and Ramit. > > When you import logging, it imports string, but it won't if you have a > string of your own already imported. > > So, when logging depends on string, it'll get mine and crash. > > But __init__.py helps what in this scenario? Nothing directly. I started my email with "As a side note" :) > The only scenario it helps, that I can understand so far, is if I make a > string directory that isn't part of a package that I'm making, but is in > its directory structure, accidentally using a library name that I want. Correct. > I guess I don't feel very satisfied because I would be happy with the > crash so that I can fix up my naming/architecture mistake rather than > depend on, and struggle with, the __init__.py scheme. > > I teach Python and this is always a hard part for people. ?It might help > if I understand it better. Don't try to over-understand! :) If an __init__.py file is present in your directory, it will be considered by Python as a package. __init__.py also avoids non-Python directories to potentially pollute/conflict with your namespace. That's pretty much it. Additionally, when importing a package, anything in the __init__.py module will be executed during import. Just as you can see from the previous "logging" traceback I sent. -- Alex | twitter.com/alexconrad From karim.liateni at free.fr Wed Jun 1 22:20:08 2011 From: karim.liateni at free.fr (Karim) Date: Wed, 01 Jun 2011 22:20:08 +0200 Subject: [Tutor] Strategy to read a redirecting html page In-Reply-To: References: <4DE57313.3040808@free.fr> Message-ID: <4DE69EF8.6040209@free.fr> On 06/01/2011 01:41 AM, Alexandre Conrad wrote: > Hi Karim, > > When you hit the page and you get an HTTP redirect code back (say, > 302), you will need to make another call to the URL specified in the > "Location" parameter in the response headers. Then you retrieve that > new page and you can check you got an acceptable HTTP response code > (such as 200) and read the page's body (or whatever you want to do > with it). Otherwise, keep looping until you get an expected HTTP > response code. > > Note: you may get stuck in an infinite loop if two URLs redirect to each other. > > You might want to take a look at the higher level httplib module: > http://docs.python.org/library/httplib.html > > Although I don't think it can automatically follow redirects for you. > You'll have to implement the loop yourself. > > If you can rely on 3rd party packages (not part of the standard Python > library), take a look at httplib2: > https://httplib2.googlecode.com/hg/doc/html/libhttplib2.html > > This one can follow redirects. > > HTH, > > 2011/5/31 Karim: >> Hello, >> >> I am having issue in reading a html page which is redirected to a new page. >> I get the first warning/error message page and not the redirection one. >> Should I request a second time the same url page or Should I loop forever >> until the >> page content is the correct (by parsing it) one? >> Do you have a better strategy or perhaps some modules deal w/ that issue? >> I am using python 2.7.1 on Linux ubuntu 11.04 and the modules urllib2, >> urllib, etc... >> The webpage is secured but I registered a password manager. >> >> cheers >> karim >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> Alex, Ian, Hugo, Thanks a THOUSAND TIMES! With all the hints and weapons 'I will survive' ;o) I have to use python standard but 'libhttplib2' 3rd party module, I will have a look. Many many thanks Cheers Karim From steve at pearwood.info Thu Jun 2 01:23:49 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 02 Jun 2011 09:23:49 +1000 Subject: [Tutor] checking if a variable is an integer? In-Reply-To: References: Message-ID: <4DE6CA05.5030906@pearwood.info> V?las P?ter wrote: > Hi guys, do you think, Hans, who wants to write his first prime number > program, still understands what we are talking about? :-) If not, he can google the bits he doesn't understand, or ask. We won't bite! -- Steven From steve at pearwood.info Thu Jun 2 02:11:00 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 02 Jun 2011 10:11:00 +1000 Subject: [Tutor] __init__.py question In-Reply-To: <33743.67.169.189.143.1306949849.squirrel@mail.tigertech.net> References: <39060.67.169.189.143.1306885493.squirrel@mail.tigertech.net> <33743.67.169.189.143.1306949849.squirrel@mail.tigertech.net> Message-ID: <4DE6D514.8050608@pearwood.info> Marilyn Davis wrote: [...] > There's something I'm missing because I think you simply can't call > something string.py unless you are willing to give up the library > string.py. No, you're right about that. Python's search path is "first match wins". Whether it's a package or a module, it will match before the library string.py. Adding __init__.py doesn't change that. (Unless you re-arrange sys.path so that library modules come first.) However, you can have a directory called "string", containing arbitrary .py files. So you could drop this in your path: string/ +-- a.py +-- b.py and add string to the path so that the directory is searched, and still get the standard string.py. (I haven't actually tried this, but it should work.) Only if you put a file __init__.py into the directory will it shadow the standard library string.py. Personally, I think the emphasis given in the docs about shadowing standard library files is misplaced. I think that is actually irrelevant. I think a more useful explanation for the need for __init__.py is simple: how else could Python distinguish a package from a mere directory containing Python files? A mere directory is not searched unless it is explicitly added to the path; a mere directory cannot be imported. A package can be. But since a package *is* a directory at the file system level, how should Python distinguish them? I suppose Python could have the rule "the directory must end in .py to be considered a package". But then, when you import the main package instead of a submodule, which file should Python read? There needs to be a standard naming convention for the file to be treated as the top-level module. But since you have such a file, there's no longer any need for adding a .py to the end of the directory name, since the standard file is sufficient to determine that the directory is a package. That file could have been called anything, __init__.py was chosen by analogy with __init__ methods in classes and because it's unlikely to clash with any name package authors might choose for their own use. -- Steven From alan.gauld at btinternet.com Thu Jun 2 02:40:44 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Thu, 2 Jun 2011 01:40:44 +0100 (BST) Subject: [Tutor] Python Extensions in C In-Reply-To: References: <1907EE83-B790-42E3-A6C6-0538D29F8035@gmail.com> Message-ID: <774934.9175.qm@web86705.mail.ird.yahoo.com> OK, It seems to have grown a bit! :-) Your use of static seems a little odd. In particular the definition of avg as a static double. You then never use avg except here: 1. avg = *return_avgp; 2. samp = 0; 3. return_varp = var(seq, count, &avg, samp, 2); 4. third_moment = var(seq, count, &avg, 0, 3);You assign the content of a pointer to avg then take use address of avg in var() - effectively making avg back into a pointer? Why not just use *return_avgp inside the var() function? And why is avg static? - do you understand what static is doing? And the side effects of that? Is there a reason to use static? If so its a bit too subtle for me... BTW, On style issues: While I prefer the braces style you have made the mistake of mixing styles, particularly confusing when done inside a single function as in the middle of stat_kurt() And I don't personally like variables being declared in the middle of code. (eg lines 365 and 430) I can just about accept at the start of a block, but I prefer at the start of the function. It's just easier to find if they are all together. Other than that I can't see the error, but its late and thats quite a lot of code for a Python programmer to wade through! :-) Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ ________________________________ From: James Reynolds To: Alan Gauld Cc: tutor at python.org Sent: Wednesday, 1 June, 2011 20:49:44 Subject: Re: [Tutor] Python Extensions in C So I've been continuing with my experiment above, and I've made some good progress and learned some new things as I've been going. I've expanded it out a little bit, and you can see the code here: http://pastebin.com/gnW4xQNv I've tried to incorporate most of your suggestions (although, the code itself looks more condensed in my editor than what it appears there). Unfortunately, I am stuck and I have no clue how to free myself from the mud. On line 370, you will notice I have "*return_varp" as the return value and not "skew". This is because I am trying to figure out why the variance function is not working properly from this function call. Earlier today it was working fine, so I know it works at least in theory. When variance is called from stats.var it works just fine and the output is as expected. so for example, a = [1,2,3,4,4,5] stats.var(a) = 2.16 (correct) stats.skew(a) = -0.74 (not correct) Again, for this I have the return value of skew set to show me the the second moment. Skew is calling the same exact function as var and with the same exact same inputs as var(), or should be. I've looked at every single variable in variance to see what is going on and here is what I know for now: 1. sumall is adding up to the wrong number when called from skew (or kurt). 2. avg, count, and moment all are what they should be. 3. The sequence passed is always the same from Python (a = [1,2,3,4,4,5]) I'm guessing this is some nuance of C code dealing static variables or something to do with memory, but again, I no even less about C than I do about Python (which is my objective here - learning some of this should make me better at both, hopefully) A couple other points: There are three parameters now, not one. The later two are optional. they are (list, avg, and sample) sample is True by default. So you can pass it an average already. Lastly, any other pointers would be greatly appreciated. James On Thu, May 26, 2011 at 7:50 PM, Alan Gauld wrote: >"James Reynolds" wrote > > > >As far as the null point goes, it shouldn't be null at all once it gets to >>the point Alan pointed out. The pointer is set in (for example) stat_avg >> >> seq = PySequence_Fast(obj, "Expected a Sequence"); >> Can the function fail? If so what does it return? That was >my point. Can seq ever still be NULL after the function call? >For example if the function is allocating memory it could fail >to grab enough and then return a NULL.... > >But it depends on how reliable the Python function is in >its return value... > > > >But maybe I am missing something that you have seen? >> Don't rely on functio returns being valid values. >It is common practice in industrial strength C to return a NULL >and expect the user to check. Manyb of the standard library >functions work that way too. > >So you often see code like > >if (foo = someFunction() ){ // notice it is an assignment not equality test > process(foo); >} > >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 sulinet at postafiok.hu Thu Jun 2 09:18:27 2011 From: sulinet at postafiok.hu (=?ISO-8859-1?Q?V=E1las_P=E9ter?=) Date: Thu, 2 Jun 2011 09:18:27 +0200 Subject: [Tutor] Structured files? Message-ID: Good morning, I can create files and write strings/unicodes. Is it possible to write a list, a dictionary or an object or anything into a file? Or do I have to transform them to strings? P?ter -------------- next part -------------- An HTML attachment was scrubbed... URL: From simonyanix at gmail.com Thu Jun 2 09:29:47 2011 From: simonyanix at gmail.com (Simon Yan) Date: Thu, 2 Jun 2011 15:29:47 +0800 Subject: [Tutor] Structured files? In-Reply-To: References: Message-ID: 2011/6/2 V?las P?ter : > Good morning, > > I can create files and write strings/unicodes. > Is it possible to write a list, a dictionary or an object or anything into a > file? Or do I have to transform them to strings? Yes you can. I guess the question is how you want the information to be structured. IMHO, everything in Python can be "string-lized". > > P?ter > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Regards, Simon Yan http://www.google.com/profiles/simonyanix From sulinet at postafiok.hu Thu Jun 2 10:05:34 2011 From: sulinet at postafiok.hu (=?ISO-8859-1?Q?V=E1las_P=E9ter?=) Date: Thu, 2 Jun 2011 10:05:34 +0200 Subject: [Tutor] Structured files? In-Reply-To: References: Message-ID: 2011. j?nius 2. 9:29 Simon Yan ?rta, : > Yes you can. > I guess the question is how you want the information to be structured. > IMHO, everything in Python can be "string-lized". > > What is the syntax then? I have Windows XP. The code is: f=open("xxx.dat","w") f.write("fff") d={'one':1, 2:'two'} f.write(d) f.close() Python 2.5 message: TypeError: argument 1 must be string or read-only character buffer, not dict Python 3.1 message: TypeError: must be str, not dict Modified code: f=open("xxx.dat","wb") The others remain as above, just I wrote wb. Python 2.5 message: TypeError: argument 1 must be string or read-only buffer, not dict Python 3.1 message: f.write("fff") TypeError: must be bytes or buffer, not str This won't write even a string. I read something about a pack function, is that the key? -------------- next part -------------- An HTML attachment was scrubbed... URL: From simonyanix at gmail.com Thu Jun 2 10:52:53 2011 From: simonyanix at gmail.com (Simon Yan) Date: Thu, 2 Jun 2011 16:52:53 +0800 Subject: [Tutor] Structured files? In-Reply-To: References: Message-ID: 2011/6/2 V?las P?ter : > > > 2011. j?nius 2. 9:29 Simon Yan ?rta, : >> >> Yes you can. >> I guess the question is how you want the information to be structured. >> IMHO, everything in Python can be "string-lized". >> > What is the syntax then?? I have Windows XP. The code is: > f=open("xxx.dat","w") > f.write("fff") > d={'one':1, 2:'two'} > f.write(d) > f.close() Try this: f=open("xxx.dat","w") f.write("fff") d={'one':1, 2:'two'} f.write(str(d)) f.close() > > Python 2.5 message: > TypeError: argument 1 must be string or read-only character buffer, not dict > Python 3.1 message: > TypeError: must be str, not dict > > Modified code: > f=open("xxx.dat","wb") The others remain as above, just I wrote wb. > Python 2.5 message: > TypeError: argument 1 must be string or read-only buffer, not dict > Python 3.1 message: > ??? f.write("fff") > TypeError: must be bytes or buffer, not str > This won't write even a string. > > I read something about a pack function, is that the key? > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Regards, Simon Yan http://www.google.com/profiles/simonyanix From wprins at gmail.com Thu Jun 2 10:58:05 2011 From: wprins at gmail.com (Walter Prins) Date: Thu, 2 Jun 2011 09:58:05 +0100 Subject: [Tutor] Structured files? In-Reply-To: References: Message-ID: >Is it possible to write a list, a dictionary or an object or anything into a file? Or do I have to transform them to strings? Have a look at the pickle module: http://docs.python.org/library/pickle.html -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Jun 2 09:58:23 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 2 Jun 2011 08:58:23 +0100 Subject: [Tutor] Structured files? References: Message-ID: "V?las P?ter" wrote > I can create files and write strings/unicodes. > Is it possible to write a list, a dictionary or an object or > anything into a > file? Or do I have to transform them to strings? You can write anything to a file, but the file will need to be opened in binary mode(see the docs). The tricky bit is reading the data back, you will need to find a way to convert the bytes read from the file into whatever the original data structure was. For that reason it is usually better to use a tool like pickle or shelve to store Python objects in a file (again see the docs) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Jun 2 11:24:16 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 2 Jun 2011 10:24:16 +0100 Subject: [Tutor] Structured files? References: Message-ID: "V?las P?ter" wrote > Modified code: > f=open("xxx.dat","wb") The others remain as above, just I wrote wb. Yes, you need to use binary mode. > I read something about a pack function, is that the key? See the file handling topic in my tutorial for a simple example of using the struct module(which includes the pack function) to write/read binary data. But, pickle or shelve are probably more useful for your needs if you want to save entire Python objects. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From sulinet at postafiok.hu Thu Jun 2 11:25:37 2011 From: sulinet at postafiok.hu (=?ISO-8859-1?Q?V=E1las_P=E9ter?=) Date: Thu, 2 Jun 2011 11:25:37 +0200 Subject: [Tutor] Structured files? In-Reply-To: References: Message-ID: 2011. j?nius 2. 10:52 Simon Yan ?rta, : > Try this: > f.write(str(d)) > > That's what I first asked, this is not a structured file then, this is a structure transformed to a string. Thanks for the idea of pickle, I will look at it. -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Thu Jun 2 13:32:08 2011 From: davea at ieee.org (Dave Angel) Date: Thu, 02 Jun 2011 07:32:08 -0400 Subject: [Tutor] Structured files? In-Reply-To: References: Message-ID: <4DE774B8.5010803@ieee.org> On 01/-10/-28163 02:59 PM, V?las P?ter wrote: > 2011. j?nius 2. 9:29 Simon Yan ?rta,: > >> Yes you can. >> I guess the question is how you want the information to be structured. >> IMHO, everything in Python can be "string-lized". >> >> What is the syntax then? I have Windows XP. The code is: > f=open("xxx.dat","w") > f.write("fff") > d={'one':1, 2:'two'} > f.write(d) > f.close() > > Python 2.5 message: > TypeError: argument 1 must be string or read-only character buffer, not dict > Python 3.1 message: > TypeError: must be str, not dict > > Modified code: > f=open("xxx.dat","wb") The others remain as above, just I wrote wb. > Python 2.5 message: > TypeError: argument 1 must be string or read-only buffer, not dict > Python 3.1 message: > f.write("fff") > TypeError: must be bytes or buffer, not str > This won't write even a string. > > I read something about a pack function, is that the key? > Look up shelve and pickle (both in the stdlib). One of them will be suitable for the purpose. DaveA From eire1130 at gmail.com Thu Jun 2 15:48:50 2011 From: eire1130 at gmail.com (James Reynolds) Date: Thu, 2 Jun 2011 09:48:50 -0400 Subject: [Tutor] Python Extensions in C In-Reply-To: <774934.9175.qm@web86705.mail.ird.yahoo.com> References: <1907EE83-B790-42E3-A6C6-0538D29F8035@gmail.com> <774934.9175.qm@web86705.mail.ird.yahoo.com> Message-ID: I fixed it. I find if I sleep on things I have a better chance at fixing them. Maybe I will get some real work done today instead of going all OCD on this side project? Here's the dif: http://pastebin.com/KYBab3H9 I'll address your points in a second, but here's how I found the problem (Python is so much easier to work with, it's scary). 1. I thought to myself last night, I knew there was a problem with the sums not adding up properly in the var() function (the sumall variable). 2. I then thought to myself, well, let me trace out every last variable in the first step. I then found that sumall was being raised to the third power, not the second power. 3. I traced out "moment" and it indeed was sending through a "3", or at least seemed to be. 4. Meanwhile, back at line 362, I am calling the same function, but with "3" in the moment arg. 5. It occurs to me that I need to save the value of the address that the pointer returned from "return_varp" to a variable. I actually have such a variable already, but just below the "third moment". The skew function now seems to work correctly. My guess is Kurt is still broken, but most likely this is the same problem. I guess what happens is, the static variable in var() func is saving the value to the same exact address. Thinking back on it, this would be consistent with Python itself if I was to have a class like Class A(): a = 1 def update_a: A.a +=1. After calling update_a, if I print A.a my answer should be 2. But, what I was thinking was that each new call to var() would be like a instance of class A above, in other words, it would create a static variable called "temp_r", but in thinking about it, this isn't the case. Declaring something static means (please correct me if I'm wrong) that the address you using for "temp_r" is now and forever will be the address assigned when initially created. So, any pointer pointing to this address will return its changing content, whether intended to do so or not. The entire reason why I was using static variables in the those functions was so they didn't lose their values when returned to their calling functions. So anyway, back to your points. I had gone through must of it to bring it in line with your suggestions from earlier, but I'm afraid you caught me getting lazy. This section: avg = *return_avgp; samp = 0; return_varp = var(seq, count, &avg, samp, 2); third_moment = var(seq, count, &avg, 0, 3); Was an artifact from troubleshooting. It should have been (and I think is now) how you suggested. So at any rate, thank you for the help and if you see something else, please don't hesitate to point it out! On Wed, Jun 1, 2011 at 8:40 PM, ALAN GAULD wrote: > OK, It seems to have grown a bit! :-) > > Your use of static seems a little odd. In particular the definition of avg > as a static double. > You then never use avg except here: > > > 1. avg = *return_avgp; > 2. samp = 0; > 3. return_varp = var(seq, count, &avg, samp, 2); > 4. third_moment = var(seq, count, &avg, 0, 3); > > You assign the content of a pointer to avg then take use address > of avg in var() - effectively making avg back into a pointer? > > Why not just use *return_avgp inside the var() function? > And why is avg static? - do you understand what static is doing? > And the side effects of that? Is there a reason to use static? > If so its a bit too subtle for me... > > BTW, On style issues: > While I prefer the braces style you have made the mistake of mixing styles, > > particularly confusing when done inside a single function as in the middle > of > stat_kurt() > > And I don't personally like variables being declared in the middle of code. > > (eg lines 365 and 430) I can just about accept at the start of a block, > but I prefer at the start of the function. It's just easier to find if they > > are all together. > > Other than that I can't see the error, but its late and thats > quite a lot of code for a Python programmer to wade through! :-) > > > Alan Gauld > Author of the Learn To Program website > > http://www.alan-g.me.uk/ > > > ------------------------------ > *From:* James Reynolds > *To:* Alan Gauld > *Cc:* tutor at python.org > *Sent:* Wednesday, 1 June, 2011 20:49:44 > > *Subject:* Re: [Tutor] Python Extensions in C > > So I've been continuing with my experiment above, and I've made some good > progress and learned some new things as I've been going. I've expanded it > out a little bit, and you can see the code here: > > http://pastebin.com/gnW4xQNv > > I've tried to incorporate most of your > suggestions (although, the code itself looks more condensed in my editor > than what it appears there). > > Unfortunately, I am stuck and I have no clue how to free myself from the > mud. > > > On line 370, you will notice I have "*return_varp" as the return value and > not "skew". This is because I am trying to figure out why the variance > function is not working properly from this function call. > > Earlier today it was working fine, so I know it works at least in theory. > > When variance is called from stats.var it works just fine and the output is > as expected. > > so for example, > > a = [1,2,3,4,4,5] > stats.var(a) = 2.16 (correct) > > stats.skew(a) = -0.74 (not correct) > > Again, for this I have the return value of skew set to show me the the > second moment. Skew is calling the same exact function as var and with the > same exact same inputs as var(), or should be. > > I've looked at every single variable in variance to see what is going on > and here is what I know for now: > > 1. sumall is adding up to the wrong number when called from skew (or kurt). > 2. avg, count, and moment all are what they should be. > 3. The sequence passed is always the same from Python (a = [1,2,3,4,4,5]) > > I'm guessing this is some nuance of C code dealing static variables or > something to do with memory, but again, I no even less about C than I do > about Python (which is my objective here - learning some of this should make > me better at both, hopefully) > > A couple other points: There are three parameters now, not one. The later > two are optional. they are (list, avg, and sample) sample is True by > default. > > So you can pass it an average already. > > Lastly, any other pointers would be greatly appreciated. > > James > > > > > > > > > > > > > > > > On Thu, May 26, 2011 at 7:50 PM, Alan Gauld wrote: > >> >> "James Reynolds" wrote >> >> >> As far as the null point goes, it shouldn't be null at all once it gets >>> to >>> the point Alan pointed out. The pointer is set in (for example) stat_avg >>> >>> seq = PySequence_Fast(obj, "Expected a Sequence"); >>> >> >> Can the function fail? If so what does it return? That was >> my point. Can seq ever still be NULL after the function call? >> For example if the function is allocating memory it could fail >> to grab enough and then return a NULL.... >> >> But it depends on how reliable the Python function is in >> its return value... >> >> >> But maybe I am missing something that you have seen? >>> >> >> Don't rely on functio returns being valid values. >> It is common practice in industrial strength C to return a NULL >> and expect the user to check. Manyb of the standard library >> functions work that way too. >> >> So you often see code like >> >> if (foo = someFunction() ){ // notice it is an assignment not equality >> test >> process(foo); >> } >> >> 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 ramit.prasad at jpmchase.com Thu Jun 2 16:04:30 2011 From: ramit.prasad at jpmchase.com (Prasad, Ramit) Date: Thu, 2 Jun 2011 10:04:30 -0400 Subject: [Tutor] checking if a variable is an integer? In-Reply-To: <4DE6CA05.5030906@pearwood.info> References: <4DE6CA05.5030906@pearwood.info> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2E345FFA2A@EMARC112VS01.exchad.jpmchase.net> >If not, he can google the bits he doesn't understand, or ask. We won't bite! Unless he asks for it ;) 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 griffinelly at gmail.com Thu Jun 2 16:12:25 2011 From: griffinelly at gmail.com (Jamie Griffin) Date: Thu, 2 Jun 2011 15:12:25 +0100 Subject: [Tutor] Introduction Message-ID: Hello everyone I'm not sure if introductions are customary on this list but I thought I would anyway as I'm going to be using it quite a bit from now. I am just starting out with python and I will no doubt get stuck and need some assistance from you all soon. I'll try my best to keep the stupidity to a minimum. Jamie. From david at pythontoo.com Thu Jun 2 16:40:42 2011 From: david at pythontoo.com (David Abbott) Date: Thu, 2 Jun 2011 10:40:42 -0400 Subject: [Tutor] Introduction In-Reply-To: References: Message-ID: On Thu, Jun 2, 2011 at 10:12 AM, Jamie Griffin wrote: > Hello everyone > > I'm not sure if introductions are customary on this list but I thought > I would anyway as I'm going to be using it quite a bit from now. > > I am just starting out with python and I will no doubt get stuck and > need some assistance from you all soon. I'll try my best to keep the > stupidity to a minimum. > > Jamie. Hi Jamie, Welcome to the list, if you have not read one here is a pretty good guide [1] for list etiquette, it would have saved me some embarrassment if I had read it before I started posting to mail lists. Have Fun :) David [1] http://curl.haxx.se/mail/etiquette.html From alexandre.conrad at gmail.com Thu Jun 2 17:57:51 2011 From: alexandre.conrad at gmail.com (Alexandre Conrad) Date: Thu, 2 Jun 2011 08:57:51 -0700 Subject: [Tutor] Structured files? In-Reply-To: References: Message-ID: 2011/6/2 V?las P?ter : > I can create files and write strings/unicodes. > Is it possible to write a list, a dictionary or an object or anything into a > file? Or do I have to transform them to strings? As suggested by Walter, you should use the Pickle module to serialize your Python objects so they can be written to files and read back to Python (de-serialized). This way you can also share your pickled objects with other Python apps and Pickle is great for this. Actually, that's how the multiprocessing module works under the hood to pass back and forth Python objects between processes. If you are only going to serialize data structures such as lists, dictionaries with data types such as strings, numbers, bools, None and you want to share that data between non-Python application, I could also suggest the use of the JSON module. JSON is a standard format (see json.org) supported by many programming languages. JSON is very popular for web service APIs. Your Python server could expose web APIs and applications written in different programming languages (Java, C, C#, Javascript ...) can call an API and interpret the JSON data your server sends back. This is some food for thought. HTH, -- Alex | twitter.com/alexconrad From alan.gauld at btinternet.com Thu Jun 2 18:13:32 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 2 Jun 2011 17:13:32 +0100 Subject: [Tutor] Structured files? References: Message-ID: "Alexandre Conrad" wrote > you want to share that data between non-Python application, I could > also suggest the use of the JSON module. JSON is a standard format > (see json.org) supported by many programming languages. But isn't it a string based format? I thought JSON converted everything into XML strings? That makes it hugely wasteful of space which is usually the reason for using a binary format in the first place. But I've only used JSON once from within TurboGears so I am no expert! -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From wprins at gmail.com Thu Jun 2 18:46:27 2011 From: wprins at gmail.com (Walter Prins) Date: Thu, 2 Jun 2011 17:46:27 +0100 Subject: [Tutor] Structured files? In-Reply-To: References: Message-ID: On 2 June 2011 17:13, Alan Gauld wrote: > But isn't it a string based format? > I thought JSON converted everything into XML strings? > > It's text based yes, although not XML. As for efficiency, I'd be of the view that it's probably efficient enough for the vast majority of use cases, especially when the transmission channel has compression on it (which is more often than not the case these days.) Cheers Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Thu Jun 2 19:07:06 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 03 Jun 2011 03:07:06 +1000 Subject: [Tutor] Structured files? In-Reply-To: References: Message-ID: <4DE7C33A.3020502@pearwood.info> Alan Gauld wrote: > > "Alexandre Conrad" wrote > >> you want to share that data between non-Python application, I could >> also suggest the use of the JSON module. JSON is a standard format >> (see json.org) supported by many programming languages. > > But isn't it a string based format? > I thought JSON converted everything into XML strings? JSON is a string format, but not XML. >>> import json >>> json.dumps({'a': 1, 'b': 2, 'c': 3}) '{"a": 1, "c": 3, "b": 2}' YAML is another alternative, arguably more human readable than JSON, but it's not in the standard library. Perhaps you're thinking of plist ("property list"). In Python 3.1: >>> from io import BytesIO >>> import plistlib >>> s = BytesIO() >>> plistlib.writePlist({'a': 1, 'b': 2, 'c': 3}, s) >>> print( s.getvalue().decode('ascii') ) a 1 b 2 c 3 > That makes it hugely wasteful of space which is usually the reason for > using a binary format in the first place. Meh, who cares whether your 100K of data takes 300K on disk? :) If you need/want binary storage, pickle has a binary mode. But generally, I am a big believer in sticking to text formats unless you absolutely have to use binary. The usefulness of being able to read, or even edit, your data files using a simple text editor cannot be under-estimated! -- Steven From ramit.prasad at jpmchase.com Thu Jun 2 19:02:59 2011 From: ramit.prasad at jpmchase.com (Prasad, Ramit) Date: Thu, 2 Jun 2011 13:02:59 -0400 Subject: [Tutor] Structured files? In-Reply-To: References: Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2E345FFF3C@EMARC112VS01.exchad.jpmchase.net> >But I've only used JSON once from within TurboGears so >I am no expert! If you use Firefox you have used JSON ;) that is how it stores bookmarks. I am sure it is more widely used than that. Usage seems to be on the rise but that could be that I see it more now that I know what it is. 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 marilyn at pythontrainer.com Thu Jun 2 19:57:28 2011 From: marilyn at pythontrainer.com (Marilyn Davis) Date: Thu, 2 Jun 2011 10:57:28 -0700 (PDT) Subject: [Tutor] __init__.py question In-Reply-To: <4DE6D514.8050608@pearwood.info> References: <39060.67.169.189.143.1306885493.squirrel@mail.tigertech.net> <33743.67.169.189.143.1306949849.squirrel@mail.tigertech.net> <4DE6D514.8050608@pearwood.info> Message-ID: <38794.67.169.189.143.1307037448.squirrel@mail.tigertech.net> Thank you for your careful explanation, Steven. I guess there's nothing more for me to know. While I think it is a mistake to put directories in your package directory structure that aren't part of the package, that seems to be all it's about. Well, I guess I don't feel quite so stupid. Thank you folks. Marilyn Davis On Wed, June 1, 2011 5:11 pm, Steven D'Aprano wrote: > Marilyn Davis wrote: > [...] > >> There's something I'm missing because I think you simply can't call >> something string.py unless you are willing to give up the library >> string.py. > > No, you're right about that. Python's search path is "first match wins". > Whether it's a package or a module, it will match before the library > string.py. Adding __init__.py doesn't change that. > > (Unless you re-arrange sys.path so that library modules come first.) > > > However, you can have a directory called "string", containing arbitrary > .py files. So you could drop this in your path: > > > > string/ +-- a.py > +-- b.py > > > and add string to the path so that the directory is searched, and still > get the standard string.py. (I haven't actually tried this, but it should > work.) > > Only if you put a file __init__.py into the directory will it shadow the > standard library string.py. > > Personally, I think the emphasis given in the docs about shadowing > standard library files is misplaced. I think that is actually irrelevant. I > think a more useful explanation for the need for __init__.py is simple: > how else could Python distinguish a package from a mere directory > containing Python files? > > A mere directory is not searched unless it is explicitly added to the > path; a mere directory cannot be imported. A package can be. But since a > package *is* a directory at the file system level, how should Python > distinguish them? > > I suppose Python could have the rule "the directory must end in .py to > be considered a package". But then, when you import the main package > instead of a submodule, which file should Python read? There needs to be a > standard naming convention for the file to be treated as the top-level > module. But since you have such a file, there's no longer any need for > adding a .py to the end of the directory name, since the standard file is > sufficient to determine that the directory is a package. > > That file could have been called anything, __init__.py was chosen by > analogy with __init__ methods in classes and because it's unlikely to clash > with any name package authors might choose for their own use. > > > > -- > Steven > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From marilyn at pythontrainer.com Thu Jun 2 20:03:31 2011 From: marilyn at pythontrainer.com (Marilyn Davis) Date: Thu, 2 Jun 2011 11:03:31 -0700 (PDT) Subject: [Tutor] checking if a variable is an integer? In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2E345FFA2A@EMARC112VS01.exchad.jpmcha se.net> References: <4DE6CA05.5030906@pearwood.info> <0604E20B5F6F2F4784C9C8C71C5DD4DD2E345FFA2A@EMARC112VS01.exchad.jpmchase.net> Message-ID: <57049.67.169.189.143.1307037811.squirrel@mail.tigertech.net> True that! This is the nicest, most patient, most knowledgeable, technical list I've ever experienced. That's why I keep coming back when I am hopelessly confused. Thank you. Marilyn Davis On Thu, June 2, 2011 7:04 am, Prasad, Ramit wrote: >> If not, he can google the bits he doesn't understand, or ask. We won't >> bite! > > Unless he asks for it ;) > > > 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. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From robert.sjoblom at gmail.com Thu Jun 2 22:06:05 2011 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Thu, 2 Jun 2011 22:06:05 +0200 Subject: [Tutor] Strategy to read a redirecting html page Message-ID: > When you hit the page and you get an HTTP redirect code back (say, > 302), you will need to make another call to the URL specified in the > "Location" parameter in the response headers. Then you retrieve that > new page and you can check you got an acceptable HTTP response code > (such as 200) and read the page's body (or whatever you want to do > with it). Otherwise, keep looping until you get an expected HTTP > response code. > > Note: you may get stuck in an infinite loop if two URLs redirect to each other. > > You might want to take a look at the higher level httplib module: > http://docs.python.org/library/httplib.html > > Although I don't think it can automatically follow redirects for you. > You'll have to implement the loop yourself. > > If you can rely on 3rd party packages (not part of the standard Python > library), take a look at httplib2: > https://httplib2.googlecode.com/hg/doc/html/libhttplib2.html > > This one can follow redirects. > > HTH, Sorry for bringing up an old topic like this, but writing longer messages on a phone is just not something that I want to do. Python already has the urllib/urllib2 package that automatically follow redirects, so I don't see why you'd need a 3rd-party module to deal with it? When it encounters a 301 status code from the server, urllib2 will search through its handlers and call the http_error_301 method, which will look for the Location: header and follow that address. The behaviour is defined in HTTPRedirectHandler, which can be overridden if necessary: >>> help(urllib.request.HTTPRedirectHandler) Help on class HTTPRedirectHandler in module urllib.request: class HTTPRedirectHandler(BaseHandler) | Method resolution order: | HTTPRedirectHandler | BaseHandler | builtins.object | | Methods defined here: | | http_error_301 = http_error_302(self, req, fp, code, msg, headers) | | http_error_302(self, req, fp, code, msg, headers) | # Implementation note: To avoid the server sending us into an | # infinite loop, the request object needs to track what URLs we | # have already seen. Do this by adding a handler-specific | # attribute to the Request object. | | http_error_303 = http_error_302(self, req, fp, code, msg, headers) | | http_error_307 = http_error_302(self, req, fp, code, msg, headers) | | redirect_request(self, req, fp, code, msg, headers, newurl) | Return a Request or None in response to a redirect. | | This is called by the http_error_30x methods when a | redirection response is received. If a redirection should | take place, return a new Request to allow http_error_30x to | perform the redirect. Otherwise, raise HTTPError if no-one | else should try to handle this url. Return None if you can't | but another Handler might. | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | inf_msg = 'The HTTP server returned a redirect error that w...n infini... | | max_redirections = 10 | | max_repeats = 4 | | ---------------------------------------------------------------------- | Methods inherited from BaseHandler: | | __lt__(self, other) | | add_parent(self, parent) | | close(self) | | ---------------------------------------------------------------------- | Data descriptors inherited from BaseHandler: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Data and other attributes inherited from BaseHandler: | | handler_order = 500 best regards, Robert S. From swiftone at swiftone.org Thu Jun 2 22:50:35 2011 From: swiftone at swiftone.org (Brett Ritter) Date: Thu, 2 Jun 2011 16:50:35 -0400 Subject: [Tutor] Strategy to read a redirecting html page In-Reply-To: References: Message-ID: On Thu, Jun 2, 2011 at 4:06 PM, Robert Sjoblom wrote: > Python already has the urllib/urllib2 package that automatically > follow redirects, so I don't see why you'd need a 3rd-party module to > deal with it? When it encounters a 301 status code from the server, Ah, but I believe the issue is that the server isn't giving him a 301, it's giving him a 200 with a page explaining that "this page has moved, please update your bookmarks" etc, with a META HTTP-EQUIV tag to redirect the page after N seconds. (Based on the part where the OP said "I get the first warning/error message page and not the redirection one.") -- Brett Ritter / SwiftOne swiftone at swiftone.org From robert.sjoblom at gmail.com Thu Jun 2 23:05:39 2011 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Thu, 2 Jun 2011 23:05:39 +0200 Subject: [Tutor] Strategy to read a redirecting html page In-Reply-To: References: Message-ID: On 2 June 2011 22:50, Brett Ritter wrote: > On Thu, Jun 2, 2011 at 4:06 PM, Robert Sjoblom wrote: >> Python already has the urllib/urllib2 package that automatically >> follow redirects, so I don't see why you'd need a 3rd-party module to >> deal with it? When it encounters a 301 status code from the server, > > Ah, but I believe the issue is that the server isn't giving him a 301, > it's giving him a 200 with a page explaining that "this page has > moved, please update your bookmarks" etc, with a META HTTP-EQUIV tag > to redirect the page after N seconds. > > (Based on the part where the OP said "I get the first warning/error > message page and not the redirection one.") > > -- > Brett Ritter / SwiftOne > swiftone at swiftone.org > Ah, I see -- but people were talking about 301 and 302's, so I assumed the topic had moved to general redirections. My bad. -- best regards, Robert S. From alan.gauld at btinternet.com Fri Jun 3 02:19:12 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 3 Jun 2011 01:19:12 +0100 Subject: [Tutor] Structured files? References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2E345FFF3C@EMARC112VS01.exchad.jpmchase.net> Message-ID: "Prasad, Ramit" wrote > >But I've only used JSON once from within TurboGears so > If you use Firefox you have used JSON ;) Yeah, OK, I've used JSON on loads of apps in that sense. I meant I've only programmed with JSON once... But I suspect you knew that! :-) -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Jun 3 02:29:37 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 3 Jun 2011 01:29:37 +0100 Subject: [Tutor] Structured files? References: <4DE7C33A.3020502@pearwood.info> Message-ID: "Steven D'Aprano" wrote >> That makes it hugely wasteful of space which is usually the reason >> for using a binary format in the first place. > > Meh, who cares whether your 100K of data takes 300K on disk? :) It depends on your volumes and your platform. About 10 years ago I bought 10G of storage for a mainframe (remember the millenium bug?!). At the time a 10G hard drive for a PC was about $100. For the big iron I paid around $10,000! It was fast and it had mirroring etc as standard but it was still eye-wateringly expensive... Storage was not cheap and binary files were common. If you are working in that kind of environment binary may still be a worthwhile option. > If you need/want binary storage, pickle has a binary mode. But > generally, I am a big believer in sticking to text formats unless > you absolutely have to use binary. In general though I agree with you. The mainframe example above is the exception not the rule and disk storage is one place I don't mind XML. For network traffic I hate it and avoid it if possible! But for most file storage plain txt or XML is far easier to work with - and can also be compressed if storage is an issue. And if I need to store a lot of data I use database and let the vendor (or Opensource programmers) worry about the binary formatting!! -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From ladymcse2000 at gmail.com Fri Jun 3 08:59:50 2011 From: ladymcse2000 at gmail.com (Becky Mcquilling) Date: Thu, 2 Jun 2011 23:59:50 -0700 Subject: [Tutor] Creating a class and calling an exception Message-ID: So I'm new to doing creating classes in python and took a script I had written to parse a log file and tried to create a class just to understand it a little better. The first script below works fine. It looks at the log, checks the date and if it's too old, raises the exception and returns a set value or if the file doesn't exist it raises the exception. If the file is there and is no more than a day old, it parses the log and returns what was backed up by the utility I'm using. The Second script written here, always raises the exception and I'm missing why, any advice? *FIRST SCRIPT* import re, os import stat import sys from datetime import date, timedelta log_file = 'd:/backup_logs/backups.log' re_backup_status = re.compile(r'^\s+Files\s+:\s+\d', re.IGNORECASE) """Example of return from regexFiles: Succeeded"168933 failed:0 """ def main(): try: s = os.stat(log_file) mtime = date.fromtimestamp(s[stat.ST_MTIME]) yesterday = date.today() - timedelta(days=1) mode = s[stat.ST_MODE] if stat.S_ISREG(mode): if mtime < yesterday: print "%s" % ('succeeded:0 failed:10000') else: log1 = (open(log_file, 'r')) for line in log1: if re_backup_status.search(line): status_out = line.split() print '%s succeeded:%s failed:%s' % ( 'map:files', status_out[2], status_out[6]) log1.close() except: print "%s" %('succeeded:0 failed:10000') if __name__ == '__main__': main() * * *SECOND SCRIPT* * * import re import os import stat import sys from datetime import date, timedelta class Log_Parser: def __init__(self): self.re_backup_status = re.compile(r'^\s+Files\s+:\s+\d', re.IGNORECASE) """Example of return from regexFiles: Succeeded"168933 failed:0 """ def log_parse(self, log_file): try: s = os.stat(log_file) mtime = date.fromtimestamp(s[stat.ST_MTIME]) yesterday = date.today() - timedelta(days=1) mode = s[stat.ST_MODE] if stat.S_ISREG(mode): print ('file is there') if mtime < yesterday: print('file is the wrong date') print "%s" % ('succeeded:0 failed:10000') else: log1 = (open(log_file, 'r')) for line in log1: if re_backup_status.search(line): status_out = line.split() print '%s succeeded:%s failed:%s' % ( 'map:files', status_out[2], status_out[6]) log1.close() except: print "%s" %('succeeded:0 failed:10000') backup_log_parser = Log_Parser() backup_log_parser.log_parse('d:/backup_logs/backups.log') -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Jun 3 10:05:49 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 3 Jun 2011 09:05:49 +0100 Subject: [Tutor] Creating a class and calling an exception References: Message-ID: "Becky Mcquilling" wrote > The Second script written here, always raises the exception and I'm > missing > why, any advice? > class Log_Parser: > def __init__(self): > self.re_backup_status = re.compile(r'^\s+Files\s+:\s+\d', > re.IGNORECASE) > > def log_parse(self, log_file): > > try: > .... > for line in log1: > if re_backup_status.search(line): When accessing an attribute of a class you need to prefix with self. You are getting a name error here I suspect. > log1.close() > except: print "%s" %('succeeded:0 failed:10000') But your cattchall exception is hiding the error. If you add a raise inside the exception handler while debugging it will print the full error text. If you did that you would have been pointed to the line with the error and told the name of the bad name. Using a catchall exceptioon is OK after the code is working if you want to shield your users from tracebacks, but during debugging catchall exceptions are evil, don't do it. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From jojo.mwebaze at gmail.com Fri Jun 3 15:03:00 2011 From: jojo.mwebaze at gmail.com (Jojo Mwebaze) Date: Fri, 3 Jun 2011 15:03:00 +0200 Subject: [Tutor] pypy - CFG! Message-ID: Hi There, Anyone used pypy to create control flow graphs? I would like to request for any example. Regards Johnson -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmchase.com Fri Jun 3 17:45:22 2011 From: ramit.prasad at jpmchase.com (Prasad, Ramit) Date: Fri, 3 Jun 2011 11:45:22 -0400 Subject: [Tutor] Structured files? In-Reply-To: References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2E345FFF3C@EMARC112VS01.exchad.jpmchase.net> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2E34795F51@EMARC112VS01.exchad.jpmchase.net> >Yeah, OK, I've used JSON on loads of apps in that sense. >I meant I've only programmed with JSON once... >But I suspect you knew that! :-) What can I say, I enjoy being a "smart ass" sometimes :) 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 Fri Jun 3 17:48:45 2011 From: ramit.prasad at jpmchase.com (Prasad, Ramit) Date: Fri, 3 Jun 2011 11:48:45 -0400 Subject: [Tutor] Creating a class and calling an exception In-Reply-To: References: Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2E34795F6E@EMARC112VS01.exchad.jpmchase.net> > class Log_Parser: It is highly recommended that you use new-style classes which would be class Log_Parser(object): 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 alan.gauld at btinternet.com Fri Jun 3 19:40:44 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 3 Jun 2011 18:40:44 +0100 Subject: [Tutor] Ann: Belarussian translation of my tutor Message-ID: A new translation of Version 2 of my tutor is now available thanks to Bohdan Zograf. There is a link from the homepage of my site. Enjoy. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From ladymcse2000 at gmail.com Fri Jun 3 22:36:12 2011 From: ladymcse2000 at gmail.com (Becky Mcquilling) Date: Fri, 3 Jun 2011 13:36:12 -0700 Subject: [Tutor] Creating a class and calling an exception In-Reply-To: References: Message-ID: Thank you very much. I should have added that I did that and it ran. I had one other error in the script thta I missed. I fixed that and it ran, then I named them as recommended and it still works and fits better with conventions, so I learned two things. On Fri, Jun 3, 2011 at 1:05 AM, Alan Gauld wrote: > > "Becky Mcquilling" wrote > > The Second script written here, always raises the exception and I'm >> missing >> why, any advice? >> class Log_Parser: >> def __init__(self): >> self.re_backup_status = re.compile(r'^\s+Files\s+:\s+\d', >> re.IGNORECASE) >> >> def log_parse(self, log_file): >> >> try: >> .... >> >> for line in log1: >> if re_backup_status.search(line): >> > > When accessing an attribute of a class you need to prefix with self. > You are getting a name error here I suspect. > > > log1.close() >> except: print "%s" %('succeeded:0 failed:10000') >> > > But your cattchall exception is hiding the error. If you add > a raise inside the exception handler while debugging it > will print the full error text. > > If you did that you would have been pointed to the > line with the error and told the name of the bad name. > Using a catchall exceptioon is OK after the code is > working if you want to shield your users from tracebacks, > but during debugging catchall exceptions are evil, > don't do it. > > 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 vincentbalmori at yahoo.com Sun Jun 5 00:03:32 2011 From: vincentbalmori at yahoo.com (Vincent Balmori) Date: Sat, 4 Jun 2011 15:03:32 -0700 (PDT) Subject: [Tutor] Loop Message-ID: <170038.14653.qm@web59416.mail.ac4.yahoo.com> Hello. Right now I am learning the python language through Python Programming for the Absolute Beginner 3rd Edition. I am having trouble with one question in Ch. 3 #2, which says "Write a program that flips a coin 100 times and then tells you the number of heads and tails." Right now I am having trouble connecting the random.randint function into the loop. # Coin import random # Set up Values coin = random.randint(1,2) tails = 0 heads = 0 if (coin == 1): tails += 1 else: heads += 1 toss = 0 while toss < 100: toss += 1 coin = input(random.randint(1,2) print("Toss Count:", count) print("Tails:", tails) print("Heads:", heads) input("\n\nPress the enter key to exit.") -------------- next part -------------- An HTML attachment was scrubbed... URL: From alexandre.conrad at gmail.com Sun Jun 5 00:48:52 2011 From: alexandre.conrad at gmail.com (Alexandre Conrad) Date: Sat, 4 Jun 2011 15:48:52 -0700 Subject: [Tutor] Loop In-Reply-To: <170038.14653.qm@web59416.mail.ac4.yahoo.com> References: <170038.14653.qm@web59416.mail.ac4.yahoo.com> Message-ID: Vincent, You will need to move the line that flips the coin: coin = random.randint(1,2) and the if/else logic *inside* the loop so it will be repeated as many times as needed. I'm not sure what you want to do with the input() inside the loop. Remove this. Alex 2011/6/4 Vincent Balmori : > Hello. Right now I am learning the python language through Python > Programming for the Absolute Beginner 3rd Edition. I am having trouble with > one question in Ch. 3 #2, which says "Write a program that flips a coin 100 > times and then tells you the number of heads and tails." Right now I am > having trouble connecting the random.randint function into the loop. > > # Coin > import random > # Set up Values > coin = random.randint(1,2) > tails = 0 > heads = 0 > if (coin == 1): > ?? ?tails += 1 > else: > ?? ?heads += 1 > toss = 0 > while toss < 100: > ?? ?toss += 1 > ?? ?coin = input(random.randint(1,2) > > print("Toss Count:", count) > print("Tails:", tails) > print("Heads:", heads) > 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 > > -- Alex | twitter.com/alexconrad From alan.gauld at btinternet.com Sun Jun 5 02:04:16 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 5 Jun 2011 01:04:16 +0100 Subject: [Tutor] Loop References: <170038.14653.qm@web59416.mail.ac4.yahoo.com> Message-ID: "Vincent Balmori" wrote > you the number of heads and tails." Right now I am > having trouble connecting the random.randint function > into the loop. Break the problem statement down. You have correctly worked out that randint(1,2) will equate to tossing the coin. You want to do that 100 times so it must be inside a loop that repeats 100 times. The normal loop to choose for a fixed number of repititions is a for loop: for count in range(100): result = randint(....) And you know how to work out if its heads or tails based on result, so that also goes in the loop. (Hint: You only really need one of them since the other is 100-X) > while toss < 100: > toss += 1 > coin = input(random.randint(1,2) I have no idea what this is doing, and I suspect neither do you! Did you try walking it through in your head? ( Hint: In programming never guess what your code might do, be sure. Its easier to debug that way!) > print("Toss Count:", count) > print("Tails:", tails) > print("Heads:", heads) Yep, that bit oughta work. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From benjamin.gregg at virginmedia.com Sun Jun 5 12:25:27 2011 From: benjamin.gregg at virginmedia.com (Benjamin Gregg) Date: Sun, 05 Jun 2011 11:25:27 +0100 Subject: [Tutor] python "glue" Message-ID: <4DEB5997.3040708@virginmedia.com> Hi I recently bought a book (python programing for the absolute beginner) and it said python was a "glue" language (could work with other languages) I've been trying to make apps for android and webOS and I was wondering if I could use python for doing this through "glueing" to program games on android and webOS can anyone help? yours sincerely minipot p.s:I have already tried pygame subset for android but it didn't give me enough freedom. From kb1pkl at aim.com Sun Jun 5 18:57:32 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Sun, 05 Jun 2011 12:57:32 -0400 Subject: [Tutor] python "glue" In-Reply-To: <4DEB5997.3040708@virginmedia.com> References: <4DEB5997.3040708@virginmedia.com> Message-ID: <4DEBB57C.8080006@aim.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 06/05/2011 06:25 AM, Benjamin Gregg wrote: > Hi I recently bought a book (python programing for the absolute beginner) > and it said python was a "glue" language (could work with other languages) > I've been trying to make apps for android and webOS and I was wondering > if I could use python for doing this through "glueing" to program games > on android and webOS can anyone help? If you're on the android your options are limited. Indeed Python can work with other languages, but not all of them and not easily. The standard Python implementation, CPython, can really only glue together C or C++ stuff. Jython can do Java, and IronPython can work with anything that is using the .NET CLI. On the 'droid your best bet would probably be http://code.google.com/p/android-scripting/, but it's still very *very* limited. For webOS it looks like the only way you'll get Python is if you whip together a C(++) program that statically links to it. - -- Corey Richardson -----BEGIN PGP SIGNATURE----- Version: GnuPG v2.0.17 (GNU/Linux) iQEcBAEBAgAGBQJN67V8AAoJEAFAbo/KNFvpv/MH/088lDJQqNlOHk/vKrzTjafQ Mn0ybNrk3sKozkL5GE/UdX+ESTxmAnYUnDBM2VFNEV/FjBxyDTLfLAGEzBNs2u4t LHvClprfW00xexm6wcOLMQHmR+peaPC5MGRIZgesP63istqkSNryxFAAlzRG9WW8 mJS8+r9BkQiSSDSdXDv2Jlk3/pNIwvMpp9Pwob9+O7IW4emSfqi1MtsTlkG9TnEv HI3YQuDCSVQWyWZpUup7wSqlyUMr3LY5TiOXal4SFNLIh8Tw30p9uSB7s10VBntv SURLH0pqTM7qWb7VKLCTRNwM5cda2pooXo/CPs/CdrG4mbWvyOiqpisihYrZQ5g= =plrm -----END PGP SIGNATURE----- From alexandre.conrad at gmail.com Sun Jun 5 19:06:43 2011 From: alexandre.conrad at gmail.com (Alexandre Conrad) Date: Sun, 5 Jun 2011 10:06:43 -0700 Subject: [Tutor] python "glue" In-Reply-To: <4DEB5997.3040708@virginmedia.com> References: <4DEB5997.3040708@virginmedia.com> Message-ID: I think by "glue language", it meant that it's also a "lightweight" programming language in a sense that it can be used for scripting. Just slap pieces of code and external programs together and make it all work in harmony. When I hear "gluing", I think you did not write everything from scratch but you basically took existing programs you use everyday and automated daily tasks by "gluing" these programs together, where the glue would be a thin layer of Python. I could think of gluing if, for example, you wrote a Python program to read commands from user input, connect to multiple servers by calling the "ssh" program, issue commands to all server simultaneously, parse outputs, log them to a file, detect / reformat errors to be shown back to the end-user and upload log files to a backup server using the "ftp" program. Sorry, this doesn't answer your WebOS / Android games questions. I am not familiar with those so I can't tell. I just wanted to give my version of the "glue language" wording. 2011/6/5 Benjamin Gregg : > Hi I recently bought a book (python programing for the absolute beginner) > and it said python was a "glue" language (could work with other languages) > I've been trying to make apps for android and webOS and I was wondering > if I could use python for doing this through "glueing" to program games on > android and > webOS can anyone help? > > yours sincerely minipot > > p.s:I have already tried pygame subset for android but it didn't give me > enough freedom. > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Alex | twitter.com/alexconrad From micha_el2003 at yahoo.com Mon Jun 6 01:48:42 2011 From: micha_el2003 at yahoo.com (Michael bridges) Date: Sun, 5 Jun 2011 16:48:42 -0700 (PDT) Subject: [Tutor] No module named player_data Message-ID: <381781.47911.qm@web161319.mail.bf1.yahoo.com> why does this happen? server [folder] player_data [folder] server.py Traceback (most recent call last): File "C:\Users\MySelf\Program\game_stuff\Game_28_02_11\Servers\server_client_begining\server.py", line 3, in from player_data import PlayerArmy ImportError: No module named player_data from player_data import PlayerArmy from player_data import PlayerBaseData from player_data import PlayerEnabledFlags from player_data import PlayerResearch from player_data import PlayerResearchers from player_data import PlayerTotalWeapons from player_data import PlayerWeaponsEquipped from player_data import PlayerWeaponsUnequipped this worked before i tried: from player_data import * """from player_data import PlayerArmy from player_data import PlayerBaseData from player_data import PlayerEnabledFlags from player_data import PlayerResearch from player_data import PlayerResearchers from player_data import PlayerTotalWeapons from player_data import PlayerWeaponsEquipped from player_data import PlayerWeaponsUnequipped""" got error about PlayerBaseData not found then undid back to: from player_data import PlayerArmy from player_data import PlayerBaseData from player_data import PlayerEnabledFlags from player_data import PlayerResearch from player_data import PlayerResearchers from player_data import PlayerTotalWeapons from player_data import PlayerWeaponsEquipped from player_data import PlayerWeaponsUnequipped now it does not work why???????????????? using python 3 and tried with python 2.7 From alexandre.conrad at gmail.com Mon Jun 6 04:11:42 2011 From: alexandre.conrad at gmail.com (Alexandre Conrad) Date: Sun, 5 Jun 2011 19:11:42 -0700 Subject: [Tutor] No module named player_data In-Reply-To: <381781.47911.qm@web161319.mail.bf1.yahoo.com> References: <381781.47911.qm@web161319.mail.bf1.yahoo.com> Message-ID: 2011/6/5 Michael bridges : > why does this happen? > > server [folder] > ? ? ? player_data [folder] > ? ? ? server.py > > Traceback (most recent call last): > ?File "C:\Users\MySelf\Program\game_stuff\Game_28_02_11\Servers\server_client_begining\server.py", line 3, in > ? ?from player_data import PlayerArmy > ImportError: No module named player_data If player_data is a package (a folder containing an __init__.py file), I guess you have your class PlayerArmy defined inside the __init__.py file, or you are importing PlayerArmy from __init__.py. Could you provide more details on what the "player_data" folder contains? -- Alex | twitter.com/alexconrad From micha_el2003 at yahoo.com Mon Jun 6 04:49:13 2011 From: micha_el2003 at yahoo.com (Michael bridges) Date: Sun, 5 Jun 2011 19:49:13 -0700 (PDT) Subject: [Tutor] No module named player_data In-Reply-To: Message-ID: <404447.1119.qm@web161306.mail.bf1.yahoo.com> one of the things i deleted was __init__.py & __init__.pyc [thought it was not used, then read import again and put it back. still not working] player_data [folder] __init__.py [several .py & .pyc files] --- On Sun, 6/5/11, Alexandre Conrad wrote: > From: Alexandre Conrad > Subject: Re: [Tutor] No module named player_data > To: "Michael bridges" > Cc: Tutor at python.org > Date: Sunday, June 5, 2011, 7:11 PM > 2011/6/5 Michael bridges : > > why does this happen? > > > > server [folder] > > ? ? ? player_data [folder] > > ? ? ? server.py > > > > Traceback (most recent call last): > > ?File > "C:\Users\MySelf\Program\game_stuff\Game_28_02_11\Servers\server_client_begining\server.py", > line 3, in > > ? ?from player_data import PlayerArmy > > ImportError: No module named player_data > > If player_data is a package (a folder containing an > __init__.py file), > I guess you have your class PlayerArmy defined inside the > __init__.py > file, or you are importing PlayerArmy from __init__.py. > > Could you provide more details on what the "player_data" > folder contains? > > -- > Alex | twitter.com/alexconrad > From alexandre.conrad at gmail.com Mon Jun 6 04:58:02 2011 From: alexandre.conrad at gmail.com (Alexandre Conrad) Date: Sun, 5 Jun 2011 19:58:02 -0700 Subject: [Tutor] No module named player_data In-Reply-To: <404447.1119.qm@web161306.mail.bf1.yahoo.com> References: <404447.1119.qm@web161306.mail.bf1.yahoo.com> Message-ID: 2011/6/5 Michael bridges : > one of the things i deleted was __init__.py & __init__.pyc [thought it was not used, then read import again and put it back. still not working] You always need an __init__.py file in a folder that you want to import in Python. That tells Python to consider the folder as a Pyton package. http://effbot.org/pyfaq/what-is-init-py-used-for.htm Your original error was: "ImportError: No module named player_data". Now you have the file back, I now suspect the error message might be slightly different. Could you copy/paste it please? -- Alex | twitter.com/alexconrad From micha_el2003 at yahoo.com Mon Jun 6 05:04:00 2011 From: micha_el2003 at yahoo.com (Michael bridges) Date: Sun, 5 Jun 2011 20:04:00 -0700 (PDT) Subject: [Tutor] No module named player_data In-Reply-To: Message-ID: <4751.73582.qm@web161303.mail.bf1.yahoo.com> more specific general info [do not want to copy/paste the whole files]: [\server_client_begining\server.py] from player_data import PlayerArmy [\server_client_begining\player_data\PlayerArmy] #PlayerArmy playerName = "john" militia_amount = 100 military_amount = 10 [with more variables] [no classes, no functions, just variables] --- On Sun, 6/5/11, Alexandre Conrad wrote: > From: Alexandre Conrad > Subject: Re: [Tutor] No module named player_data > To: "Michael bridges" > Cc: Tutor at python.org > Date: Sunday, June 5, 2011, 7:11 PM > 2011/6/5 Michael bridges : > > why does this happen? > > > > server [folder] > > ? ? ? player_data [folder] > > ? ? ? server.py > > > > Traceback (most recent call last): > > ?File > "C:\Users\MySelf\Program\game_stuff\Game_28_02_11\Servers\server_client_begining\server.py", > line 3, in > > ? ?from player_data import PlayerArmy > > ImportError: No module named player_data > > If player_data is a package (a folder containing an > __init__.py file), > I guess you have your class PlayerArmy defined inside the > __init__.py > file, or you are importing PlayerArmy from __init__.py. > > Could you provide more details on what the "player_data" > folder contains? > > -- > Alex | twitter.com/alexconrad > From micha_el2003 at yahoo.com Mon Jun 6 05:05:46 2011 From: micha_el2003 at yahoo.com (Michael bridges) Date: Sun, 5 Jun 2011 20:05:46 -0700 (PDT) Subject: [Tutor] No module named player_data In-Reply-To: Message-ID: <100828.86805.qm@web161319.mail.bf1.yahoo.com> Traceback (most recent call last): File "C:\Users\MySelf\Program\game_stuff\Game_28_02_11\Servers\server_client_begining\server.py", line 3, in from player_data import PlayerArmy ImportError: No module named player_data --- On Sun, 6/5/11, Alexandre Conrad wrote: > From: Alexandre Conrad > Subject: Re: [Tutor] No module named player_data > To: "Michael bridges" > Cc: Tutor at python.org > Date: Sunday, June 5, 2011, 7:58 PM > 2011/6/5 Michael bridges : > > one of the things i deleted was __init__.py & > __init__.pyc [thought it was not used, then read import > again and put it back. still not working] > > You always need an __init__.py file in a folder that you > want to > import in Python. That tells Python to consider the folder > as a Pyton > package. > > http://effbot.org/pyfaq/what-is-init-py-used-for.htm > > Your original error was: "ImportError: No module named > player_data". > Now you have the file back, I now suspect the error message > might be > slightly different. Could you copy/paste it please? > > > -- > Alex | twitter.com/alexconrad > From micha_el2003 at yahoo.com Mon Jun 6 05:14:06 2011 From: micha_el2003 at yahoo.com (Michael bridges) Date: Sun, 5 Jun 2011 20:14:06 -0700 (PDT) Subject: [Tutor] No module named player_data In-Reply-To: Message-ID: <231615.69744.qm@web161313.mail.bf1.yahoo.com> simple file was named __ init __.py not __init__.py restored from recycle bin showed the error thanks for your help --- On Sun, 6/5/11, Alexandre Conrad wrote: > From: Alexandre Conrad > Subject: Re: [Tutor] No module named player_data > To: "Michael bridges" > Cc: Tutor at python.org > Date: Sunday, June 5, 2011, 7:58 PM > 2011/6/5 Michael bridges : > > one of the things i deleted was __init__.py & > __init__.pyc [thought it was not used, then read import > again and put it back. still not working] > > You always need an __init__.py file in a folder that you > want to > import in Python. That tells Python to consider the folder > as a Pyton > package. > > http://effbot.org/pyfaq/what-is-init-py-used-for.htm > > Your original error was: "ImportError: No module named > player_data". > Now you have the file back, I now suspect the error message > might be > slightly different. Could you copy/paste it please? > > > -- > Alex | twitter.com/alexconrad > From seasideryan at gmail.com Mon Jun 6 08:29:08 2011 From: seasideryan at gmail.com (Ryan Wu) Date: Mon, 6 Jun 2011 14:29:08 +0800 Subject: [Tutor] about print() Message-ID: Hi all, I am a newbie of python, and reading 'python essential reference'. Now I want to print this results 'a is %d' % a -> a is 42 > with the code a = 42 > test = "'a is %d' % a" > print( '%20s ->' % test, test) > but what I get is > 'a is %d' % a -> 'a is %d' % a > What is the difference of print(test) and print ( 'a is %d' % a )? Regards -------------- next part -------------- An HTML attachment was scrubbed... URL: From tommy.kaas at kaasogmulvad.dk Mon Jun 6 10:05:26 2011 From: tommy.kaas at kaasogmulvad.dk (Tommy Kaas) Date: Mon, 6 Jun 2011 10:05:26 +0200 Subject: [Tutor] search-replace Message-ID: <002301cc2420$7e6e4110$7b4ac330$@kaasogmulvad.dk> Hi tutors If I need to clean a textfile (perhaps after web scraping), I have used this method - without problems - but I'm sure there must be smarter and better ways. I'm especially interested to know how I do more than just one search-replace without having to repeat the whole step below. I'm using Python 2.6.6 on a windows pc. fin = open("dirtyfile.txt") fout = open("cleanfile.txt", "w") for line in fin: fout.write(line.replace('## ', '#')) fin.close() fout.close() Thanks, Tommy -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Jun 6 10:21:58 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 6 Jun 2011 09:21:58 +0100 Subject: [Tutor] about print() References: Message-ID: "Ryan Wu" wrote > I am a newbie of python, and reading 'python essential reference'. > > Now I want to print this results > 'a is %d' % a -> a is 42 > > with the code > > a = 42 >> test = "'a is %d' % a" test is now a literal string >> print( '%20s ->' % test, test) And this inserts the literal string into the format string then prints the literal string What I think you wanted to do is: >>> a = 42 >>> test = 'a is %d' >>> print( '%20s -> %s' % (test, test % a) ) > What is the difference of print(test) and print ( 'a is %d' % a )? In test you have the a inside the string delimiters so it is part of the string. In the second case a is outside the string and gets evaluated as a variable HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From seasideryan at gmail.com Mon Jun 6 11:18:37 2011 From: seasideryan at gmail.com (Ryan Wu) Date: Mon, 6 Jun 2011 17:18:37 +0800 Subject: [Tutor] about print() In-Reply-To: References: Message-ID: Oh, I see! It's a little stupid question :) Thanks,Alan! On 6/6/11, Alan Gauld wrote: > "Ryan Wu" wrote > >> I am a newbie of python, and reading 'python essential reference'. >> >> Now I want to print this results >> 'a is %d' % a -> a is 42 >> >> with the code >> >> a = 42 >>> test = "'a is %d' % a" > > test is now a literal string > >>> print( '%20s ->' % test, test) > > And this inserts the literal string into the format string then > prints the literal string > > What I think you wanted to do is: > >>>> a = 42 >>>> test = 'a is %d' > >>>> print( '%20s -> %s' % (test, test % a) ) > >> What is the difference of print(test) and print ( 'a is %d' % a )? > > In test you have the a inside the string delimiters so it is part > of the string. In the second case a is outside the string and > gets evaluated as a variable > > 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 > -- ---- Ryan Wu From alan.gauld at btinternet.com Mon Jun 6 11:51:22 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 6 Jun 2011 10:51:22 +0100 Subject: [Tutor] search-replace References: <002301cc2420$7e6e4110$7b4ac330$@kaasogmulvad.dk> Message-ID: "Tommy Kaas" wrote > I'm especially interested to know how I do more than just one > search-replace > without having to repeat the whole step below. > fin = open("dirtyfile.txt") > fout = open("cleanfile.txt", "w") > for line in fin: > fout.write(line.replace('## ', '#')) > fin.close() > fout.close() Can be simplified to: with open("cleanfile.txt", "w") as fout: for line in open("dirtyfile.txt"): fout.write(line.replace('## ', '#')) To do multiple replaces simply expand the inner block for line in open("dirtyfile.txt"): line = line.replace(....) #first line = line.replace(....) #second etc fout.write(line) Or if you have a lot of them: replacePatterns = [('##','#'),('!!!','!!'),....] for line in open("dirtyfile.txt"): for old,new in repace_patterns: line = line.replace(old,new) fout.write(line) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From tommy.kaas at kaasogmulvad.dk Mon Jun 6 11:58:43 2011 From: tommy.kaas at kaasogmulvad.dk (Tommy Kaas) Date: Mon, 6 Jun 2011 11:58:43 +0200 Subject: [Tutor] search-replace In-Reply-To: References: <002301cc2420$7e6e4110$7b4ac330$@kaasogmulvad.dk> Message-ID: <005101cc2430$51ac0580$f5041080$@kaasogmulvad.dk> > -----Oprindelig meddelelse----- > Fra: tutor-bounces+tommy.kaas=kaasogmulvad.dk at python.org > [mailto:tutor-bounces+tommy.kaas=kaasogmulvad.dk at python.org] P? vegne > af Alan Gauld > Sendt: 6. juni 2011 11:51 > Til: tutor at python.org > Emne: Re: [Tutor] search-replace > > > "Tommy Kaas" wrote > > > > I'm especially interested to know how I do more than just one > > search-replace without having to repeat the whole step below. > > fin = open("dirtyfile.txt") > > fout = open("cleanfile.txt", "w") > > for line in fin: > > fout.write(line.replace('## ', '#')) > > fin.close() > > fout.close() > > Can be simplified to: > > with open("cleanfile.txt", "w") as fout: > for line in open("dirtyfile.txt"): > fout.write(line.replace('## ', '#')) > > To do multiple replaces simply expand the inner block > > > for line in open("dirtyfile.txt"): > line = line.replace(....) #first > line = line.replace(....) #second etc > fout.write(line) > > Or if you have a lot of them: > > replacePatterns = [('##','#'),('!!!','!!'),....] > > for line in open("dirtyfile.txt"): > for old,new in repace_patterns: > line = line.replace(old,new) > fout.write(line) > Excellent! Thanks. tommy From davidheiserca at gmail.com Mon Jun 6 16:26:10 2011 From: davidheiserca at gmail.com (davidheiserca at gmail.com) Date: Mon, 6 Jun 2011 07:26:10 -0700 Subject: [Tutor] search-replace References: <002301cc2420$7e6e4110$7b4ac330$@kaasogmulvad.dk> <005101cc2430$51ac0580$f5041080$@kaasogmulvad.dk> Message-ID: <885709D4BBA64D6688A2FB28ECDBCEF9@dheiser> Or, open the file as a blob (one long string) and do a single 'replace'. fin = open("dirtyfile.txt", 'r').read().replace('## ', '#') open("dirtyfile.txt", 'w').write(fin) or, open("dirtyfile.txt", 'w').write(open("dirtyfile.txt", 'r').read().replace('## ', '#')) ----- Original Message ----- From: "Tommy Kaas" To: Sent: Monday, June 06, 2011 2:58 AM Subject: Re: [Tutor] search-replace > -----Oprindelig meddelelse----- > Fra: tutor-bounces+tommy.kaas=kaasogmulvad.dk at python.org > [mailto:tutor-bounces+tommy.kaas=kaasogmulvad.dk at python.org] P? vegne > af Alan Gauld > Sendt: 6. juni 2011 11:51 > Til: tutor at python.org > Emne: Re: [Tutor] search-replace > > > "Tommy Kaas" wrote > > > > I'm especially interested to know how I do more than just one > > search-replace without having to repeat the whole step below. > > fin = open("dirtyfile.txt") > > fout = open("cleanfile.txt", "w") > > for line in fin: > > fout.write(line.replace('## ', '#')) > > fin.close() > > fout.close() > > Can be simplified to: > > with open("cleanfile.txt", "w") as fout: > for line in open("dirtyfile.txt"): > fout.write(line.replace('## ', '#')) > > To do multiple replaces simply expand the inner block > > > for line in open("dirtyfile.txt"): > line = line.replace(....) #first > line = line.replace(....) #second etc > fout.write(line) > > Or if you have a lot of them: > > replacePatterns = [('##','#'),('!!!','!!'),....] > > for line in open("dirtyfile.txt"): > for old,new in repace_patterns: > line = line.replace(old,new) > fout.write(line) > Excellent! Thanks. tommy _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From micha_el2003 at yahoo.com Tue Jun 7 04:43:47 2011 From: micha_el2003 at yahoo.com (Michael bridges) Date: Mon, 6 Jun 2011 19:43:47 -0700 (PDT) Subject: [Tutor] floats Message-ID: <981702.91185.qm@web161312.mail.bf1.yahoo.com> i saw it somewhere, but where? i want to 10 / 1000 and get 0.01 not 0 if 1000 is made 1000.00 then 0.01 is printed but that gives 500 / 1000.00 is 0.5 not 0.50 i might be thinking C# not python. can someone till me how to get a two decimal precision every time? From modulok at gmail.com Tue Jun 7 05:49:51 2011 From: modulok at gmail.com (Modulok) Date: Mon, 6 Jun 2011 21:49:51 -0600 Subject: [Tutor] floats In-Reply-To: <981702.91185.qm@web161312.mail.bf1.yahoo.com> References: <981702.91185.qm@web161312.mail.bf1.yahoo.com> Message-ID: >> Can someone till me how to get a two decimal precision every time? print "%.2f" % (500/1000.0) # or... result = 500 / 1000.0 print "%.2f" % result Using 'new' style string formatting works too: print "{0:.2f}".format(500/1000.0) -Modulok- On 6/6/11, Michael bridges wrote: > i saw it somewhere, but where? > > i want to 10 / 1000 and get 0.01 not 0 > if 1000 is made 1000.00 then 0.01 is printed > but that gives 500 / 1000.00 is 0.5 not 0.50 > > i might be thinking C# not python. > > can someone till me how to get a two decimal precision every time? > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From cwitts at compuscan.co.za Tue Jun 7 07:15:59 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Tue, 07 Jun 2011 07:15:59 +0200 Subject: [Tutor] floats In-Reply-To: <981702.91185.qm@web161312.mail.bf1.yahoo.com> References: <981702.91185.qm@web161312.mail.bf1.yahoo.com> Message-ID: <4DEDB40F.7020302@compuscan.co.za> On 2011/06/07 04:43 AM, Michael bridges wrote: > i saw it somewhere, but where? > > i want to 10 / 1000 and get 0.01 not 0 > if 1000 is made 1000.00 then 0.01 is printed > but that gives 500 / 1000.00 is 0.5 not 0.50 > > i might be thinking C# not python. > > can someone till me how to get a two decimal precision every time? > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > >>> 100/1000 0 >>> from __future__ import division >>> 100/1000 0.1 >>> 100//1000 0 So you can still get the old behaving floor division using double divisors and any normal syntax will be true division. In Python 3.x it's already the standard, this is only necessary for Python 2.x -- Christian Witts // -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Jun 7 10:16:58 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 7 Jun 2011 09:16:58 +0100 Subject: [Tutor] floats References: <981702.91185.qm@web161312.mail.bf1.yahoo.com> Message-ID: "Michael bridges" wrote > i want to 10 / 1000 and get 0.01 not 0 > if 1000 is made 1000.00 then 0.01 is printed > but that gives 500 / 1000.00 is 0.5 not 0.50 > > can someone till me how to get a two decimal precision every time? You are confusing two different things.. The first case is that of integer versus float division. You solve that by either explicitly making one of the numbers a float or by converting to float using the foloat() operation. The second issue is the *representation* of the result. The number of decimal places displayed is a matter of representation only, the actual value stored will not change. Thus 0.5 and 0.50 and 0.50000000 are all the same value in memory, it is only how they are printed that changes and that is controlled by how you choose to format the display. Typically you use a format string: res = 10/float(20) "%f" % res "%7.3f" % res "%5.1f" % res "%6e" % res "%6.4g" % res HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From micha_el2003 at yahoo.com Tue Jun 7 22:10:02 2011 From: micha_el2003 at yahoo.com (Michael bridges) Date: Tue, 7 Jun 2011 13:10:02 -0700 (PDT) Subject: [Tutor] floats In-Reply-To: Message-ID: <553885.76265.qm@web161306.mail.bf1.yahoo.com> ok, will attempt to clarify. i want to out put of two numbers [int or float or anything] to be x.xx not x.x. i want two numbers after the decimal not one. --- On Tue, 6/7/11, Alan Gauld wrote: > From: Alan Gauld > Subject: Re: [Tutor] floats > To: tutor at python.org > Date: Tuesday, June 7, 2011, 1:16 AM > > "Michael bridges" > wrote > > > i want to 10 / 1000 and get 0.01 not 0 > > if 1000 is made 1000.00 then 0.01 is printed > > but that gives 500 / 1000.00 is 0.5 not 0.50 > > > > can someone till me how to get a two decimal precision > every time? > > You are confusing two different things.. > The first case is that of integer versus float division. > You solve that by either explicitly making one of the > numbers a float or by converting to float using the > foloat() operation. > > The second issue is the *representation* of the result. > The number of decimal places displayed is a matter > of representation only, the actual value stored will not > change. Thus 0.5 and 0.50 and 0.50000000 are all > the same value in memory, it is only how they are > printed that changes and that is controlled by how > you choose to format the display. > > Typically you use a format string: > > res = 10/float(20) > "%f" % res > "%7.3f" % res > "%5.1f" % res > "%6e" % res > "%6.4g" % res > > > 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 wprins at gmail.com Tue Jun 7 22:31:27 2011 From: wprins at gmail.com (Walter Prins) Date: Tue, 7 Jun 2011 21:31:27 +0100 Subject: [Tutor] floats In-Reply-To: <553885.76265.qm@web161306.mail.bf1.yahoo.com> References: <553885.76265.qm@web161306.mail.bf1.yahoo.com> Message-ID: Hello Michael On 7 June 2011 21:10, Michael bridges wrote: > ok, will attempt to clarify. > i want to out put of two numbers [int or float or anything] to be x.xx not > x.x. > i want two numbers after the decimal not one. > > Alan's already given you exactly the correct answer. Have you tried his suggestions? What did you not understand or what problems did you run into? Here's a little example from an interactive Python interpreter session which shows you how you can play with these concepts to help clarify your understanding: Python 2.7 (r27:82525, Jul 4 2010, 07:43:08) [MSC v.1500 64 bit (AMD64)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> res = 10/float(20) >>> res 0.5 >>> "%f" % res '0.500000' >>> "%7.3f" % res ' 0.500' >>> str = "%6e" % res >>> str '5.000000e-01' >>> print str 5.000000e-01 >>> Regards, Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From mbrunt12 at gmail.com Tue Jun 7 23:26:00 2011 From: mbrunt12 at gmail.com (Matthew Brunt) Date: Tue, 7 Jun 2011 16:26:00 -0500 Subject: [Tutor] if statement Message-ID: i'm very new to python (currently going through a python for beginners book at work to pass the time), and i'm having trouble with an if statement exercise. basically, i'm creating a very simple password program that displays "Access Granted" if the if statement is true. the problem i'm having is that no matter what i set the password to, it seems like it's ignoring the if statement (and failing to print "Access Granted"). the code is copied below. i'm pretty sure it's my own programming ignorance, but i would greatly appreciate any feedback. # Granted or Denied # Demonstrates an else clause print("Welcome to System Security Inc.") print("-- where security is our middle name\n") password = input("Enter your password: ") if password == "a": print("Access Granted") input("\n\nPress the enter key to exit.") From andreengels at gmail.com Tue Jun 7 23:38:05 2011 From: andreengels at gmail.com (Andre Engels) Date: Tue, 7 Jun 2011 23:38:05 +0200 Subject: [Tutor] if statement In-Reply-To: References: Message-ID: On Tue, Jun 7, 2011 at 11:26 PM, Matthew Brunt wrote: > i'm very new to python (currently going through a python for beginners > book at work to pass the time), and i'm having trouble with an if > statement exercise. ?basically, i'm creating a very simple password > program that displays "Access Granted" if the if statement is true. > the problem i'm having is that no matter what i set the password to, > it seems like it's ignoring the if statement (and failing to print > "Access Granted"). ?the code is copied below. ?i'm pretty sure it's my > own programming ignorance, but i would greatly appreciate any > feedback. Actually, no, this case it's not your ignorance. What is probably going on is that you are using Python 2, but the book is going with Python 3. I won't get into the details, but the function that does what input() does in Python 3, is called raw_input() in Python 2 (and the Python 2 input() function is advised against using for security reasons). Probably if you change input to raw_input in your program, it does do what you want it to do. > # Granted or Denied > # Demonstrates an else clause > > print("Welcome to System Security Inc.") > print("-- where security is our middle name\n") > > password = input("Enter your password: ") > > if password == "a": > ? print("Access Granted") > > 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 > -- Andr? Engels, andreengels at gmail.com From sulinet at postafiok.hu Wed Jun 8 00:38:01 2011 From: sulinet at postafiok.hu (=?ISO-8859-1?Q?V=E1las_P=E9ter?=) Date: Wed, 8 Jun 2011 00:38:01 +0200 Subject: [Tutor] Copying a mutable Message-ID: Hi, let X be a mutable container, such as dict/set/list=bytearray, and Y=X, When I change X, Y will follow it, having always the same value, although id(X)!=id(Y). How is that, what is the explanation? Meanwhile the same for immutable types results a real copy, and so does for simple mutables such as int. I suspect it has something to do with pointers, but what is the difference between mutables and immutables, and why have they different id's if they are the same? -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Jun 8 00:44:10 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 7 Jun 2011 23:44:10 +0100 Subject: [Tutor] if statement References: Message-ID: "Andre Engels" wrote > Actually, no, this case it's not your ignorance. What is probably > going on is that you are using Python 2, but the book is going with > Python 3. You can quickly check the version by just typing python at an OS command prompt to get into the interactive interpreter(>>>). The welcome message should tell you the version you are running. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From waynejwerner at gmail.com Wed Jun 8 01:02:01 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Tue, 7 Jun 2011 18:02:01 -0500 Subject: [Tutor] Copying a mutable In-Reply-To: References: Message-ID: Apologies for the top post, my phone doesn't allow editing the message body. You are slightly confused - ints are not mutable! You can combine or multiply them, along with several other operations, but they are certainly not mutable. The easiest way to check is use them as keys in a dict. You can't do that with lists or other mutable types. Since I don't have computer access right now I can't look up the docs on id, but hopefully someone else can enlighten you. But ints are definitely immutable. I suspect you're confusing the fact that you can easily reassign ints with mutability. HTH, Wayne On Jun 7, 2011 5:50 PM, "V?las P?ter" wrote: Hi, let X be a mutable container, such as dict/set/list=bytearray, and Y=X, When I change X, Y will follow it, having always the same value, although id(X)!=id(Y). How is that, what is the explanation? Meanwhile the same for immutable types results a real copy, and so does for simple mutables such as int. I suspect it has something to do with pointers, but what is the difference between mutables and immutables, and why have they different id's if they are the same? _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From sulinet at postafiok.hu Wed Jun 8 01:09:06 2011 From: sulinet at postafiok.hu (=?ISO-8859-1?Q?V=E1las_P=E9ter?=) Date: Wed, 8 Jun 2011 01:09:06 +0200 Subject: [Tutor] Copying a mutable In-Reply-To: References: Message-ID: 2011. j?nius 8. 1:02 Wayne Werner ?rta, : > You are slightly confused - ints are not mutable! > All right, I was really wrong in this question (here it is after midnight :-), but this doesn't make an influence on the main question. -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Wed Jun 8 01:11:33 2011 From: wprins at gmail.com (Walter Prins) Date: Wed, 8 Jun 2011 00:11:33 +0100 Subject: [Tutor] Copying a mutable In-Reply-To: References: Message-ID: Hi, 2011/6/7 V?las P?ter > Hi, > > let X be a mutable container, such as dict/set/list=bytearray, and Y=X, > When I change X, Y will follow it, having always the same value, although > id(X)!=id(Y). That's not correct: Python 2.7 (r27:82525, Jul 4 2010, 07:43:08) [MSC v.1500 64 bit (AMD64)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> x=[1,2,3] >>> y=x >>> id(x) 36115464L >>> id(y) 36115464L >>> x.append(4) >>> id(x) 36115464L >>> id(y) 36115464L >>> x [1, 2, 3, 4] >>> As you can see, x and y are references to the same object (e.g. with the same id.) Regards Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From nathan2012 at 163.com Wed Jun 8 03:08:55 2011 From: nathan2012 at 163.com (Nathan) Date: Wed, 8 Jun 2011 09:08:55 +0800 (CST) Subject: [Tutor] Copying a mutable In-Reply-To: References: Message-ID: <1a7d7475.121f5.1306ccb8524.Coremail.nathan2012@163.com> unsubscribe ? 2011-06-08 07:11:33?"Walter Prins" ??? Hi, 2011/6/7 V?las P?ter Hi, let X be a mutable container, such as dict/set/list=bytearray, and Y=X, When I change X, Y will follow it, having always the same value, although id(X)!=id(Y). That's not correct: Python 2.7 (r27:82525, Jul 4 2010, 07:43:08) [MSC v.1500 64 bit (AMD64)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> x=[1,2,3] >>> y=x >>> id(x) 36115464L >>> id(y) 36115464L >>> x.append(4) >>> id(x) 36115464L >>> id(y) 36115464L >>> x [1, 2, 3, 4] >>> As you can see, x and y are references to the same object (e.g. with the same id.) Regards Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Wed Jun 8 04:19:32 2011 From: davea at ieee.org (Dave Angel) Date: Tue, 07 Jun 2011 22:19:32 -0400 Subject: [Tutor] Copying a mutable In-Reply-To: References: Message-ID: <4DEEDC34.90206@ieee.org> On 01/-10/-28163 02:59 PM, V?las P?ter wrote: > Hi, > > let X be a mutable container, such as dict/set/list=bytearray, and Y=X, > When I change X, Y will follow it, having always the same value, although > id(X)!=id(Y). How is that, what is the explanation? Meanwhile the same for > immutable types results a real copy, and so does for simple mutables such as > int. > > I suspect it has something to do with pointers, but what is the difference > between mutables and immutables, and why have they different id's if they > are the same? > It would help greatly if you actually posted some code that showed your confusion, since there are several errors in your message. As Wayne pointed out, integers are immutable. There are no methods on them that modify them in place. All you can do is bind a variable to a different integer object. Further, if you set Y=X, the id's will be the same. Try it, and paste the actual test into your message. Don't just paraphrase. Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> x = [4, 5,6] >>> y = x >>> id(y) 24789144 >>> id(x) 24789144 Now, if you change x by doing an append, for example, they both change: You mutated the object to which they both refer. >>> x.append(42) >>> x [4, 5, 6, 42] >>> y [4, 5, 6, 42] >>> But if you rebind one of them, then they can diverge: >>> x = [3] >>> x [3] >>> y [4, 5, 6, 42] >>> id(x) 24978568 >>> id(y) 24789144 Now you can notice that x has a different id. It's bound to a different object. Now, if an object is immutable, then the question of what happens when you change the object is nonsensical. Since you can't change it, you don't really care if the two names are bound to same object, or just to two objects that happen to have the same value. One more thing. Binding happens in an assignment, but it also happens in a function call, and in some import syntaxes and in for loops, generator expressions, and list comprehensions. Some of that behavior can change between different versions of Python, so if you start getting into those corners, you'll have to be more specific. HTH DaveA From sulinet at postafiok.hu Wed Jun 8 08:30:39 2011 From: sulinet at postafiok.hu (=?ISO-8859-1?Q?V=E1las_P=E9ter?=) Date: Wed, 8 Jun 2011 08:30:39 +0200 Subject: [Tutor] Copying a mutable In-Reply-To: <4DEEDC34.90206@ieee.org> References: <4DEEDC34.90206@ieee.org> Message-ID: Walter and Dave, thank you for the useful and detailed answer, now I see it better. I didn't write code, because once I realized I had spoiled something, the mistake has no more importance except historical, the correct solutions have importance. 2011. j?nius 8. 4:19 Dave Angel ?rta, : > Now, if an object is immutable, then the question of what happens when you > change the object is nonsensical. Since you can't change it, you don't > really care if the two names are bound to same object, or just to two > objects that happen to have the same value. > Being one of the purposes of Python to be a simple educational language, I want to make this simple to a beginner who does care. :-) Here is a piece of code, Python 3.1.2, a small game with a list and a tuple: >>> li=[3,4] >>> id(li) 13711200 >>> la=li >>> id(la) 13711200 >>> li*=4 >>> li [3, 4, 3, 4, 3, 4, 3, 4] >>> la [3, 4, 3, 4, 3, 4, 3, 4] >>> id(li) 13711200 >>> tup=(3,4) >>> id(tup) 13697392 >>> top=tup >>> id(top) 13697392 >>> tup*=4 >>> tup (3, 4, 3, 4, 3, 4, 3, 4) >>> top (3, 4) >>> id(tup) 12956016 >>> id(top) 13697392 My question is: how would you explain the different behaviour of a list and a tuple for a beginner? Formally we made the same intervention to these poor guys, the list and the tuple, they look the same except parenthesis and square bracket, but they reacted differently. Although tuples are immutable, the beginner only sees that they have changed in the same way. This is another point the beginner may be confused: multiple assignments. Formally we play the same game with an int and a list, and they will again react in a different way. >>> n=m=8 >>> m*=8 >>> m 64 >>> n 8 >>> n=m=[2,3] >>> m*=8 >>> m [2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3] >>> n [2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3] > > One more thing. Binding happens in an assignment, but it also happens in a > function call, and in some import syntaxes and in for loops, generator > expressions, and list comprehensions. Just to precisely understand English words, because this is a foreign language for me. As far as I understand, assignment means giving a value to a variable which is the expression used by classical languages that have variables (such as Pascal or Basic). Python has no variables, since even the simpliest data is an object, but we still say assignment, because it is comfortable. In this sense, if I say, "assignment" is a subset of "binding", is it correct? P?ter -------------- next part -------------- An HTML attachment was scrubbed... URL: From vincentbalmori at yahoo.com Wed Jun 8 10:08:26 2011 From: vincentbalmori at yahoo.com (Vincent Balmori) Date: Wed, 8 Jun 2011 01:08:26 -0700 (PDT) Subject: [Tutor] Python Beginners Message-ID: <734049.92004.qm@web59414.mail.ac4.yahoo.com> Hello. Right now I am learning the python language through Python Programming for the Absolute Beginner 3rd Edition. I am having trouble with one question in Ch. 4 #3, which says "Improve 'WordJumble so that each word is paired with a hint. The player should be able to see the hint if he or she is stuck. Add a scoring system that rewards players who solve a jumble without asking for the hint'". Right now I am having trouble with giving the 'hint' variable a value despite the conditions. Everything else is working fine. # Word Jumble # # The computer picks a random word and then "jumbles" it # The player has to guess the original word import random # create a sequence of words to choose from WORDS = ("python", "jumble", "easy", "difficult", "answer", "xylophone") # pick one word randomly from the sequence word = random.choice(WORDS) # create a variable to use later to see if the guess is correct correct = word # create a jumbled version of the word jumble ="" while word: position = random.randrange(len(word)) jumble += word[position] word = word[:position] + word[(position + 1):] # hints for each word hint = None if word == "python": hint = ("It's a snake!!") elif word == "jumble": hint = ("Shake Those Words!") elif word == "easy": hint = ("Not Hard!") elif word == "difficult": hint = ("Not Easy!") elif word == "answer": hint = ("I ask a question you have an...") elif word == "xylophone": hint = ("Metal bars with two drum sticks") # start the game print( """ Welcome to Word Jumble! Unscramble the letters to make a word. (Press the enter key at the prompt to quit.) """ ) print("The jumble is:", jumble) print("\nFor a hint, type in 'yes'. If not, type in 'no'.") helpcount = 0 help = input("Do you need a hint?: ") if help == "yes": print(hint) helpcount += 1 guess = input("\nYour guess: ") elif help == "no": guess = input("\nYour guess: ") while guess != correct and guess != "": print("Sorry, that's not it.") guess = input("Your guess: ") if guess == correct: print("That's it! You guessed it!") if helpcount == 0: print("And you didn't even need a hint! You're awesome!\n") print("Thanks for playing.") input("\n\nPress the enter key to exit.") -------------- next part -------------- An HTML attachment was scrubbed... URL: From sulinet at postafiok.hu Wed Jun 8 10:23:23 2011 From: sulinet at postafiok.hu (=?ISO-8859-1?Q?V=E1las_P=E9ter?=) Date: Wed, 8 Jun 2011 10:23:23 +0200 Subject: [Tutor] Python Beginners In-Reply-To: <734049.92004.qm@web59414.mail.ac4.yahoo.com> References: <734049.92004.qm@web59414.mail.ac4.yahoo.com> Message-ID: Since you have jumbled the word in the same variable, you have a very small chance (1:len(word)! which is 1:120 for a five-letter word) to have any of the given words in the variable "word" whan your program reaches the yellow part. You shold try to use "correct" instead of "word" in the yellow if. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Wed Jun 8 12:58:07 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 08 Jun 2011 20:58:07 +1000 Subject: [Tutor] if statement In-Reply-To: References: Message-ID: <4DEF55BF.2050706@pearwood.info> Matthew Brunt wrote: > i'm very new to python (currently going through a python for beginners > book at work to pass the time), and i'm having trouble with an if > statement exercise. basically, i'm creating a very simple password > program that displays "Access Granted" if the if statement is true. > the problem i'm having is that no matter what i set the password to, > it seems like it's ignoring the if statement (and failing to print > "Access Granted"). the code is copied below. i'm pretty sure it's my > own programming ignorance, but i would greatly appreciate any > feedback. More important than the exact solution to the problem is to learn how to solve this sort of problem: > password = input("Enter your password: ") > if password == "a": > print("Access Granted") If this is not doing what you expect, you should see what password actually is: print(password) It might also help to print the repr() of password, in case there are any unexpected spaces or other characters: print(repr(password)) Of course, if you're getting an error instead, then you should read the error message, and look at the full traceback, and see what it says. -- Steven From steve at pearwood.info Wed Jun 8 12:53:25 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 08 Jun 2011 20:53:25 +1000 Subject: [Tutor] Python Beginners In-Reply-To: <734049.92004.qm@web59414.mail.ac4.yahoo.com> References: <734049.92004.qm@web59414.mail.ac4.yahoo.com> Message-ID: <4DEF54A5.5070105@pearwood.info> Vincent Balmori wrote: > Hello. Right now I am learning the python language through Python Programming > for the Absolute Beginner 3rd Edition. I am having trouble with one question in > Ch. 4 #3, which says "Improve 'WordJumble so that each word is paired with a > hint. The player should be able to see the hint if he or she is stuck. Add a > scoring system that rewards players who solve a jumble without asking for the > hint'". > > Right now I am having trouble with giving the 'hint' variable a value despite > the conditions. Everything else is working fine. Try adding an "else" clause to your "if word == ... hint = ..." block. else: print "word = '%s'" % word I think you might be surprised by the value of word. A bit more advice for you: > # create a jumbled version of the word > jumble ="" > while word: > position = random.randrange(len(word)) > jumble += word[position] > word = word[:position] + word[(position + 1):] That's a rather complicated way to shuffle word. Here's a better way: >>> import random >>> word = 'python' >>> jumble = list(word) >>> random.shuffle(jumble) >>> jumble = ''.join(jumble) >>> jumble 'ytohpn' -- Steven From davea at ieee.org Wed Jun 8 13:00:23 2011 From: davea at ieee.org (Dave Angel) Date: Wed, 08 Jun 2011 07:00:23 -0400 Subject: [Tutor] Python Beginners In-Reply-To: <734049.92004.qm@web59414.mail.ac4.yahoo.com> References: <734049.92004.qm@web59414.mail.ac4.yahoo.com> Message-ID: <4DEF5647.7050408@ieee.org> On 01/-10/-28163 02:59 PM, Vincent Balmori wrote: > Hello. Right now I am learning the python language through Python Programming > for the Absolute Beginner 3rd Edition. I am having trouble with one question in > Ch. 4 #3, which says "Improve 'WordJumble so that each word is paired with a > hint. The player should be able to see the hint if he or she is stuck. Add a > scoring system that rewards players who solve a jumble without asking for the > hint'". > > Right now I am having trouble with giving the 'hint' variable a value despite > the conditions. Everything else is working fine. > Don't try to use color to give us any information, since this is a text newsgroup. I wouldn't know you had tried if Valas hadn't mentioned yellow. > # Word Jumble > # > # The computer picks a random word and then "jumbles" it > # The player has to guess the original word > > import random > > # create a sequence of words to choose from > WORDS = ("python", "jumble", "easy", "difficult", "answer", "xylophone") > # pick one word randomly from the sequence > word = random.choice(WORDS) > # create a variable to use later to see if the guess is correct > correct = word > Since the words and hints are so closely tied, you should just make one list/tuple with both of them, so that once you have chosen a word, you've already got the hint. WORDS = (("python","It's a snake"), ("jumble", Shake Those Words"), ... then word, hint = random.choice(WORDS) > # create a jumbled version of the word > jumble ="" > while word: > position = random.randrange(len(word)) > jumble += word[position] > word = word[:position] + word[(position + 1):] > There's a random function that does this in one go. Look through the module and see if you can find it. > # hints for each word > > hint = None > if word == "python": > hint = ("It's a snake!!") > elif word == "jumble": > hint = ("Shake Those Words!") > elif word == "easy": > hint = ("Not Hard!") > elif word == "difficult": > hint = ("Not Easy!") > elif word == "answer": > hint = ("I ask a question you have an...") > elif word == "xylophone": > hint = ("Metal bars with two drum sticks") > Don't need this part any more. DaveA From steve at pearwood.info Wed Jun 8 13:15:47 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 08 Jun 2011 21:15:47 +1000 Subject: [Tutor] Python Beginners In-Reply-To: <4DEF5647.7050408@ieee.org> References: <734049.92004.qm@web59414.mail.ac4.yahoo.com> <4DEF5647.7050408@ieee.org> Message-ID: <4DEF59E3.2020406@pearwood.info> Dave Angel wrote: > On 01/-10/-28163 02:59 PM, Vincent Balmori wrote: >> Hello. Right now I am learning the python language through Python >> Programming >> for the Absolute Beginner 3rd Edition. I am having trouble with one >> question in >> Ch. 4 #3, which says "Improve 'WordJumble so that each word is paired >> with a >> hint. The player should be able to see the hint if he or she is stuck. >> Add a >> scoring system that rewards players who solve a jumble without asking >> for the >> hint'". >> >> Right now I am having trouble with giving the 'hint' variable a value >> despite >> the conditions. Everything else is working fine. >> > > Don't try to use color to give us any information, since this is a text > newsgroup. I wouldn't know you had tried if Valas hadn't mentioned yellow. Not to mention that about one in 12 males (and 1 in 200 females) are colour blind and have difficulty distinguishing colours, and a surprisingly large number of completely blind people manage to read and write emails by use of screen readers and speech-to-text programs. -- Steven From steve at pearwood.info Wed Jun 8 13:37:05 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 08 Jun 2011 21:37:05 +1000 Subject: [Tutor] Copying a mutable In-Reply-To: References: <4DEEDC34.90206@ieee.org> Message-ID: <4DEF5EE1.2080203@pearwood.info> V?las P?ter wrote: > Being one of the purposes of Python to be a simple educational language, I > want to make this simple to a beginner who does care. :-) > Here is a piece of code, Python 3.1.2, a small game with a list and a tuple: >>>> li=[3,4] >>>> id(li) > 13711200 >>>> la=li >>>> id(la) > 13711200 You can make it simpler by ignoring id() and using the `is` operator instead. `is` is equivalent to this function: def my_is(a, b): return id(a) == id(b) Of course you don't need to use that, instead do this: >>> a = [1, 2, 3] >>> b = a >>> a is b True > My question is: how would you explain the different behaviour of a list and > a tuple for a beginner? Lists are mutable, which means you can change them in-place. The *= command changes the list in place: >>> a = [1, 2] >>> b = a >>> b *= 2 >>> a is b True >>> b [1, 2, 1, 2] Since you have changed the list object itself, both a and b see the same change. Naturally, since a and b are nothing but two different names for the same object. But tuples are immutable, which means you *cannot* change then in-place. Since *= cannot change the tuple in-place, it has to create a new tuple and assign it to the name on the left hand side: >>> c = (1, 2) >>> d = c >>> c is d True >>> d *= 2 >>> d (1, 2, 1, 2) c remains a name for the first tuple, and d is now a name for the new, expanded tuple: >>> c (1, 2) >>> c is d False [...] > Just to precisely understand English words, because this is a foreign > language for me. As far as I understand, assignment means giving a value to > a variable which is the expression used by classical languages that have > variables (such as Pascal or Basic). Python has no variables, since even the > simpliest data is an object, but we still say assignment, because it is > comfortable. > In this sense, if I say, "assignment" is a subset of "binding", is it > correct? I don't think so. They are definitely related, though, assignment in the Pascal or C sense is *like* name binding in the Python or Java sense, but they are not strictly subset/superset of each other. If one was a subset of the other, then you could write down every fact about name binding: Name binding is: 1. blah blah blah... 2. ... 3. ... 999. ... and then every fact about assignment: Assignment is: 1. blah blah blah... 2. ... 3. ... 777. ... and every fact about assignment would also be a fact about name binding. But that's not the case. -- Steven From ajarncolin at gmail.com Wed Jun 8 14:40:13 2011 From: ajarncolin at gmail.com (col speed) Date: Wed, 8 Jun 2011 19:40:13 +0700 Subject: [Tutor] Copying a mutable In-Reply-To: <1a7d7475.121f5.1306ccb8524.Coremail.nathan2012@163.com> References: <1a7d7475.121f5.1306ccb8524.Coremail.nathan2012@163.com> Message-ID: I think this is easily seen by a for loop: for something in range(20): print something In the above "something" is a variable, in this case an int(which is immutable). However, "something" is changed every time it goes through the loop. It's the equivalent of: x = 0 x = 1 x = 2 and so on Just because an int is immutable, doesn't mean that you can't change the "variable" that refers to it. Hope that helps -- -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Wed Jun 8 14:50:33 2011 From: wprins at gmail.com (Walter Prins) Date: Wed, 8 Jun 2011 13:50:33 +0100 Subject: [Tutor] Copying a mutable In-Reply-To: References: <4DEEDC34.90206@ieee.org> Message-ID: 2011/6/8 V?las P?ter > As far as I understand, assignment means giving a value to a variable which > is the expression used by classical languages that have variables (such as > Pascal or Basic). Python has no variables, since even the simpliest data is > an object, but we still say assignment, because it is comfortable. > I'd submit that conceptually Python has variables, but the way it implements it is simply slightly different from some other languages. So conceptually talking about assignment is quite appropriate even if as an implementation detail it's slightly different to some other languages (due to being object oriented and due to design choices made in the langugae.) I'd further submit that from a conceptual point of view assignments mostly work as expected, for example consider this exchange: ActivePython 2.5.2.2 (ActiveState Software Inc.) based on Python 2.5.2 (r252:60911, Mar 27 2008, 17:57:18) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> a = [1,2,3] >>> b = [1,2,3] >>> a == b True >>> id(a) 14423144 >>> id(b) 14425384 >>> a = (1,2,3) >>> b = (1,2,3) >>> id(a) 10877368 >>> id(b) 14312952 >>> a is b False >>> a == b True >>> Note, the lists are 2 seperate objects, but contain the same values. From a newbies point of view they look to be the same. Now, from an *identity* (id) point of view they're actually not the same, however usually that's a detail that you can ignore, and furthermore you'll normally use an equality check to see if they're "the same", so when a newbie that checks them for equality (using ==) he/she will get the expected result, e.g. that they're equal (despite not being the same object). In other words, the fact that they're different objects are actually irrelevant in this case. The same goes for the tuple as shown. In some sense, this is atually no different from a normal pascal/C variable, where e.g. one int will have a seperate identity (address in memory heap or on the stack) from another int, and when comparing them it would be implicitly understood that the machine would be reading the value from the one address and comparing it to the value at the other address and returning the result of the value comparison. The identities (pointers/memory addresses) are then conceptually irrelevant. So, I submit that the implications and effects of some types being mutable and others being immutable and the fact that they're implemented via objects need not lead to confusion or complication to basic notions of assignment in Python. Conceptually you have variables, and you can assign values to them. Everything else is details. HTH, Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From nitinchandra1 at gmail.com Wed Jun 8 17:20:12 2011 From: nitinchandra1 at gmail.com (nitin chandra) Date: Wed, 8 Jun 2011 20:50:12 +0530 Subject: [Tutor] lxml.html Message-ID: Hello Every One, doc = lxml.html.parse('/home/dev/wsgi-scripts/index.py').getroot() name = doc.forms[0].fields['name'] html = 'name is ' html += name ERROR [Wed Jun 08 20:29:51 2011] [error] [client 192.168.1.9] Traceback (most recent call last): [Wed Jun 08 20:29:51 2011] [error] [client 192.168.1.9] File "/home/dev/wsgi-scripts/response.py", line 33, in application [Wed Jun 08 20:29:51 2011] [error] [client 192.168.1.9] return handler.do(environ, start_response) [Wed Jun 08 20:29:51 2011] [error] [client 192.168.1.9] File "/home/dev/wsgi-scripts/response.py", line 15, in do [Wed Jun 08 20:29:51 2011] [error] [client 192.168.1.9] html += name [Wed Jun 08 20:29:51 2011] [error] [client 192.168.1.9] TypeError: cannot concatenate 'str' and 'NoneType' objects I am extracting form field name / value from an html, but then it gives the above error and does not display the value of the variable 'name' entered in the respective form. Thank Nitin From steve at pearwood.info Wed Jun 8 17:36:44 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 09 Jun 2011 01:36:44 +1000 Subject: [Tutor] lxml.html In-Reply-To: References: Message-ID: <4DEF970C.4060800@pearwood.info> nitin chandra wrote: > Hello Every One, > > doc = lxml.html.parse('/home/dev/wsgi-scripts/index.py').getroot() > name = doc.forms[0].fields['name'] > > html = 'name is ' > html += name > > ERROR > [Wed Jun 08 20:29:51 2011] [error] [client 192.168.1.9] Traceback > (most recent call last): What is all this extraneous date/error/ip address nonsense in the traceback? Where does it come from? > TypeError: > cannot concatenate 'str' and 'NoneType' objects > I am extracting form field name / value from an html, but then it > gives the above error and does > not display the value of the variable 'name' entered in the respective form. What is the value of the variable 'name'? Hint: read the error message that you get when you try to concatenate a string with the None object: >>> "spam" + None Traceback (most recent call last): File "", line 1, in TypeError: cannot concatenate 'str' and 'NoneType' objects -- Steven From malaclypse2 at gmail.com Wed Jun 8 17:49:05 2011 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 8 Jun 2011 11:49:05 -0400 Subject: [Tutor] lxml.html In-Reply-To: References: Message-ID: On Wed, Jun 8, 2011 at 11:20 AM, nitin chandra wrote: > Hello Every One, > > ? ? ? ? doc = lxml.html.parse('/home/dev/wsgi-scripts/index.py').getroot() Is index.py really an XML document? If so, it's named pretty oddly... -- Jerry From joel.goldstick at gmail.com Wed Jun 8 18:51:51 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 8 Jun 2011 12:51:51 -0400 Subject: [Tutor] lxml.html In-Reply-To: References: Message-ID: On Wed, Jun 8, 2011 at 11:49 AM, Jerry Hill wrote: > On Wed, Jun 8, 2011 at 11:20 AM, nitin chandra > wrote: > > Hello Every One, > > > > doc = > lxml.html.parse('/home/dev/wsgi-scripts/index.py').getroot() > > Is index.py really an XML document? If so, it's named pretty oddly... > > -- > Jerry > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Can you display the source code of your html file you are trying to process? -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From vincentbalmori at yahoo.com Wed Jun 8 21:25:52 2011 From: vincentbalmori at yahoo.com (Vincent Balmori) Date: Wed, 8 Jun 2011 12:25:52 -0700 (PDT) Subject: [Tutor] Q Message-ID: <672348.23483.qm@web59410.mail.ac4.yahoo.com> For the Absolute Beginner 3rd Edition book, I am having trouble with another question, which says "create a game where the computer picks a random word and the player must guess that word. The computer tells the player how many letters are in the word. Then the player gets 5 chances to ask if a letter is in the word. The computer can only respond with 'yes' or 'no'. The player must then guess the word." In the "Loop of Game" section of my code for some reason it gives me five more chances than I wanted it to. When I put two as the chance limit, it allowed seven. Also, the program will always say "yes" to any letter I enter, even if it's wrong. #Word Guess import random Aquino # create a sequence of words to choose from WORDS = ("python", "jumble", "easy", "difficult", "answer", "xylophone") # pick one word randomly from the sequence word = random.choice(WORDS) # create a variable to use later to see if the guess is correct correct = word # Getting the letter count and selection lcount = len(correct) LETTERS = None if correct == "python": LETTERS = "python" elif correct == "jumble": LETTERS = "jumble" elif correct == "easy": LETTERS = "easy" elif correct == "difficult": LETTERS = "difficult" elif correct == "answer": LETTERS = "answer" elif correct == "xylophone": LETTERS = "xylophone" #Start Game print("\n\n This word has", lcount,"letters in it.") #Loop of Game chances = 0 while chances < 5: guess = input("Does the word have a: ") for letter in correct: if letter.lower() in LETTERS: print("\nYes") chances += 1 guess = input("\nDoes the word have a: ") else: print("\nNo") chances += 1 guess = input("\nDoes the word have a: ") print("\nYour chances are up!") theguess = input("What is your guess?: ") if theguess == correct: print("\n\nYou did it!") input("\n\nPress the Enter key to exit.") else: print("\n\nSorry the word is:", correct) print(("Try again!")) input("\n\nPress the Enter key to exit.") -------------- next part -------------- An HTML attachment was scrubbed... URL: From eizetov at gmail.com Wed Jun 8 22:10:39 2011 From: eizetov at gmail.com (eizetov at gmail.com) Date: Wed, 08 Jun 2011 20:10:39 +0000 Subject: [Tutor] String formatting question with 's'.format() Message-ID: <20cf3071cc4a258ca604a538ee06@google.com> I'm working through the 'Learn Python' book by Mark Lutz, in this example: >>> somelist = list('SPAM') >>> parts = somelist[0], somelist[-1], somelist[1:3] >>> 'first={0}, last={1}, middle={2}'.format(*parts) "first=S, last=M, middle=['P', 'A']" why do we need the '*' at 'parts'. I know we need it, because otherwise it gives an error: Traceback (most recent call last): File "", line 1, in 'first={0}, last={1}, middle={2}'.format(parts) IndexError: tuple index out of range Still, wouldn't python basically see 'parts' and insert the actual tuple instead of the variable 'parts'? How does the machine think? -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmchase.com Wed Jun 8 23:17:16 2011 From: ramit.prasad at jpmchase.com (Prasad, Ramit) Date: Wed, 8 Jun 2011 17:17:16 -0400 Subject: [Tutor] String formatting question with 's'.format() In-Reply-To: <20cf3071cc4a258ca604a538ee06@google.com> References: <20cf3071cc4a258ca604a538ee06@google.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2E34BA7F91@EMARC112VS01.exchad.jpmchase.net> From: tutor-bounces+ramit.prasad=jpmchase.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmchase.com at python.org] On Behalf Of eizetov at gmail.com Sent: Wednesday, June 08, 2011 3:11 PM To: tutor at python.org Subject: [Tutor] String formatting question with 's'.format() I'm working through the 'Learn Python' book by Mark Lutz, in this example: >>> somelist = list('SPAM') >>> parts = somelist[0], somelist[-1], somelist[1:3] >>> 'first={0}, last={1}, middle={2}'.format(*parts) "first=S, last=M, middle=['P', 'A']" why do we need the '*' at 'parts'. I know we need it, because otherwise it gives an error: Traceback (most recent call last): File "", line 1, in 'first={0}, last={1}, middle={2}'.format(parts) IndexError: tuple index out of range Still, wouldn't python basically see 'parts' and insert the actual tuple instead of the variable 'parts'? How does the machine think? ======================== When you use {0} and {1} and {2} it looks for 3 variables being passed into it format. Passing *parts tells Python that parts is NOT an argument but instead a list of arguments. *parts is equivalent to 3 variables where: Variable 1 = 'S' Variable 2 = 'M' Variable 3 = ['P', 'A'] The error you see when using parts instead of *parts is basically saying it is looking for 2 more arguments to be passed into the function so that it can replace it. Compare: >>> 'first={0}'.format(parts) "first=('S', 'M', ['P', 'A'])" >>> 'first={0}'.format(*parts) 'first=S' 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 eizetov at gmail.com Wed Jun 8 23:48:25 2011 From: eizetov at gmail.com (Evgeny Izetov) Date: Wed, 8 Jun 2011 17:48:25 -0400 Subject: [Tutor] String formatting question with 's'.format() In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2E34BA7F91@EMARC112VS01.exchad.jpmchase.net> References: <20cf3071cc4a258ca604a538ee06@google.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2E34BA7F91@EMARC112VS01.exchad.jpmchase.net> Message-ID: I see now, that example helps. Basically I use one asterisk to extract a list or a tuple and double asterisks for a dictionary, but I have to provide keys in case of a dictionary, like here: >>> template = '{motto}, {pork} and {food}' >>> a = dict(motto='spam', pork='ham', food='eggs') >>> template.format(**a) 'spam, ham and eggs' Thanks for clearing things up. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Jun 9 00:05:40 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 8 Jun 2011 23:05:40 +0100 Subject: [Tutor] Copying a mutable References: <4DEEDC34.90206@ieee.org> Message-ID: "V?las P?ter" wrote > > really care if the two names are bound to same object, or just to > > two > > objects that happen to have the same value. > Being one of the purposes of Python to be a simple educational > language, I > want to make this simple to a beginner who does care. :-) That's good. But the fundamental precursor to explaining it is to explain the concept of an object. Because everything in Python is an object. If you don;t explain the concept of an object the beginner will never understand the different behaviours. There is nothing unusual in this, other object oriented languages require the same fundamental comprehension of objects. (eg Smalltalk - alsdo a language developed to teach beginners - indeed children - about programming.) > My question is: how would you explain the different > behaviour of a list and a tuple for a beginner? By explaining what immutability means and that some objects are mutable (the objects are changed in place) and others are not (new objects of the same type but with different values are created) - and that's just how it is... Every language has some core concepts that need to be addressed early in the learning experience. (Like the idea of maxint in C and Pascal say...) Python's data model and concept of mutability is one such concept. > This is another point the beginner may be confused: > multiple assignments. Frankly I never use those with beginners. They are syntactic sugar and never needed. If a beginner comes across them somewhere then I explain them. But they are an idiom best picked up by osmosis IMHO. > As far as I understand, assignment means giving a value to > a variable which is the expression used by classical languages and in math where the terms originated. > variables (such as Pascal or Basic). Python has no variables, Python does have variables but the implementation model is different to languages like C and Pascal where they map to memory locations. But compared to Lisp and Smalltalk (both heavily used as teaching languages) Python is semantically very similar. > since even the simpliest data is an object, > but we still say assignment, Exactly, provided we have explained the concept of objects and that everything is an object, then assignment is simply the associating of a name with an object - a very simple and consistent concept for a true beginner. It's the folks who come with a load of mental baggage from other, memory mapped, languages that have the problems because they are trying to force Python's model onto their preconceived notions of variables. If you come from a clean slate with no previous knowledge Python's model is simple and consistent. > In this sense, if I say, "assignment" is a subset of "binding", No because binding has a specific meaning in relation to classes and object instances. Assignment in Python is a form of name association not binding. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Jun 9 00:21:06 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 8 Jun 2011 23:21:06 +0100 Subject: [Tutor] String formatting question with 's'.format() References: <20cf3071cc4a258ca604a538ee06@google.com> Message-ID: wrote >>>> 'first={0}, last={1}, middle={2}'.format(*parts) > "first=S, last=M, middle=['P', 'A']" > > why do we need the '*' at 'parts'. I know we need it, because > otherwise it > gives an error: The * tells Python to unpack parts and treat the contents as individual values. format is looking for 3 values. Without the * it sees one, a tuple and complains about insufficient values. If it did try to do the format you would wind up with something like: "first=(S,M,['P', 'A']) last=None, middle=None" Python can't tell automatiocally whether you want the tuple treated as a single value and youu just forgot the other two or if you want the tuple unpacked. The * says unpack this value. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From swiftone at swiftone.org Thu Jun 9 02:23:58 2011 From: swiftone at swiftone.org (Brett Ritter) Date: Wed, 8 Jun 2011 20:23:58 -0400 Subject: [Tutor] Q In-Reply-To: <672348.23483.qm@web59410.mail.ac4.yahoo.com> References: <672348.23483.qm@web59410.mail.ac4.yahoo.com> Message-ID: On Wed, Jun 8, 2011 at 3:25 PM, Vincent Balmori wrote: > In the "Loop of Game" section of my code for some reason it gives me five > more chances than I wanted it to. When I put two as the chance limit, it > allowed seven. Also, the program will always say "yes" to any letter I > enter, even if it's wrong. Let's take a look. I'll comment on a few parts that aren't the cause of your problems. > WORDS = ("python", "jumble", "easy", "difficult", "answer", "xylophone") > # pick one word randomly from the sequence > word = random.choice(WORDS) > # create a variable to use later to see if the guess is correct > correct = word I'm unclear on the purpose of this step. You never again use word, so why have correct and not just use word? > LETTERS = None > if correct == "python": > ?? ? ? ?LETTERS = "python" LETTERS always ends up == correct (and thus == word). Why not just use correct (or word)? > chances = 0 > while chances < 5: > ?? ?guess = input("Does the word have a: ") > ?? ?for letter in correct: You are looping over every letter in correct. Why? Don't you just want to loop over my 5 chances? > ?? ? ? ?if letter.lower() in LETTERS: Here's your other issue. What is letter? Based on your for loop, it's one of the letters in correct. What test do you actual intend to do here? Say it in english and the python code should be fairly obvious. > ?? ? ? ? ? ?print("\nYes") > ?? ? ? ? ? ?chances += 1 > ?? ? ? ? ? ?guess = input("\nDoes the word have a: ") > ?? ? ? ?else: > ?? ? ? ? ? ?print("\nNo") > ?? ? ? ? ? ?chances += 1 > ?? ? ? ? ? ?guess = input("\nDoes the word have a: ") Just as a tip you've got a lot of repetition here. If you move the "chances" line and "guess" line outside of the if/else, your program will be shorter and cleaner. > ?? ?print("\nYour chances are up!") You want this to occur when your chances are up, right? So why is it _inside_ the while loop? Your basic approach is fine, you just have some extra stuff going on unnecessarily and I'm guessing it's confused you as to your logic. Give it another shot and let us know how it goes. -- Brett Ritter / SwiftOne swiftone at swiftone.org From steve at pearwood.info Thu Jun 9 02:54:10 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 09 Jun 2011 10:54:10 +1000 Subject: [Tutor] lxml.html In-Reply-To: References: <4DEF970C.4060800@pearwood.info> Message-ID: <4DF019B2.1040200@pearwood.info> nitin chandra wrote to me off-list. I've taken the liberty of returning the conversation to the mailing list. > Hi, > >>> ERROR >>> [Wed Jun 08 20:29:51 2011] [error] [client 192.168.1.9] Traceback >>> (most recent call last): >> What is all this extraneous date/error/ip address nonsense in the traceback? >> Where does it come from? > > This error statement comes from Apache Error Logs. Python / WSGI / apache. In future, please strip that extraneous noise before posting, thank you. >>> TypeError: >>> cannot concatenate 'str' and 'NoneType' objects > >>> I am extracting form field name / value from an html, but then it >>> gives the above error and does >>> not display the value of the variable 'name' entered in the respective >>> form. >> What is the value of the variable 'name'? > > Value entered in the form is 'admin' I didn't ask what the value entered in the form is. Where does the form go? Where are you looking? Are you sure you're looking in the right place? You're looking at a file /home/dev/wsgi-scripts/index.py and trying to extract XML from that file. What's inside that file? >> Hint: read the error message that you get when you try to concatenate a >> string with the None object: >>>>> "spam" + None >> Traceback (most recent call last): >> File "", line 1, in >> TypeError: cannot concatenate 'str' and 'NoneType' objects > > > Did this.... gives the same error... now the question is how do i NOT > face the same error.? By making sure that the variable name actually contains a name. -- Steven From msg.ashwini at gmail.com Thu Jun 9 07:38:04 2011 From: msg.ashwini at gmail.com (Ashwini Oruganti) Date: Thu, 9 Jun 2011 11:08:04 +0530 Subject: [Tutor] Objects C++ vs Python Message-ID: I'm trying to learn Python, and know C++. I have a slight confusion regarding the meaning of "object" in python. Here's what I've concluded so far: When we say "object" in C++, it means an instance of a class. e.g. class x{.......}; x ob1; // here ob1 is an object. but, for; int x; // x is NOT an object, it is a *variable* while in python, from what i've understood so far, >>> x=5 implies that there's a memory allocation (called object) that holds the value 3, and "x" is the variable (or name) that is used to refer to it. Further, in python, *everything *is an object, while in C++, only*instances of a class * are called objects. So does the term *Object * change its meaning when we shift the context from C++ to python?? This is a little confusing, can someone clear it up?? -- Regards, Ashwini -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Thu Jun 9 08:01:53 2011 From: steve at alchemy.com (Steve Willoughby) Date: Wed, 08 Jun 2011 23:01:53 -0700 Subject: [Tutor] Objects C++ vs Python In-Reply-To: References: Message-ID: <4DF061D1.6050602@alchemy.com> On 08-Jun-11 22:38, Ashwini Oruganti wrote: > I'm trying to learn Python, and know C++. I have a slight confusion > regarding the meaning of "object" in python. Here's what I've concluded > so far: > > When we say "object" in C++, it means an instance of a class. > e.g. This is true in both Python and C++. > int x; // x is NOT an object, it is a *variable* You're confusing variables and the things they hold. x here is a variable which contains an "int" type value. Another variable might hold a pointer to an object. > while in python, from what i've understood so far, > >>> x=5 > implies that there's a memory allocation (called object) that holds the > value 3, and "x" is the variable (or name) that is used to refer to it. Maybe this will be more clear: The value 5 is an integer-class object. Full stop. Don't even go down the road of thinking of "memory allocation" (yet). It's an object floating around in Python's runtime somewhere. x is a name you gave to that object for now, so you can refer to it somehow. The big difference is that variable names in Python are really just names for objects (something like pointers/references in C++ but a lot easier to work with), while in C++ they refer to specific memory locations, which must be the right size for what you store into them. Since Python is just naming objects, there is no such problem. That has nothing to do with what an "object" means. > So does the term *Object * change its meaning when we shift the context > from C++ to python?? This is a little confusing, can someone clear it up?? Not really. I think your confusion was about variables. -- 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 msg.ashwini at gmail.com Thu Jun 9 08:33:36 2011 From: msg.ashwini at gmail.com (Ashwini Oruganti) Date: Thu, 9 Jun 2011 12:03:36 +0530 Subject: [Tutor] Objects C++ vs Python In-Reply-To: <4DF061D1.6050602@alchemy.com> References: <4DF061D1.6050602@alchemy.com> Message-ID: That clears it up to an extent. On Thu, Jun 9, 2011 at 11:31 AM, Steve Willoughby wrote: > The value 5 is an integer-class object. But now what is "Integer-class"? Isn't integer a data type? I mean there is no concept of "classes" in C, and yet in C, we can write int x = 5; Will "5", then be called an integer class object? What exactly is a class now? I thought is a collection of variables and (or) associated functions. Am I missing something here? -- Regards, Ashwini -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Thu Jun 9 09:42:45 2011 From: steve at alchemy.com (Steve Willoughby) Date: Thu, 09 Jun 2011 00:42:45 -0700 Subject: [Tutor] Objects C++ vs Python In-Reply-To: References: <4DF061D1.6050602@alchemy.com> Message-ID: <4DF07975.1010303@alchemy.com> On 08-Jun-11 23:33, Ashwini Oruganti wrote: > On Thu, Jun 9, 2011 at 11:31 AM, Steve Willoughby > wrote: > > The value 5 is an integer-class object. > > > But now what is "Integer-class"? Isn't integer a data type? I mean there > is no concept of "classes" in C, and yet in C, we can write In Python, everything is an object, so integers are objects. In C, integers are a fundamental data type. C doesn't have objects at all. Classes are data types, too, though, (the combination of a data representation and the set of behaviors that define what that data does in your program). > > int x = 5; > > Will "5", then be called an integer class object? In an object-oriented language, yes. In C, no, since it doesn't even have classes. > What exactly is a class now? I thought is a collection of variables and > (or) associated functions. Am I missing something here? But in an object oriented language such as Python, we have classes and objects, and integers are just another class of data objects. In this case, it's a very simple data structure with an associated set of methods to do things like add integers together, compare them with each other, etc. -- 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 Jun 9 10:48:44 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 9 Jun 2011 09:48:44 +0100 Subject: [Tutor] Objects C++ vs Python References: Message-ID: "Ashwini Oruganti" wrote > I'm trying to learn Python, and know C++. I have a slight confusion > regarding the meaning of "object" in python. Here's what I've > concluded so > far: > > When we say "object" in C++, it means an instance of a class. No, although its a common misconception. An object in OOP, in any language is the encapsulation of data and the operations that act on that data. It is first and foremost a conceptuial entity. It just so happens that the normal way of producing objects in C++ is by instantiating classes. [But you can create objects in C++ without (explicitly) instantiating a class, for example when passing arguments to functions/methods temporary objects are frequently created. Also when using templated classes there is no explicit class for a List or a List we are using an implied class produced by the template at compile/runtime.] > int x; // x is NOT an object, it is a *variable* C++ grew out of C so it has a lot of non OOP features. It is no surprise to find therefore that its primitive types are related to memory allocation and raw data rather than objects. > while in python, from what i've understood so far, >>>> x=5 > implies that there's a memory allocation (called object) that holds > the > value 3, and "x" is the variable (or name) that is used to refer to > it. There is an object created (the integer 5) that is associated with a name(x), yes. But forget about memory allocation because, depending on implementation, no new memory may be required. > Further, in python, *everything *is an object, while in C++, > only*instances of a class * are called objects. Yes, because thats how objects are created in C++, its one of the limitations of C++ as a hybrid OOP language. > So does the term *Object * change its meaning when we > shift the context from C++ to python?? This is a little confusing, No object is standard in OOP. It is a concept. It is the instantiated encapsulation of data and function. How it is created varies between language implementations. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From evosweet at hotmail.com Thu Jun 9 11:06:13 2011 From: evosweet at hotmail.com (Rayon) Date: Thu, 9 Jun 2011 05:06:13 -0400 Subject: [Tutor] telnet connection question Message-ID: HI All, Is there any way that I can use python telnetlib to connect to a telnet session. Send commands and get back data without closing the connection. I need the response to be faster and the login process is taking up too much time. I was thinking I could use a queue to pass in data but I am not sure how i would get it out. Regards Rayon -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Thu Jun 9 12:02:08 2011 From: wprins at gmail.com (Walter Prins) Date: Thu, 9 Jun 2011 11:02:08 +0100 Subject: [Tutor] Objects C++ vs Python In-Reply-To: References: Message-ID: On 9 June 2011 09:48, Alan Gauld wrote: > > So does the term *Object * change its meaning when we >> shift the context from C++ to python?? This is a little confusing, >> > > > No object is standard in OOP. It is a concept. It is the instantiated > encapsulation of data and function. How it is created varies between > language implementations. > I'd like to emphasise Alan's point, by adding/pointing out that it is perfectly possible to write e.g. Object Oriented code in e.g. a procedural language like C, which obviously doesn't support the notion of objects explicitly in the language, although then it's up to you to come up with conventions and infrastructure to support the concept of object orientation in your program. As examples, the X Window System was originally written in C but using object oriented principles, also GTK+ is an object oriented cross platform widget set written in C. It relies on a library called GObject for realisation of object orientation. See e.g. http://en.wikipedia.org/wiki/GObject Regards Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From msg.ashwini at gmail.com Thu Jun 9 13:03:35 2011 From: msg.ashwini at gmail.com (Ashwini Oruganti) Date: Thu, 9 Jun 2011 16:33:35 +0530 Subject: [Tutor] Objects C++ vs Python In-Reply-To: References: Message-ID: On Thu, Jun 9, 2011 at 2:18 PM, Alan Gauld wrote: C++ grew out of C so it has a lot of non OOP features. It is no > surprise to find therefore that its primitive types are related to > memory allocation and raw data rather than objects. > > No object is standard in OOP. It is a concept. It is the instantiated > encapsulation of data and function. How it is created varies between > language implementations. Well, that clears it up! I guess Python is a wider implementation of OOP, hence a wider use of objects. Thanks a lot. On Thu, Jun 9, 2011 at 3:32 PM, Walter Prins wrote: > Object Oriented code in e.g. a procedural language like C, which obviously > doesn't support the notion of objects explicitly in the language, although > then it's up to you to come up with conventions and infrastructure to > support the concept of object orientation in your program. Didn't know that! It's interesting that GObject is itself written in C, which is a procedural laguage.. -- Regards, Ashwini -------------- next part -------------- An HTML attachment was scrubbed... URL: From izzaddin.ruhulessin at gmail.com Thu Jun 9 15:53:25 2011 From: izzaddin.ruhulessin at gmail.com (Izz ad-Din Ruhulessin) Date: Thu, 9 Jun 2011 15:53:25 +0200 Subject: [Tutor] Objects C++ vs Python In-Reply-To: References: Message-ID: Compared to Python, I do not even consider C++ an object ori?nted language. 2011/6/9 Ashwini Oruganti > On Thu, Jun 9, 2011 at 2:18 PM, Alan Gauld wrote: > > C++ grew out of C so it has a lot of non OOP features. It is no >> surprise to find therefore that its primitive types are related to >> memory allocation and raw data rather than objects. >> > > > >> No object is standard in OOP. It is a concept. It is the instantiated >> encapsulation of data and function. How it is created varies between >> language implementations. >> > > > Well, that clears it up! I guess Python is a wider implementation of OOP, > hence a wider use of objects. Thanks a lot. > > > > > On Thu, Jun 9, 2011 at 3:32 PM, Walter Prins wrote: > > Object Oriented code in e.g. a procedural language like C, which obviously >> doesn't support the notion of objects explicitly in the language, although >> then it's up to you to come up with conventions and infrastructure to >> support the concept of object orientation in your program. > > > > Didn't know that! It's interesting that GObject is itself written in C, > which is a procedural laguage.. > > > > > -- > Regards, > Ashwini > > > _______________________________________________ > 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 nitinchandra1 at gmail.com Thu Jun 9 16:10:05 2011 From: nitinchandra1 at gmail.com (nitin chandra) Date: Thu, 9 Jun 2011 19:40:05 +0530 Subject: [Tutor] lxml.html In-Reply-To: <4DF019B2.1040200@pearwood.info> References: <4DEF970C.4060800@pearwood.info> <4DF019B2.1040200@pearwood.info> Message-ID: Sorry, did not realise , on clicking "Reply", I was mailing only to you. Thank you for pointing that out. Duly complied. >>>> TypeError: >>>> cannot concatenate 'str' and 'NoneType' objects >> >>>> I am extracting form field name / value from an html, but then it >>>> gives the above error and does >>>> not display the value of the variable 'name' entered in the respective >>>> form. >>> >>> What is the value of the variable 'name'? >> >> Value entered in the form is 'admin' > > I didn't ask what the value entered in the form is. Where does the form go? > Where are you looking? Are you sure you're looking in the right place? The following is the html code in index.py html = "C Informatics" html += "

Hospital Management & Information System


" html += '


' html += '


' html += '


' html += '

' html += '
' html += 'User Name :
' html += 'Password   :
' html += '' html += '
Highest Qualifications:' html += '
' html += '' html += '' html += '' html += "" > > You're looking at a file /home/dev/wsgi-scripts/index.py and trying to > extract XML from that file. What's inside that file? With lxml.html i am looking to extract 'name="variable" ' from it. Thank you Nitin From wprins at gmail.com Thu Jun 9 16:50:27 2011 From: wprins at gmail.com (Walter Prins) Date: Thu, 9 Jun 2011 15:50:27 +0100 Subject: [Tutor] lxml.html In-Reply-To: References: <4DEF970C.4060800@pearwood.info> <4DF019B2.1040200@pearwood.info> Message-ID: Hello Nitin, On 9 June 2011 15:10, nitin chandra wrote: > The following is the html code in index.py > > html = "C Informatics" > html += "

Hospital Management & Information > System


" > html += '


' > html += '


' > html += '


' > html += '

' > html += '
' > html += 'User Name :
' > html += 'Password   : name="paswd1">
' > html += '' > html += '
Highest Qualifications:' > html += '
' > html += '' > html += '' > html += '' > html += "" > > That's not HTML, that's python code that builds up HTML in a string. (As an aside, it does that in a rather inefficient way.) lxml.html is for parsing HTML, it's not meant for parsing "python that builds HTML". To belabor the point, lxml.html is meant for proper HTML, nothing else. Therefore, you should be feeding a text file (HTML file) into LXML, not a piece of python code that builds HTML. Where did you get that HTML? How did it get to be part of the python code above? Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From kb1pkl at aim.com Thu Jun 9 21:33:54 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Thu, 09 Jun 2011 15:33:54 -0400 Subject: [Tutor] Objects C++ vs Python In-Reply-To: References: Message-ID: <4DF12022.2040203@aim.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 06/09/2011 07:03 AM, Ashwini Oruganti wrote: > On Thu, Jun 9, 2011 at 3:32 PM, Walter Prins wrote: > >> Object Oriented code in e.g. a procedural language like C, which obviously >> doesn't support the notion of objects explicitly in the language, although >> then it's up to you to come up with conventions and infrastructure to >> support the concept of object orientation in your program. > > > > Didn't know that! It's interesting that GObject is itself written in C, > which is a procedural laguage.. > (The Python interpreter you're probably using is written in C too) Well, anything object-oriented will get executed on a processor, which is procedural, and stored in RAM, which is essentially just a giant array of numbers. It should come with no surprise that OO can be and is written in a procedural language. An object is just data+behaviour, take this snippet of C: struct address_book_entry { char *name; char *address; char *extra; }; void printPerson(struct address_book_entry d) { /* d is a pointer so we could modify it */ printf("%s, age %d\n", d.name, d.age); printf("Address: %s", d.address); } Encapsulate that, and you have yourself an object. OO isn't hard to do, even (single!) inheritance isn't too great of a challenge. It's getting things dynamic instead of static that's the biggest challenge. - -- Corey Richardson -----BEGIN PGP SIGNATURE----- Version: GnuPG v2.0.17 (GNU/Linux) iQEcBAEBAgAGBQJN8SAiAAoJEAFAbo/KNFvpi/oIAJfSwifBQzilopoZTS3gEggT 4ekhhW1ao8XOcmgEBSrCLL5rWwQeYDGF1USkdeSQSpUfqEb6g7ua3HuhvOimRGKs KQx7t5jhI3AvWKE/mXslXD4nCq+vRf0q4AvGngnnAByEeQfbeZPg3huLeo6/SzXn QLHAbKKhcHWAXwmbhx4EbTkTEgyQocVNkjYj8z9bMxRcW0IMcj+ePDsPs0IQUALO D2T4xwjb7QwDC1OgQoGbMwTEGWup2ULxAOpMpFVwgyz2BgY7rm1PkQ2NTJuYSGIE TYhQ4HtyevMfORjPyfvq/JJG+QYBXseucAev4PizQkCgxuA++6JF7/VHJDXJPVw= =LXLl -----END PGP SIGNATURE----- From compbiocancerresearcher at gmail.com Thu Jun 9 21:49:21 2011 From: compbiocancerresearcher at gmail.com (B G) Date: Thu, 9 Jun 2011 15:49:21 -0400 Subject: [Tutor] Syntax for Simplest Way to Execute One Python Program Over 1000's of Datasets Message-ID: I'm trying to analyze thousands of different cancer datasets and run the same python program on them. I use Windows XP, Python 2.7 and the IDLE interpreter. I already have the input files in a directory and I want to learn the syntax for the quickest way to execute the program over all these datasets. As an example,for the sample python program below, I don't want to have to go into the python program each time and change filename and countfile. A computer could do this much quicker than I ever could. Thanks in advance! * * import string filename = 'draft1.txt' countfile = 'draft1_output.txt' def add_word(counts, word): if counts.has_key(word): counts[word] += 1 else: counts[word] = 1 def get_word(item): word = '' item = item.strip(string.digits) item = item.lstrip(string.punctuation) item = item.rstrip(string.punctuation) word = item.lower() return word def count_words(text): text = ' '.join(text.split('--')) #replace '--' with a space items = text.split() #leaves in leading and trailing punctuation, #'--' not recognised by split() as a word separator counts = {} for item in items: word = get_word(item) if not word == '': add_word(counts, word) return counts infile = open(filename, 'r') text = infile.read() infile.close() counts = count_words(text) outfile = open(countfile, 'w') outfile.write("%-18s%s\n" %("Word", "Count")) outfile.write("=======================\n") counts_list = counts.items() counts_list.sort() for word in counts_list: outfile.write("%-18s%d\n" %(word[0], word[1])) outfile.close -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Thu Jun 9 22:07:34 2011 From: wprins at gmail.com (Walter Prins) Date: Thu, 9 Jun 2011 21:07:34 +0100 Subject: [Tutor] Syntax for Simplest Way to Execute One Python Program Over 1000's of Datasets In-Reply-To: References: Message-ID: On 9 June 2011 20:49, B G wrote: > I'm trying to analyze thousands of different cancer datasets and run the > same python program on them. I use Windows XP, Python 2.7 and the IDLE > interpreter. I already have the input files in a directory and I want to > learn the syntax for the quickest way to execute the program over all these > datasets. > > As an example,for the sample python program below, I don't want to have to > go into the python program each time and change filename and countfile. A > computer could do this much quicker than I ever could. Thanks in advance! > OK, so make a function of the current program logic for a single filename, and make the base filename a parameter to that function. Then write another function (or main program) that iterates over your directory tree and calls the processing function for each input file. See documentation for module os, specifically os.walk(). (See here: http://docs.python.org/library/os.html ) If that doesn't get you going then post back again. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From kb1pkl at aim.com Thu Jun 9 22:30:48 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Thu, 09 Jun 2011 16:30:48 -0400 Subject: [Tutor] Syntax for Simplest Way to Execute One Python Program Over 1000's of Datasets In-Reply-To: References: Message-ID: <4DF12D78.6010906@aim.com> On 06/09/2011 03:49 PM, B G wrote: > I'm trying to analyze thousands of different cancer datasets and run the > same python program on them. I use Windows XP, Python 2.7 and the IDLE > interpreter. I already have the input files in a directory and I want to > learn the syntax for the quickest way to execute the program over all these > datasets. > > As an example,for the sample python program below, I don't want to have to > go into the python program each time and change filename and countfile. A > computer could do this much quicker than I ever could. Thanks in advance! > I think os.listdir() would be better for you than os.walk(), as Walter suggested, but if you have a directory tree, walk is better. Your file code could be simplified a lot by using context managers, which for a file looks like this: with open(filename, mode) as f: f.write("Stuff!") f will automatically be closed and everything. Now for some code review! > > import string > > filename = 'draft1.txt' > countfile = 'draft1_output.txt' > > def add_word(counts, word): > if counts.has_key(word): > counts[word] += 1 > else: > counts[word] = 1 > See the notes on this later. > def get_word(item): > word = '' > item = item.strip(string.digits) > item = item.lstrip(string.punctuation) > item = item.rstrip(string.punctuation) > word = item.lower() > return word This whole function could be simplified to: return item.strip(string.digits + string.punctuation).lower() Note that foo.strip(bar) == foo.lstrip(bar).rstrip(bar) > > > def count_words(text): > text = ' '.join(text.split('--')) #replace '--' with a space How about text = text.replace('--', ' ') > items = text.split() #leaves in leading and trailing punctuation, > #'--' not recognised by split() as a word separator Or, items = text.split('--') You can specify the split string! You should read the docs on string methods: http://docs.python.org/library/stdtypes.html#string-methods > counts = {} > for item in items: > word = get_word(item) > if not word == '': That should be 'if word:', which just checks if it evaluates to True. Since the only string that evaluate to False is '', it makes the code shorter and more readable. > add_word(counts, word) > return counts A better way would be using a DefaultDict, like so: from collections import defaultdict [...] def count_words(text): counts = defaultdict(int) # Every key starts off at 0! items = text.split('--') for item in items: word = get_word(item) if word: counts[word] += 1 return counts Besides that things have a default value, a defaultdict is the same as any other dict. We pass 'int' as a parameter because defaultdict uses the parameter as a function for the default value. It works out because int() == 0. > > infile = open(filename, 'r') > text = infile.read() > infile.close() This could be: text = open(filename).read() When you're opening a file as 'r', the mode is optional! > > counts = count_words(text) > > outfile = open(countfile, 'w') > outfile.write("%-18s%s\n" %("Word", "Count")) > outfile.write("=======================\n") It may just be me, but I think outfile.write(('=' * 23) + '\n') looks better. > > counts_list = counts.items() > counts_list.sort() > for word in counts_list: > outfile.write("%-18s%d\n" %(word[0], word[1])) > > outfile.close Parenthesis are important! outfile.close is a method object, outfile.close() is a method call. Context managers make this easy, because you don't have to manually close things. Hope it helped, -- Corey Richardson From eire1130 at gmail.com Thu Jun 9 23:05:48 2011 From: eire1130 at gmail.com (James Reynolds) Date: Thu, 9 Jun 2011 17:05:48 -0400 Subject: [Tutor] Syntax for Simplest Way to Execute One Python Program Over 1000's of Datasets In-Reply-To: <4DF12D78.6010906@aim.com> References: <4DF12D78.6010906@aim.com> Message-ID: My advice would be to stay away from generic names, like: for item in items: do stuff with item For a couple of lines its ok, but when programs get large, your program will get confusing even to you as the author. Sometimes, it's best just to do "for all in listx: but I think that's rare. Usually, you know what the contents of a list are, and you know what the list is, so for example for assets in portfolio: do stuff with assets for loans in cdo: do stuff with loans for protein in gen_sequence: do stuff with protein. etc. The other piece of advice I would give you is, make it more object oriented. This should get you away from having to rename things, as you say, and use self referential path finding mechanisms, such as os.getcwd() (get current working directory) and use listdir as mentioned previously. On Thu, Jun 9, 2011 at 4:30 PM, Corey Richardson wrote: > On 06/09/2011 03:49 PM, B G wrote: > > I'm trying to analyze thousands of different cancer datasets and run the > > same python program on them. I use Windows XP, Python 2.7 and the IDLE > > interpreter. I already have the input files in a directory and I want to > > learn the syntax for the quickest way to execute the program over all > these > > datasets. > > > > As an example,for the sample python program below, I don't want to have > to > > go into the python program each time and change filename and countfile. > A > > computer could do this much quicker than I ever could. Thanks in > advance! > > > > I think os.listdir() would be better for you than os.walk(), as Walter > suggested, but if you have a directory tree, walk is better. Your file > code could be simplified a lot by using context managers, which for a > file looks like this: > > with open(filename, mode) as f: > f.write("Stuff!") > > f will automatically be closed and everything. > > Now for some code review! > > > > > import string > > > > filename = 'draft1.txt' > > countfile = 'draft1_output.txt' > > > > def add_word(counts, word): > > if counts.has_key(word): > > counts[word] += 1 > > else: > > counts[word] = 1 > > > > See the notes on this later. > > > def get_word(item): > > word = '' > > item = item.strip(string.digits) > > item = item.lstrip(string.punctuation) > > item = item.rstrip(string.punctuation) > > word = item.lower() > > return word > > This whole function could be simplified to: > > return item.strip(string.digits + string.punctuation).lower() > > Note that foo.strip(bar) == foo.lstrip(bar).rstrip(bar) > > > > > > > def count_words(text): > > text = ' '.join(text.split('--')) #replace '--' with a space > > How about > > text = text.replace('--', ' ') > > > items = text.split() #leaves in leading and trailing punctuation, > > #'--' not recognised by split() as a word > separator > > Or, items = text.split('--') > > You can specify the split string! You should read the docs on string > methods: > http://docs.python.org/library/stdtypes.html#string-methods > > > counts = {} > > for item in items: > > word = get_word(item) > > if not word == '': > > That should be 'if word:', which just checks if it evaluates to True. > Since the only string that evaluate to False is '', it makes the code > shorter and more readable. > > > add_word(counts, word) > > return counts > > A better way would be using a DefaultDict, like so: > > from collections import defaultdict > [...] > > def count_words(text): > counts = defaultdict(int) # Every key starts off at 0! > items = text.split('--') > for item in items: > word = get_word(item) > if word: > counts[word] += 1 > return counts > > > Besides that things have a default value, a defaultdict is the same as > any other dict. We pass 'int' as a parameter because defaultdict uses > the parameter as a function for the default value. It works out because > int() == 0. > > > > > infile = open(filename, 'r') > > text = infile.read() > > infile.close() > > This could be: > > text = open(filename).read() > > When you're opening a file as 'r', the mode is optional! > > > > > counts = count_words(text) > > > > outfile = open(countfile, 'w') > > outfile.write("%-18s%s\n" %("Word", "Count")) > > outfile.write("=======================\n") > > It may just be me, but I think > > outfile.write(('=' * 23) + '\n') > > looks better. > > > > > counts_list = counts.items() > > counts_list.sort() > > for word in counts_list: > > outfile.write("%-18s%d\n" %(word[0], word[1])) > > > > outfile.close > > Parenthesis are important! outfile.close is a method object, > outfile.close() is a method call. Context managers make this easy, > because you don't have to manually close things. > > Hope it helped, > -- > Corey Richardson > _______________________________________________ > 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 compbiocancerresearcher at gmail.com Fri Jun 10 01:26:56 2011 From: compbiocancerresearcher at gmail.com (B G) Date: Thu, 9 Jun 2011 19:26:56 -0400 Subject: [Tutor] Syntax for Simplest Way to Execute One Python Program Over 1000's of Datasets In-Reply-To: References: Message-ID: hmm, thanks for the help. So I kinda got it working, although from an efficiency perspective it leaves a lot to be desired. I managed to do the following: 1) Create a script that gives me a list of all the filenames in the folder: path = "...\\Leukemia_Project" i = 0 for (files) in os.walk(path): print(files) print("\n") i += 1 2) I manually copy and paste the resulting list from the IDLE interpreter into a .txt file 3) Open the .txt file in Excel, remove the few lines I don't need (ie single quotes, etc) 4) Write another python script to print the result from step 3 in a new txt file, where each filename has its own row (pretty easy to do b/c all separated by the tab in the original txt file) 5)Put a for loop around my original python script that takes as input each line from the result of step 4. As it stands it is painfully awkward, but it works and has already saved me a lot of aggravation... On Thu, Jun 9, 2011 at 4:07 PM, Walter Prins wrote: > > > On 9 June 2011 20:49, B G wrote: > >> I'm trying to analyze thousands of different cancer datasets and run the >> same python program on them. I use Windows XP, Python 2.7 and the IDLE >> interpreter. I already have the input files in a directory and I want to >> learn the syntax for the quickest way to execute the program over all these >> datasets. >> >> As an example,for the sample python program below, I don't want to have to >> go into the python program each time and change filename and countfile. A >> computer could do this much quicker than I ever could. Thanks in advance! >> > > OK, so make a function of the current program logic for a single filename, > and make the base filename a parameter to that function. Then write another > function (or main program) that iterates over your directory tree and calls > the processing function for each input file. See documentation for module > os, specifically os.walk(). (See here: > http://docs.python.org/library/os.html ) > > If that doesn't get you going then post back again. > > Walter > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Jun 10 01:45:47 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 10 Jun 2011 00:45:47 +0100 Subject: [Tutor] Objects C++ vs Python References: Message-ID: "Ashwini Oruganti" wrote > Didn't know that! It's interesting that GObject is itself written > in C, > which is a procedural laguage.. The original implementation of C++ was called cfront which was a preprocessor which converted C++ code into vanilla C ready for compilation. (Actually there was an earlier version but it wasn't generally available outside Bell Labs) OOP isn't really that mysterious, it's just a bunch of data structures. About the only thing you really need is the ability to create a grouped data structure and the ability to reference a function and then include that reference within your grouped data. Thats why you can get OOP versions of almost any language - even COBOL! Alan G. From alan.gauld at btinternet.com Fri Jun 10 01:53:11 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 10 Jun 2011 00:53:11 +0100 Subject: [Tutor] Syntax for Simplest Way to Execute One Python Program Over1000's of Datasets References: Message-ID: "B G" wrote > I'm trying to analyze thousands of different cancer datasets and run > the > same python program on them. I use Windows XP, Python 2.7 and the > IDLE > interpreter. First thing: Don;t use IODLE as your interpreter. IDLE is a development environment that should not be used for running code in "production" type environments. Python is the interoreter, use it directly. > I already have the input files in a directory and I want to > learn the syntax for the quickest way to execute the program over > all these > datasets. If the script take a filename as an input parameter you can likely do python myfile.py *.* from the OS command prompt. Or in MacOS or Windows select all the files in Explorer and drag them onto your script. I suspect most Linux desktops will allow the same. Or you could write a second python script that traverses the files in your folder and calls a function which contains your code (recall that a python file can be impoerted as a module into another python file...) Just some ideas, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From sulinet at postafiok.hu Fri Jun 10 09:16:08 2011 From: sulinet at postafiok.hu (=?ISO-8859-1?Q?V=E1las_P=E9ter?=) Date: Fri, 10 Jun 2011 09:16:08 +0200 Subject: [Tutor] Syntax for Simplest Way to Execute One Python Program Over 1000's of Datasets In-Reply-To: References: Message-ID: A few hints to make it more efficient: 2011/6/10 B G > 1) Create a script that gives me a list of all the filenames in the folder: > I managed to do the following: > path = "...\\Leukemia_Project" > Use / in path instead of \\, it will work in all environments, not just Windows. One of the advantages of Python is that most of its code is platform independent; it would be a pity to throw this benefit away, and you don't know where and for what purpose will you use your scripts later. i = 0 > What do you use i for? Is it necessary? > for (files) in os.walk(path): > print(files) > print("\n") > i += 1 > 2) I manually copy and paste the resulting list from the IDLE interpreter > into a .txt file > 3) Open the .txt file in Excel, remove the few lines I don't need (ie > single quotes, etc) > I would not do this unless it is much easier than programming it or I am forced to do so with a machine gun. :-) Instead of print and copy and paste and save, you should write the whole stuff into a file. Processing it in Excel may be worth if you cannot exactly specify the things you want to remove. If they are well specified, do it in Python. As far as i understand, you have a great amount of data, and this is what programming is for. :-) > 4) Write another python script to print the result from step 3 in a new txt > file, where each filename has its own row (pretty easy to do b/c all > separated by the tab in the original txt file) > Once you preprocessed the filelist, it can be aither another script or the same. It depends on whether you always run them together, or some of them is needed alone. As Alan wrote, IDLE is no interpreter. Personally, I find more comfortable to write my scripts in Notepad++ and run at command prompt, because IDLE does not provide line numbers :-((, and I suspect that it makes a great load for the computer (on my weak machine it often looses socket and won't start any more). 2011/6/10 Alan Gauld > If the script take a filename as an input parameter you can likely do > > python myfile.py *.* > > from the OS command prompt. > Using Windows you may omit python, too. myfile.py is enough for a well educated Windows. :-) P?ter -------------- next part -------------- An HTML attachment was scrubbed... URL: From vincentbalmori at yahoo.com Fri Jun 10 10:01:43 2011 From: vincentbalmori at yahoo.com (Vincent Balmori) Date: Fri, 10 Jun 2011 01:01:43 -0700 (PDT) Subject: [Tutor] Lists Message-ID: <512866.29728.qm@web59401.mail.ac4.yahoo.com> I'm stuck on two problems from the Absolute Beginners book. The first is simple. I am trying to print all the words in the list in random order without repeats, but it always shows None for some reason. #Program prints list of words in random order with no repeats import random #List of words list = ["first", "second", "third", "fourth","fifth"] #Randomize word order order = random.shuffle(list) #Print words in random order print(order) input("\n\nPress the Enter to exit") The other question is: "Improve the program by adding a choice that lets the user enter a name and get back a grandfather. You should still only use one list of son-father pairs. Make sure to include several generations in list so a match can be found." The only thing I have done is adding choice 5 with its basic elif block and adding another name in each of the three sequences in the list, but I am completely stuck otherwise. #User can enter name of male and name of his father will show #Allow user to add, replace, and delete son-father pairs. #Also have the user enter a name to get back a grandfather #Setting values sondad = {"Vincent": "Ramon": "Lolo","Jesus": "God": "Unknown", "Simba": "Mufasa": "Lion"} choice = None while choice != "0": print( """ Who's Your Daddy?! 0 - Quit 1 - Look Up Pair 2 - Add a Pair 3 - Replace a Pair 4 - Delete a Pair 5 - Look up a Grandfather """ ) choice = input("Choice: ") print() # exit if choice == "0": print("Good-bye.") # look up pair elif choice == "1": choice = input("Which pair do you want to look up?: ") if choice in sondad: dad = sondad[choice] print("\n", choice,"is son to:", dad) else: print("\nSorry, I don't know", choice) # add a father elif choice == "2": choice = input("Who is the son you want to add?: ") if choice not in sondad: dad = input("\nWho's the father?: ") sondad[choice] = dad print("\n", dad, "has been added.") else: print("\nThat pair already exists! Try replacing them.") # replace a father elif choice == "3": choice = input("Which son do you want to replace a father?: ") if choice in sondad: dad = input("Who's the father?: ") sondad[choice] = dad print("\n", choice, "has been replaced.") else: print("\nThey don't exist! Try adding them.") # delete a pair elif choice == "4": choice = input("Which pair do you want to delete?: ") if choice in sondad: del sondad[choice] print("\nOkay, I deleted", choice) else: print("\nI can't do that!", choice, "don't exist.") # look up grandfather: elif choice == "5": choice = input("Who's grandfather are you looking up?: ") if choice in sondad: dad = sondad[choice] print("\n", choice,"is grandson to:", dad) else: print("\nSorry, I don't know", choice) # some unknown choice else: print("\nSorry, but", choice, "isn't a valid choice.") input("\n\nPress the enter key to exit.") -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Fri Jun 10 12:25:34 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 10 Jun 2011 20:25:34 +1000 Subject: [Tutor] Lists In-Reply-To: <512866.29728.qm@web59401.mail.ac4.yahoo.com> References: <512866.29728.qm@web59401.mail.ac4.yahoo.com> Message-ID: <4DF1F11E.5030808@pearwood.info> Vincent Balmori wrote: > I'm stuck on two problems from the Absolute Beginners book. The first is simple. > I am trying to print all the words in the list in random order without repeats, > but it always shows None for some reason. > > #Program prints list of words in random order with no repeats > > import random > > #List of words > > list = ["first", "second", "third", "fourth","fifth"] > > #Randomize word order > > order = random.shuffle(list) shuffle() does not return a new list, it shuffles in place, and returns None. So order will always be assigned the value None. What you want is to make a copy of your word list, and shuffle that. words = ["first", "second", "third", "fourth","fifth"] shuffled = words[:] # make a copy using slice notation [:] random.shuffle(shuffled) > The other question is: "Improve the program by adding a choice that lets the > user enter a name and get back a grandfather. You should still only use one list > of son-father pairs. Make sure to include several generations in list so a match > can be found." The only thing I have done is adding choice 5 with its basic elif > block and adding another name in each of the three sequences in the list, but I > am completely stuck otherwise. > > #User can enter name of male and name of his father will show > #Allow user to add, replace, and delete son-father pairs. > #Also have the user enter a name to get back a grandfather > > #Setting values > sondad = {"Vincent": "Ramon": "Lolo","Jesus": "God": "Unknown", "Simba": > "Mufasa": "Lion"} That can't work, you will get a syntax error. Each pair of key:value must be separated by a comma, not a colon, and you can't have key:key:value. Since you can't do son:father:grandfather, you need another strategy. Fortunately there is a simple one: father is the son of grandfather. So your dict becomes: sondad = { "Vincent": "Ramon", "Ramon": "Lolo", "Hermes": "Zeus", "Apollo": "Zeus", "Zeus": "Cronus", "Cronus": "Uranus", "Jesus": "God the Demiurge, the false God", "God the Demiurge, the false God": "God the Monad, the One, The Absolute, Bythos, Aion teleos", "Simba": "Mufasa", "Mufasa": "Lion", "Bart Simpson": "Homer Simpson", "Homer Simpson": "Abe Simpson", } Try that and see how you go. -- Steven From steve at pearwood.info Fri Jun 10 12:53:14 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 10 Jun 2011 20:53:14 +1000 Subject: [Tutor] telnet connection question In-Reply-To: References: Message-ID: <4DF1F79A.20403@pearwood.info> Rayon wrote: > HI All, > > Is there any way that I can use python telnetlib to connect to a telnet > session. It would be a pretty rubbish telnet library if it didn't let you make telnet connections. I don't understand why you are asking this question, since you have successfully made connections and are complaining that they are too slow. > Send commands and get back data without closing the connection. It would be a pretty rubbish telnet library if you couldn't send telnet commands. What makes you think it might not? > I need the response to be faster and the login process is taking up too much > time. Then get a faster link. Seriously, this is a silly question. It's like saying "I need a longer piece of string". Okay, fine. How long would you like? Why is the piece you have too short? We can't answer those questions. How are you logging in? How much time are you talking about? How fast is your link? > I was thinking I could use a queue to pass in data but I am not sure how i > would get it out. What data do you need to pass in, and why do you think a queue will help you? -- Steven From sulinet at postafiok.hu Fri Jun 10 12:55:57 2011 From: sulinet at postafiok.hu (=?ISO-8859-1?Q?V=E1las_P=E9ter?=) Date: Fri, 10 Jun 2011 12:55:57 +0200 Subject: [Tutor] Syntax for Simplest Way to Execute One Python Program Over 1000's of Datasets In-Reply-To: References: Message-ID: 2011/6/10 B G > > path = "...\\Leukemia_Project" > i = 0 > for (files) in os.walk(path): > print(files) > print("\n") > i += 1 > Continuing my thoughts: I ran your loop, and got several tuples, each representing a directory. All the tuples have the same structure: 0th element is the name of the directory, followed by a list of subdirs (possibly empty) and a list of files (possibly empty). I find no reason to maipulate this by Excel. Try instead: def clean(f): any processing, removing here path = ".../Leukemia_Project" dirlists = [] for (files) in os.walk(path): print(files) dirlists.append(clean(files)) print("\n") Then go on with next step. You will enjoy your work more than with printing-marking-copying-pasting-saving-opening-processing-saving-reopening... -------------- next part -------------- An HTML attachment was scrubbed... URL: From Warrior at programmer.net Fri Jun 10 14:41:01 2011 From: Warrior at programmer.net (Kaustubh Pratap chand) Date: Fri, 10 Jun 2011 12:41:01 +0000 Subject: [Tutor] Excited about python Message-ID: <20110610124101.55700@gmx.com> Hello, I just joined this mailing list so that i can boost up my learning of python.I come from a C background so python looks a little strange to me but it is easier to learn then any other languages around.Yet,i have not been able to find any cool books on python for peoples who are already programmers.The ones which i found which i found were quite boring and exhaustive. Can you recommend a book for a person like me which comes with a C background and the book covers all essential algoithmic methods and examples? Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From Steve.Flynn at capita.co.uk Fri Jun 10 14:50:03 2011 From: Steve.Flynn at capita.co.uk (Flynn, Stephen (L & P - IT)) Date: Fri, 10 Jun 2011 13:50:03 +0100 Subject: [Tutor] Excited about python In-Reply-To: <20110610124101.55700@gmx.com> References: <20110610124101.55700@gmx.com> Message-ID: Python manuals from http://www.python.org/doc/ ________________________________ From: tutor-bounces+steve.flynn=capita.co.uk at python.org [mailto:tutor-bounces+steve.flynn=capita.co.uk at python.org] On Behalf Of Kaustubh Pratap chand Sent: Friday, June 10, 2011 1:41 PM To: tutor at python.org Subject: [Tutor] Excited about python Hello, I just joined this mailing list so that i can boost up my learning of python.I come from a C background so python looks a little strange to me but it is easier to learn then any other languages around.Yet,i have not been able to find any cool books on python for peoples who are already programmers.The ones which i found which i found were quite boring and exhaustive. Can you recommend a book for a person like me which comes with a C background and the book covers all essential algoithmic methods and examples? Thank you. This email has been scanned for all viruses by the MessageLabs SkyScan service. This email and any attachment to it are confidential. Unless you are the intended recipient, you may not use, copy or disclose either the message or any information contained in the message. If you are not the intended recipient, you should delete this email and notify the sender immediately. Any views or opinions expressed in this email are those of the sender only, unless otherwise stated. All copyright in any Capita material in this email is reserved. All emails, incoming and outgoing, may be recorded by Capita and monitored for legitimate business purposes. Capita exclude all liability for any loss or damage arising or resulting from the receipt, use or transmission of this email to the fullest extent permitted by law. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jonvspython at gmail.com Fri Jun 10 15:19:02 2011 From: jonvspython at gmail.com (jon vs. python) Date: Fri, 10 Jun 2011 15:19:02 +0200 Subject: [Tutor] Excited about python In-Reply-To: References: <20110610124101.55700@gmx.com> Message-ID: Dive into Python: http://diveintopython.org/ is what you're looking for. -------------- next part -------------- An HTML attachment was scrubbed... URL: From eire1130 at gmail.com Fri Jun 10 15:51:20 2011 From: eire1130 at gmail.com (James Reynolds) Date: Fri, 10 Jun 2011 09:51:20 -0400 Subject: [Tutor] Syntax for Simplest Way to Execute One Python Program Over 1000's of Datasets In-Reply-To: References: Message-ID: > > 3) Open the .txt file in Excel, remove the few lines I don't need (ie > single quotes, etc) Regarding Excel, you can write your output directly to an Excel file from python using the Python-Excel module. Just install all three packages. I use them all the time. Here is something that I wrote just yesterday which writes data to sheets one and three in an existing notebook. from xlrd import open_workbook > from xlutils.copy import copy > from xlwt import easyxf def insert_excel(self, exfile, insert_list): > book = open_workbook(exfile, formatting_info = True) > copy_book = copy(book) > copy_sheet = copy_book.get_sheet(0) > copy_sheet_two = copy_book.get_sheet(2) > plain = easyxf('') > allp = len(insert_list) > for row, listx in enumerate(insert_list): > listx = self.formater(listx) > print row +1, ' of ', allp > if len(listx) > 250: > first_list = listx[0:250] > second_list = listx[250:] > for i, cell in enumerate(first_list): > copy_sheet.write(row+2, i, cell, plain) > for i, cell in enumerate(second_list): > try: > copy_sheet_two.write(row+2, i, cell, plain) > except ValueError: > break > else: > for i, cell in enumerate(listx): > copy_sheet.write(row+2, i, cell, plain) > copy_book.save(exfile) -------------- next part -------------- An HTML attachment was scrubbed... URL: From msg.ashwini at gmail.com Fri Jun 10 15:53:08 2011 From: msg.ashwini at gmail.com (Ashwini Oruganti) Date: Fri, 10 Jun 2011 19:23:08 +0530 Subject: [Tutor] Excited about python In-Reply-To: <20110610124101.55700@gmx.com> References: <20110610124101.55700@gmx.com> Message-ID: You can also try "Learning Python" On Fri, Jun 10, 2011 at 6:11 PM, Kaustubh Pratap chand < Warrior at programmer.net> wrote: > Hello, > I just joined this mailing list so that i can boost up my learning of > python.I come from a C background so python looks a little strange to me but > it is easier to learn then any other languages around.Yet,i have not been > able to find any cool books on python for peoples who are already > programmers.The ones which i found which i found were quite boring and > exhaustive. > > Can you recommend a book for a person like me which comes with a C > background and the book covers all essential algoithmic methods and > examples? > > Thank you. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Regards, Ashwini -------------- next part -------------- An HTML attachment was scrubbed... URL: From patty at cruzio.com Fri Jun 10 16:21:38 2011 From: patty at cruzio.com (Patty) Date: Fri, 10 Jun 2011 07:21:38 -0700 Subject: [Tutor] Excited about python References: <20110610124101.55700@gmx.com> Message-ID: <402D7DB1DED84345A98C80E5377946EA@mycomputer> ----- Original Message ----- From: Kaustubh Pratap chand To: tutor at python.org Sent: Friday, June 10, 2011 5:41 AM Subject: [Tutor] Excited about python Hello, I just joined this mailing list so that i can boost up my learning of python.I come from a C background so python looks a little strange to me but it is easier to learn then any other languages around.Yet,i have not been able to find any cool books on python for peoples who are already programmers.The ones which i found which i found were quite boring and exhaustive. Can you recommend a book for a person like me which comes with a C background and the book covers all essential algoithmic methods and examples? Thank you. ------------------------------------------------------------------------------ _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Hello Kaustubh: I am also a C programmer and the first thing I read about Python was "A Quick, Painless Tutorial on the Python Language" by Prof. Norman Matloff of UC-Davis. Here is the link to his page -- I didn't realize he had created other tutorials regarding Python, and will have to look at those myself. http://heather.cs.ucdavis.edu/~matloff/python.html Here is the specific link to the tutorial I mentioned: http://heather.cs.ucdavis.edu/~matloff/Python/PythonIntro.pdf In addition, I wasn't satisfied after learning on my own and took an online course. I also like Beginning Python - From Novice to Professional by Magnus Hetland. I have other books as well, such as Python Programming for the Absolute Beginner by Michael Dawson, but I like Hetland's style more and have a book being shipped to me by Hetland called Python Algorithms. Good Luck Patty -------------- next part -------------- An HTML attachment was scrubbed... URL: From motoom at xs4all.nl Fri Jun 10 16:26:02 2011 From: motoom at xs4all.nl (Michiel Overtoom) Date: Fri, 10 Jun 2011 16:26:02 +0200 Subject: [Tutor] Excited about python In-Reply-To: References: <20110610124101.55700@gmx.com> Message-ID: On Jun 10, 2011, at 15:53, Ashwini Oruganti wrote: > You can also try "Learning Python" I also came from a C/C++ background, but I found the standard tutorial sufficient. http://docs.python.org/tutorial/ Greetings, > On Fri, Jun 10, 2011 at 6:11 PM, Kaustubh Pratap chand wrote: > Hello, > I just joined this mailing list so that i can boost up my learning of python.I come from a C background so python looks a little strange to me but it is easier to learn then any other languages around.Yet,i have not been able to find any cool books on python for peoples who are already programmers.The ones which i found which i found were quite boring and exhaustive. > > Can you recommend a book for a person like me which comes with a C background and the book covers all essential algoithmic methods and examples? > > Thank you. -- "Freedom: To ask nothing. To expect nothing. To depend on nothing." - Ayn Rand From Warrior at programmer.net Fri Jun 10 16:38:27 2011 From: Warrior at programmer.net (Kaustubh Pratap chand) Date: Fri, 10 Jun 2011 14:38:27 +0000 Subject: [Tutor] Excited about python Message-ID: <20110610143828.55700@gmx.com> Thanks I liked the tutorial very much. ----- Original Message ----- From: Patty Sent: 06/10/11 10:21 AM To: Kaustubh Pratap chand, tutor at python.org Subject: Re: [Tutor] Excited about python ----- Original Message ----- *From:* Warrior at programmer.net *To:* tutor at python.org *Sent:* Friday, June 10, 2011 5:41 AM *Subject:* [Tutor] Excited about python Hello, I just joined this mailing list so that i can boost up my learning of python.I come from a C background so python looks a little strange to me but it is easier to learn then any other languages around.Yet,i have not been able to find any cool books on python for peoples who are already programmers.The ones which i found which i found were quite boring and exhaustive. Can you recommend a book for a person like me which comes with a C background and the book covers all essential algoithmic methods and examples? Thank you. ----------------------------------------------------------------- _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Hello Kaustubh: I am also a C programmer and the first thing I read about Python was "A Quick, Painless Tutorial on the Python Language" by Prof. Norman Matloff of UC-Davis. Here is the link to his page -- I didn't realize he had created other tutorials regarding Python, and will have to look at those myself. http://heather.cs.ucdavis.edu/~matloff/python.html Here is the specific link to the tutorial I mentioned: http://heather.cs.ucdavis.edu/~matloff/Python/PythonIntro.pdf In addition, I wasn't satisfied after learning on my own and took an online course. I also like Beginning Python - From Novice to Professional by Magnus Hetland. I have other books as well, such as Python Programming for the Absolute Beginner by Michael Dawson, but I like Hetland's style more and have a book being shipped to me by Hetland called Python Algorithms. Good Luck Patty -------------- next part -------------- An HTML attachment was scrubbed... URL: From zebra05 at gmail.com Fri Jun 10 16:59:52 2011 From: zebra05 at gmail.com (Sithembewena Lloyd Dube) Date: Fri, 10 Jun 2011 16:59:52 +0200 Subject: [Tutor] Parsing an XML document using ElementTree In-Reply-To: References: Message-ID: Hi Stefan, Thanks for the code review :) Only just noticed this. On Wed, May 25, 2011 at 3:10 PM, Stefan Behnel wrote: > Sithembewena Lloyd Dube, 25.05.2011 14:40: > > Thanks for all your suggestions. I read up on gzip and urllib and also >> learned in the process that I could use urllib2 as its the latest form of >> that library. >> >> Herewith my solution: I don't know how elegant it is, but it works just >> fine. >> >> def get_contests(): >> url = ' >> >> http://xml.matchbook.com/xmlfeed/feed?sport-id=&vendor=TEST&sport-name=&short-name=Po >> ' >> req = urllib2.Request(url) >> req.add_header('accept-encoding','gzip/deflate') >> opener = urllib2.build_opener() >> response = opener.open(req) >> > > This is ok. > > > > compressed_data = response.read() >> compressed_stream = StringIO.StringIO(compressed_data) >> gzipper = gzip.GzipFile(fileobj=compressed_stream) >> data = gzipper.read() >> > > This should be simplifiable to > > uncompressed_stream = gzip.GzipFile(fileobj=response) > > > > current_path = os.path.realpath(MEDIA_ROOT + '/xml-files/d.xml') >> data_file = open(current_path, 'w') >> data_file.write(data) >> data_file.close() >> xml_data = ET.parse(open(current_path, 'r')) >> > > And this subsequently becomes > > xml_data = ET.parse(uncompressed_stream) > > > > contest_list = [] >> for contest_parent_node in xml_data.getiterator('contest'): >> > > Take a look at ET.iterparse(). > > > > contest = Contest() >> for contest_child_node in contest_parent_node: >> if (contest_child_node.tag == "name" and >> contest_child_node.text is not None and contest_child_node.text != ""): >> contest.name = contest_child_node.text >> if (contest_child_node.tag == "league" and >> contest_child_node.text is not None and contest_child_node.text != ""): >> contest.league = contest_child_node.text >> if (contest_child_node.tag == "acro" and >> contest_child_node.text is not None and contest_child_node.text != ""): >> contest.acro = contest_child_node.text >> if (contest_child_node.tag == "time" and >> contest_child_node.text is not None and contest_child_node.text != ""): >> contest.time = contest_child_node.text >> if (contest_child_node.tag == "home" and >> contest_child_node.text is not None and contest_child_node.text != ""): >> contest.home = contest_child_node.text >> if (contest_child_node.tag == "away" and >> contest_child_node.text is not None and contest_child_node.text != ""): >> contest.away = contest_child_node.text >> > > This is screaming for a simplification, such as > > for child in contest_parent_node: > if child.tag in ('name', 'league', ...): # etc. > if child.text: > setattr(context, child.tag, child.text) > > > > Stefan > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Regards, Sithembewena Lloyd Dube -------------- next part -------------- An HTML attachment was scrubbed... URL: From nikunjbadjatya at gmail.com Fri Jun 10 17:57:27 2011 From: nikunjbadjatya at gmail.com (Nikunj Badjatya) Date: Fri, 10 Jun 2011 21:27:27 +0530 Subject: [Tutor] Excited about python In-Reply-To: <20110610143828.55700@gmx.com> References: <20110610143828.55700@gmx.com> Message-ID: "a byte of python " from Swaroop CH. On Fri, Jun 10, 2011 at 8:08 PM, Kaustubh Pratap chand < Warrior at programmer.net> wrote: > > Thanks I liked the tutorial very much. > > > > ----- Original Message ----- > > From: Patty > > Sent: 06/10/11 10:21 AM > > To: Kaustubh Pratap chand, tutor at python.org > > Subject: Re: [Tutor] Excited about python > > > > ----- Original Message ----- > *From:* Kaustubh Pratap chand > *To:* tutor at python.org > *Sent:* Friday, June 10, 2011 5:41 AM > *Subject:* [Tutor] Excited about python > > Hello, > I just joined this mailing list so that i can boost up my learning of > python.I come from a C background so python looks a little strange to me but > it is easier to learn then any other languages around.Yet,i have not been > able to find any cool books on python for peoples who are already > programmers.The ones which i found which i found were quite boring and > exhaustive. > > Can you recommend a book for a person like me which comes with a C > background and the book covers all essential algoithmic methods and > examples? > > Thank you. > > > ------------------------------ > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Hello Kaustubh: > > I am also a C programmer and the first thing I read about Python was "A > Quick, Painless Tutorial on the Python Language" by Prof. Norman Matloff of > UC-Davis. > Here is the link to his page -- I didn't realize he had created other > tutorials regarding Python, and will have to look at those myself. > > http://heather.cs.ucdavis.edu/~matloff/python.html > > Here is the specific link to the tutorial I mentioned: > http://heather.cs.ucdavis.edu/~matloff/Python/PythonIntro.pdf > > In addition, I wasn't satisfied after learning on my own and took an > online course. > > I also like Beginning Python - From Novice to Professional by Magnus > Hetland. I have other books as well, such as Python Programming for the > Absolute Beginner by Michael Dawson, but I like Hetland's style more and > have a book being shipped to me by Hetland called Python Algorithms. > > Good Luck > > Patty > > > > > _______________________________________________ > 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 Fri Jun 10 18:16:26 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 10 Jun 2011 17:16:26 +0100 Subject: [Tutor] telnet connection question References: Message-ID: "Rayon" wrote > Is there any way that I can use python telnetlib to connect to a > telnet > session. > Send commands and get back data without closing the connection. Yes, thats what it's for. > I need the response to be faster and the login process is taking up > too much > time. Faster than what? Is it fast if you do it manually? The library can only talk to the same telnet server at the far end that your local telnet client talks to. If its a slow link or server then login (and most other things!) will be slow. What makes you think its the library at fault? If you are seeing big differences between manual and auto login then there might be an issue. In that case send us the timings for each method and the code you are using to login. (with login details obscured if necessary!) > I was thinking I could use a queue to pass in data > but I am not sure how i would get it out. Of course you can use a queue to pass in data, but that has nothing to do with telnet. As to getting it out. Out of what? The queue or the telnet session? We need more detail to be able to give specific answers. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From jeff at dcsoftware.com Fri Jun 10 19:13:37 2011 From: jeff at dcsoftware.com (Jeff Johnson) Date: Fri, 10 Jun 2011 10:13:37 -0700 Subject: [Tutor] Excited about python In-Reply-To: <20110610124101.55700@gmx.com> References: <20110610124101.55700@gmx.com> Message-ID: <4DF250C1.7000100@dcsoftware.com> On 06/10/2011 05:41 AM, Kaustubh Pratap chand wrote: > Hello, > I just joined this mailing list so that i can boost up my learning of > python.I come from a C background so python looks a little strange to > me but it is easier to learn then any other languages around.Yet,i > have not been able to find any cool books on python for peoples who > are already programmers.The ones which i found which i found were > quite boring and exhaustive. > > Can you recommend a book for a person like me which comes with a C > background and the book covers all essential algoithmic methods and > examples? > > Thank you. > > I found The Python Phrase Book extremely helpful because you can run the programs and this was the quickest way for me to learn. http://www.amazon.com/Python-Phrasebook-Brad-Dayley/dp/0672329107/ref=cm_cr_pr_product_top or http://tinyurl.com/3st9g54 Jeff ------------------- Jeff Johnson jeff at dcsoftware.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From cfuller084 at thinkingplanet.net Fri Jun 10 19:12:11 2011 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Fri, 10 Jun 2011 12:12:11 -0500 Subject: [Tutor] Excited about python In-Reply-To: <20110610124101.55700@gmx.com> References: <20110610124101.55700@gmx.com> Message-ID: <201106101212.13824.cfuller084@thinkingplanet.net> For a handy reference, you can't beat "Python Essential Reference" by David Beazley (along with the online documentation, of course!). I think this book is obligatory if you are going to be working with Python a lot. I own all four editions :) But you wanted something more in depth with algorithms, etc. The O'Reilly book "Programming Python" by Mark Lutz is a classic and is probably a good bet for you. Core Python by Wesley Chun is also good, and I've seen him on this list from time to time. Also, check out the Python wiki: http://wiki.python.org/moin/PythonBooks Cheers From python at bdurham.com Fri Jun 10 20:15:33 2011 From: python at bdurham.com (python at bdurham.com) Date: Fri, 10 Jun 2011 14:15:33 -0400 Subject: [Tutor] Excited about python In-Reply-To: <201106101212.13824.cfuller084@thinkingplanet.net> References: <20110610124101.55700@gmx.com> <201106101212.13824.cfuller084@thinkingplanet.net> Message-ID: <1307729733.25111.1461799605@webmail.messagingengine.com> > For a handy reference, you can't beat "Python Essential Reference" by David Beazley (along with the online documentation, of course!). I think this book is obligatory if you are going to be working with Python a lot. I own all four editions :) > But you wanted something more in depth with algorithms, etc. The O'Reilly book "Programming Python" by Mark Lutz is a classic and is probably a good bet for you. Core Python by Wesley Chun is also good, and I've seen him on this list from time to time. +1 on all of Chris's recommendations with a special +1 for Mark Lutz's book. Malcolm From sulinet at postafiok.hu Fri Jun 10 21:14:45 2011 From: sulinet at postafiok.hu (=?ISO-8859-1?Q?V=E1las_P=E9ter?=) Date: Fri, 10 Jun 2011 21:14:45 +0200 Subject: [Tutor] Syntax for Simplest Way to Execute One Python Program Over 1000's of Datasets In-Reply-To: References: Message-ID: 2011. j?nius 10. 15:51 James Reynolds ?rta, : > > Regarding Excel, you can write your output directly to an Excel file from > python using the Python-Excel module. Just install all three packages. I use > them all the time. > > > Do they work with Py3K? -------------- next part -------------- An HTML attachment was scrubbed... URL: From piotr-kam at o2.pl Fri Jun 10 21:12:26 2011 From: piotr-kam at o2.pl (=?utf-8?B?UGlvdHIgS2FtacWEc2tp?=) Date: Fri, 10 Jun 2011 21:12:26 +0200 Subject: [Tutor] Lists In-Reply-To: <4DF1F11E.5030808@pearwood.info> References: <512866.29728.qm@web59401.mail.ac4.yahoo.com> <4DF1F11E.5030808@pearwood.info> Message-ID: Dnia 10-06-2011 o 12:25:34 Steven D'Aprano napisa?(a): > Vincent Balmori wrote: >> I'm stuck on two problems from the Absolute Beginners book. The first >> is simple. I am trying to print all the words in the list in random >> order without repeats, but it always shows None for some reason. >> #Program prints list of words in random order with no repeats >> import random >> #List of words >> list = ["first", "second", "third", "fourth","fifth"] >> #Randomize word order >> order = random.shuffle(list) ... > > sondad = { > "Vincent": "Ramon", > "Ramon": "Lolo", > "Hermes": "Zeus", > "Apollo": "Zeus", > "Zeus": "Cronus", > "Cronus": "Uranus", > "Jesus": "God the Demiurge, the false God", > "God the Demiurge, the false God": > "God the Monad, the One, The Absolute, Bythos, Aion teleos", ... Could you please refrain from presenting your *religious* convictions in this list: the notions you believe in as well as the ones that you believe are false? This is a *technical* list, as I understand it, solely dedicated to the technical side of teaching the *Python* programming language and *programming* in general. I would like to keep it this way and I believe there are many persons or at least a number of people constituting a minority (or, likely, a silent majority) sharing my views in this respect. What is more, I am profoundly convinced that there are many other mailing lists and/or sites on the Internet, specifically dedicated to debating various religious, worldview and philosophical issues. --- As an aside, I have noticed that you tend to simply criticise Christianity as being unscientific and "false" and you do not bother to mention the religion or the philosophical or scientific belief system that you believe in. That seems to be quite a simplistic, unsophisticated form of ideological *intolerance* characteristic at best of a religious/philosophical zealot. As I have said I do not know the name of your belief system, however before you start to bash a belief system (and criticise it without giving any reason and without *constructively* suggesting your alternative), please first take due care to become familiar with e.g. Karl Popper's (http://en.wikipedia.org/wiki/Karl_Popper) views on: Marxism, Darwinism and Christianity. Notice that he gives reasons (the theory of *falsifiability*) why he thinks Marxist historical materialism and its idea of the progress of humanity is *unscientific*. That does not put the ideas of *"progressiveness"* of the New Left in a good light, does it? Especially when compared with Popper's views on Christianity. That must seem scary and blasphemous for leftists to distinguish the similarities between (Neo)marxism and Christianity... Thus that is why some philosophers see the varied (neo)marxist movements as denominations of the *non-traditional* Marxist *religion*, in a way similar to the diverse denominations of Christianity. The similarity between the two religions ends at this point, since their goals differ completely. A lot more can be said about them. I will not elaborate on the subject, as I realise that I am as likely to convince a leftist of Christianity's truthfulness (and vice versa, i.e. a Christian of leftism's truthfulness), as one is likely to convince a Muslim of Christianity's truthfulness (and vice versa, i.e. a Christian of Islam's truthfulness). Lastly, I believe that a young person looking for non-simplistic intellectual answers has to *consciously* discover them evaluating on his/her own the Christian, Marxist, etc. religions and/or ideologies. As to my person, I am a Christian and I also highly value, the few that exist, patriotic, politically independence-oriented representatives of anticommunist, antitotalitarian (i.e. the people that are against both the German *national* __socialism__ and the Soviet *international* __socialism__) Left who are not "useful idiots", easily indoctrinated by the Neosoviets and other totalitarian Left. That is my outlook on religious and ideological matters. I have wanted it to be known, so I have mentioned it *once* (Steven provoked my response). I do not intend to remind you repeatedly how I despise the genocidal totalitarian Left (e.g. that starved to death *5 - 6 million people* in Ukraine in 1932 - 1933 ( http://en.wikipedia.org/wiki/Holodomor )) or pseudo liberal leftist denominations. If I ever feel a need for that, I can easily find a dedicated Internet forum and express my views in this thematic scope. I am quite sure nobody needs my repeated ideological propaganda *in this mailing list*; let me know if I am wrong... One last thought, Steven, you might also find useful the section (of the Wikipedia article on Karl Popper) on the paradox of tolerance and on the subject of unlimited tolerance, as it seems particularly relevant to you in the light of your visible ideological intolerance. Piotr From piotr-kam at o2.pl Fri Jun 10 20:55:40 2011 From: piotr-kam at o2.pl (=?utf-8?B?UGlvdHIgS2FtacWEc2tp?=) Date: Fri, 10 Jun 2011 20:55:40 +0200 Subject: [Tutor] Excited about python In-Reply-To: <4DF250C1.7000100@dcsoftware.com> References: <20110610124101.55700@gmx.com> <4DF250C1.7000100@dcsoftware.com> Message-ID: Dnia 10-06-2011 o 19:13:37 Jeff Johnson napisa?(a): > I found The Python Phrase Book extremely helpful because you can run the > programs and this was the quickest way for me to learn. > > http://www.amazon.com/Python-Phrasebook-Brad-Dayley/dp/0672329107/ref=cm_cr_pr_product_top > > or > > http://tinyurl.com/3st9g54 > > > Jeff > > ------------------- > > Jeff Johnson > jeff at dcsoftware.com I too found it useful; it's got a lot of working code examples and shows well the use of the language's syntax and Python's most common applications e.g. string processing, working with databases, HTML and XML processing. For details, have look at the Table of Contents. Piotr From eire1130 at gmail.com Fri Jun 10 21:49:07 2011 From: eire1130 at gmail.com (James Reynolds) Date: Fri, 10 Jun 2011 15:49:07 -0400 Subject: [Tutor] Syntax for Simplest Way to Execute One Python Program Over 1000's of Datasets In-Reply-To: References: Message-ID: Honestly no idea. At work I use 2.6 / 2.7. At home it's 3.2 / 2.7. I've never actually tried doing this at home, so I don't know. They have a mail list though, I would post there to find out. 2011/6/10 V?las P?ter > > > 2011. j?nius 10. 15:51 James Reynolds ?rta, : > > >> Regarding Excel, you can write your output directly to an Excel file from >> python using the Python-Excel module. Just install all three packages. I use >> them all the time. >> >> >> Do they work with Py3K? > > > _______________________________________________ > 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 kb1pkl at aim.com Fri Jun 10 22:00:46 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Fri, 10 Jun 2011 16:00:46 -0400 Subject: [Tutor] Lists In-Reply-To: References: <512866.29728.qm@web59401.mail.ac4.yahoo.com> <4DF1F11E.5030808@pearwood.info> Message-ID: <4DF277EE.1060701@aim.com> On 06/10/2011 03:12 PM, Piotr Kami?ski wrote: > Could you please refrain from presenting your *religious* convictions > in this list: the notions you believe in as well as the ones that you > believe are false? > > This is a *technical* list, as I understand it, solely dedicated to > the technical side of teaching the *Python* programming language and > *programming* in general. I would like to keep it this way and I > believe there are many persons or at least a number of people > constituting a minority (or, likely, a silent majority) sharing my > views in this respect. > > What is more, I am profoundly convinced that there are many other > mailing lists and/or sites on the Internet, specifically dedicated to > debating various religious, worldview and philosophical issues. > You should have stopped here. Or, even better, just not written at all. It's the internet, does someone else's world religious really matter so much that you write a lengthy response to the whole list (which should be focused on python, as you mentioned)? > --- > > [...] > > That is my outlook on religious and ideological matters. I have > wanted it to be known, so I have mentioned it *once* (Steven provoked > my response). I do not intend to remind you repeatedly how I despise > the genocidal totalitarian Left (e.g. that starved to death *5 - 6 > million people* in Ukraine in 1932 - 1933 ( > http://en.wikipedia.org/wiki/Holodomor )) or pseudo liberal leftist > denominations. If I ever feel a need for that, I can easily find a > dedicated Internet forum and express my views in this thematic scope. > I am quite sure nobody needs my repeated ideological propaganda *in > this mailing list*; let me know if I am wrong... > A wise man once said, > Could you please refrain from presenting your *religious* convictions > in this list: the notions you believe in as well as the ones that you > believe are false? Could be applied to government too. -- Corey Richardson From jeremy.clark at ucr.edu Fri Jun 10 22:25:40 2011 From: jeremy.clark at ucr.edu (Jeremy G Clark) Date: Fri, 10 Jun 2011 20:25:40 +0000 Subject: [Tutor] if statement Message-ID: <343C0CEA73D3804F91FC1E9FCEC11D4916A1197F@EXCH-MBOX-1.exch.ucr.edu> Sorry, jumping in on this thread a couple days late... Steven's suggestion is how I figured out a similar problem recently. If you're executing the code through a windows command line, you might be getting the carriage-return character returned to the program (this behavior doesn't happen in IDLE). Remove it by using rstrip like so: password = input("Enter your password: ").rstrip('\r') Jeremy -------------- next part -------------- An HTML attachment was scrubbed... URL: From cyclicflux at yahoo.com Fri Jun 10 22:44:49 2011 From: cyclicflux at yahoo.com (Larry Flynton) Date: Fri, 10 Jun 2011 13:44:49 -0700 (PDT) Subject: [Tutor] Great List!!!mtutor@python.org Message-ID: <308495.10265.qm@web32505.mail.mud.yahoo.com> I just joined the list a little bit ago, and I must say while learning python it has proved to be a resource second to none. I myself am not from a traditional computer science background, more or less financial/economics, & discrete mathematics.? I have had courses on MySQL, Visual Basic, matlab,etc.... Plus, I do know more about computers than most people. But, I have began to program in python and learning the ropes, and playing around with IPython(which is def. great!!!). I was reading about creating functions/etc.... in one's library and I followed several examples in books(dive into python+python for Unix/Linux System Administration). But in general I wanted to do some data mining with resource retrieval from the internet. I found and have played with beautiful soup, scrapy, and urllib3.? I want to be able to retrieve the data and then put it in a MySQL(pyworkbench is what I have), and I was curious of perspectives to look at functions, to help build a multi-faceted library to undertake this task.? As well as a couple pointers on the ways one can import python to pyworkbench(I also have SQLAlchemy).? I have found the mailing list to be great, and have enjoyed the reading. However, as the books were insightful, and without a doubt helpful found this to be beyond their realm, and this list appeared to be the best resource. Thanks in advance!!! -------------- next part -------------- An HTML attachment was scrubbed... URL: From Warrior at programmer.net Fri Jun 10 22:57:23 2011 From: Warrior at programmer.net (Kaustubh Pratap chand) Date: Fri, 10 Jun 2011 20:57:23 +0000 Subject: [Tutor] Printing RAW string Message-ID: <20110610205724.89260@gmx.com> How i can print the string in raw...as it is s="hello world\n" print s Output: helloworld But i want it to be "hello world\n" I know it can be done by adding a 'r' prefix but is there any other way because the string will be taken in during input! Any help appreciated :D -------------- next part -------------- An HTML attachment was scrubbed... URL: From Warrior at programmer.net Fri Jun 10 22:59:11 2011 From: Warrior at programmer.net (Kaustubh Pratap chand) Date: Fri, 10 Jun 2011 20:59:11 +0000 Subject: [Tutor] Great List!!!mtutor@python.org Message-ID: <20110610205912.103940@gmx.com> Great place this is.....i am also new and i have started to love this place as it can help me in learning python fast ----- Original Message ----- From: Larry Flynton Sent: 06/10/11 04:44 PM To: tutor at python.org Subject: [Tutor] Great List!!!mtutor at python.org I just joined the list a little bit ago, and I must say while learning python it has proved to be a resource second to none. I myself am not from a traditional computer science background, more or less financial/economics, & discrete mathematics. I have had courses on MySQL, Visual Basic, matlab,etc.... Plus, I do know more about computers than most people. But, I have began to program in python and learning the ropes, and playing around with IPython(which is def. great!!!). I was reading about creating functions/etc.... in one's library and I followed several examples in books(dive into python+python for Unix/Linux System Administration). But in general I wanted to do some data mining with resource retrieval from the internet. I found and have played with beautiful soup, scrapy, and urllib3. I want to be able to retrieve the data and then put it in a MySQL(pyworkbench is what I have), and I was curious of perspectives to look at functions, to help build a multi-faceted library to undertake this task. As well as a couple pointers on the ways one can import python to pyworkbench(I also have SQLAlchemy). I have found the mailing list to be great, and have enjoyed the reading. However, as the books were insightful, and without a doubt helpful found this to be beyond their realm, and this list appeared to be the best resource. Thanks in advance!!! -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeremy.clark at ucr.edu Fri Jun 10 23:09:15 2011 From: jeremy.clark at ucr.edu (Jeremy G Clark) Date: Fri, 10 Jun 2011 21:09:15 +0000 Subject: [Tutor] Printing RAW string In-Reply-To: <20110610205724.89260@gmx.com> References: <20110610205724.89260@gmx.com> Message-ID: <343C0CEA73D3804F91FC1E9FCEC11D4916A119FA@EXCH-MBOX-1.exch.ucr.edu> print(repr(s)) _________________________________ How i can print the string in raw...as it is s="hello world\n" print s Output: helloworld But i want it to be "hello world\n" I know it can be done by adding a 'r' prefix but is there any other way because the string will be taken in during input! Any help appreciated :D -------------- next part -------------- An HTML attachment was scrubbed... URL: From piotr-kam at o2.pl Fri Jun 10 23:53:37 2011 From: piotr-kam at o2.pl (=?utf-8?B?UGlvdHIgS2FtacWEc2tp?=) Date: Fri, 10 Jun 2011 23:53:37 +0200 Subject: [Tutor] Lists In-Reply-To: <4DF277EE.1060701@aim.com> References: <512866.29728.qm@web59401.mail.ac4.yahoo.com> <4DF1F11E.5030808@pearwood.info> <4DF277EE.1060701@aim.com> Message-ID: Dnia 10-06-2011 o 22:00:46 Corey Richardson napisa?(a): > On 06/10/2011 03:12 PM, Piotr Kami?ski wrote: >> Could you please refrain from presenting your *religious* convictions >> in this list: the notions you believe in as well as the ones that you >> believe are false? >> >> This is a *technical* list, as I understand it, solely dedicated to >> the technical side of teaching the *Python* programming language and >> *programming* in general. I would like to keep it this way and I >> believe there are many persons or at least a number of people >> constituting a minority (or, likely, a silent majority) sharing my >> views in this respect. >> >> What is more, I am profoundly convinced that there are many other >> mailing lists and/or sites on the Internet, specifically dedicated to >> debating various religious, worldview and philosophical issues. >> > > You should have stopped here. Or, even better, just not written at all. > It's the internet, does someone else's world religious really matter so > much that you write a lengthy response to the whole list (which should > be focused on python, as you mentioned)? I know it's the Internet and I also use my right to express my opinions about somebody's short (or lengthy) views that I think of as *unfounded and offensive*. You obviously cannot imagine - living in a non-totalitarian, non-(post)communist country - that someone else's "world religious" really matters so much that one writes a lengthy response (is the property of being lengthy, a crime or too much of a burden on someone's (uninterested in religious, social and political philosophy and practice?) mind?). Please note that very short, catchy, one-sentence-long or so phrases *unsupported with* any thorough, *factual arguments* are commonly used to create groundless *impressions* in their receivers/consumers and, effectively, manipulate people into thinking and behaving in a way that a given person or a group of people want. For your information, such a piece of information creating some false impressions instead of giving true, supported with solid arguments information is technically known as a *factoid* ( http://en.wikipedia.org/wiki/Factoid ): "...The word is defined by the Compact Oxford English Dictionary as "an item of **unreliable information** that is **repeated so often** that it becomes **accepted as fact**". - the double stars were added by me. So you can see that a "good" factoid is almost never "lengthy" so that *most* people listening/watching to it get the point conveyed and do not get bored too quickly "or something"... I am aware of the above facts, so I am loudly protesting against Steven's verbal and conceptual behaviour. You don't have to agree with me. I realise that I use "big" words but that's something to get used to, if you want to talk precisely about the discussed matters. If you are a teenager or an adult uninterested in talking/reading about religion or politics, you can of course skip the thread or my posts. There is no obligation to read them and my intent was not to *unconditionally* close, or to demand doing so, Steven's or somebody else's mouth and not to talk about Christianity at all. I have said what I have had to say on this topic; I will not comment on the the thread any more. Good luck with learning and teaching Python and the basics of programming, everybody. > >> --- >> >> [...] >> >> That is my outlook on religious and ideological matters. I have >> wanted it to be known, so I have mentioned it *once* (Steven provoked >> my response). I do not intend to remind you repeatedly how I despise >> the genocidal totalitarian Left (e.g. that starved to death *5 - 6 >> million people* in Ukraine in 1932 - 1933 ( >> http://en.wikipedia.org/wiki/Holodomor )) or pseudo liberal leftist >> denominations. If I ever feel a need for that, I can easily find a >> dedicated Internet forum and express my views in this thematic scope. >> I am quite sure nobody needs my repeated ideological propaganda *in >> this mailing list*; let me know if I am wrong... >> > > A wise man once said, "A wise man" also once said "repeatedly". That strictly means more than once, and also exactly speaking: in different threads and on different dates... > >> Could you please refrain from presenting your *religious* convictions >> in this list: the notions you believe in as well as the ones that you >> believe are false? > > Could be applied to government too. From steve at pearwood.info Sat Jun 11 04:34:47 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 11 Jun 2011 12:34:47 +1000 Subject: [Tutor] Lists In-Reply-To: References: <512866.29728.qm@web59401.mail.ac4.yahoo.com> <4DF1F11E.5030808@pearwood.info> Message-ID: <4DF2D447.7030708@pearwood.info> Piotr Kami?ski wrote: > Could you please refrain from presenting your *religious* convictions in > this list: the notions you believe in as well as the ones that you believe > are false? > > This is a *technical* list, as I understand it, solely dedicated to the > technical side of teaching the *Python* programming language and > *programming* in general. I would like to keep it this way ... followed by FIFTY TWO lines of pseudo-philosophical waffling about his own religious beliefs. That's really funny. You made me laugh :) Piotr, I'm sorry that your religious faith is so fragile that it can't bear to be exposed to even the *existence* of contrary opinions, but that's not my problem. -- Steven From eizetov at gmail.com Sat Jun 11 06:56:08 2011 From: eizetov at gmail.com (eizetov at gmail.com) Date: Sat, 11 Jun 2011 04:56:08 +0000 Subject: [Tutor] Lists In-Reply-To: <4DF2D447.7030708@pearwood.info> Message-ID: Vincent, you should also try to avoid naming your lists a 'list'. There's a couple dozen words in Python that are reserved 'for system use': >>> import keyword >>> print(keyword.kwlist) ['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield'] 'List' is actually not listed here, however, using it as a variable name is still bad: >>> list('spam') ['s', 'p', 'a', 'm'] >>> list = '42' >>> list('spam') Traceback (most recent call last): File "", line 1, in list('spam') TypeError: 'str' object is not callable -------------- next part -------------- An HTML attachment was scrubbed... URL: From tommy at enkelthed.dk Sat Jun 11 13:34:49 2011 From: tommy at enkelthed.dk (Tommy Bell) Date: Sat, 11 Jun 2011 13:34:49 +0200 Subject: [Tutor] Building games Message-ID: <4DF352D9.3030200@enkelthed.dk> Hello I've been programming for a few years, mainly scripts and small applications that monitor folders and performs actions based on content of files and so on. I recently got the idea of trying to do a small game that is capable of illustrating some common problems in my field, now the game design is not the problem. I've done that, I've also gotten so far as to have windows and having some simple animations, like bouncing balls and things that react to key-presses. Now, regarding the title, building games, i need to be able to place buildings, like squares that is placed with the mouse and can be clicked and these kind of things. Can anyone recommend places to go or books to read? the books i've found so far are mostly about 2d-games like asteroids or something similar. Not quite what I was hoping, and pygame.org has alot of good sources, but outside of simply taking apart an existing game and looking at how they did it, are there any ressources to help me learn? I apologize if this is not the correct place to ask for this. Regards Tommy From piotr-kam at o2.pl Sat Jun 11 11:33:15 2011 From: piotr-kam at o2.pl (=?utf-8?B?UGlvdHIgS2FtacWEc2tp?=) Date: Sat, 11 Jun 2011 11:33:15 +0200 Subject: [Tutor] Lists In-Reply-To: <4DF2D447.7030708@pearwood.info> References: <512866.29728.qm@web59401.mail.ac4.yahoo.com> <4DF1F11E.5030808@pearwood.info> <4DF2D447.7030708@pearwood.info> Message-ID: Dnia 11-06-2011 o 04:34:47 Steven D'Aprano napisa?(a): > Piotr Kami?ski wrote: > >> Could you please refrain from presenting your *religious* convictions in >> this list: the notions you believe in as well as the ones that you >> believe >> are false? >> This is a *technical* list, as I understand it, solely dedicated to the >> technical side of teaching the *Python* programming language and >> *programming* in general. I would like to keep it this way ... > > followed by FIFTY TWO lines of pseudo-philosophical waffling about his > own religious beliefs. > > That's really funny. You made me laugh :) > > Piotr, I'm sorry that your religious faith is so fragile that it can't > bear to be exposed to even the *existence* of contrary opinions, but > that's not my problem. > "followed by FIFTY TWO lines of pseudo-philosophical waffling about his own religious beliefs.(...)" I guess then that according to this line of thought the mentioned articles on Karl Popper and the Great Hunger in Ukraine - and the arguments expressed there - are too my *exclusively own* religious beliefs... The statement on the nonscientificness of (Neo)marxism must have been terribly painful to you, that you've skipped it completely and escaped forwards into ridiculing me... I think it's better to use FIFTY TWO lines of my (and other persons') arguments than to use just TWO lines of "...pseudo-philosophical waffling about his own religious beliefs" making use of no arguments supporting them, just *negating* the belief system of Christianity. Surely, Steven, "(...)your religious faith is so fragile that it can't bear to be exposed to even the *existence* of contrary opinions(...)" *supported with arguments*, without you *simply ridiculing* the adversary's factual, historical evidence and arguments. Your inner anti-Christian leftist *bigotry* and *zeal* in ridiculing and simply *spitting on* the belief system and its followers, are not my problem. Instead, I wanted to signal the inappropriateness of your behaviour and I did it. That's it. I don't have the time and willingness to keep the conversation going in your style, i.e. ridiculing the *person* of the opponent, his *beliefs* and the *arguments in favour* of them. I guess I would be definitely more successful if I had called you with an f... word or told you - more or less in this way: your constant, simplistic adversarial style (arguing *often exclusively* for the sake of arguing) is offensive, however it is I that choose not to be offended. To be clear, I'm talking of the ways that your nasty and biassed against Christianity character has been dealt with recently in the general Python list. On having this *treatment* applied to you, you usually get silent for a day or two and start to speak in a much, much meeker, less arrogant, provocative and offensive way. I realise that you need a heavy verbal thrashing, not my "fragile, laughable" factual arguments presented in a *polite*, seemingly feeble way, you "brave and always right" Internet troll and a Christianity hater. Shortly put, I am not a boor or lout, therefore I like to write longer texts with factual arguments in them, not one- or two-sentence-long, *primitive* *negations*, i.e. statements of your imaginary, unsubstantiated in any way whatsoever ideological and *moral* superiority. Why don't you, for a change, start ridiculing the Jewish or the Islamic faiths... I reckon their responses won't be so "lengthy, fragile", polite and non-violent... Stop pushing around Christianity using it as your doormat and take off your anti-Christian horse blinkers.. And it is always worth repeating (and some of you may eagerly point out my comments on the use of the word "repeatedly", I'm fine with such criticism - I criticise, so I am prepared to being exposed to criticising, and the criticising itself) : "(...)Notice that he (Karl Popper) gives reasons (the theory of *falsifiability*) why he thinks Marxist historical materialism and its idea of the progress of humanity is *unscientific*. That does not put the ideas of *"progressiveness"* of the New Left in a good light, does it? Especially when compared with Popper's views on Christianity. That must seem scary and blasphemous for leftists to distinguish the similarities between (Neo)marxism and Christianity... Thus that is why some philosophers see the varied (neo)marxist movements as denominations of the *non-traditional* Marxist *religion*, in a way similar to the diverse denominations of Christianity.(...) " Bye (that is, as it originally meant in its full form: God be with you), a biassed follower of yet another religion, a religion pretending to be a branch of science. Piotr From piotr-kam at o2.pl Sat Jun 11 11:33:15 2011 From: piotr-kam at o2.pl (=?utf-8?B?UGlvdHIgS2FtacWEc2tp?=) Date: Sat, 11 Jun 2011 11:33:15 +0200 Subject: [Tutor] Lists In-Reply-To: <4DF2D447.7030708@pearwood.info> References: <512866.29728.qm@web59401.mail.ac4.yahoo.com> <4DF1F11E.5030808@pearwood.info> <4DF2D447.7030708@pearwood.info> Message-ID: Dnia 11-06-2011 o 04:34:47 Steven D'Aprano napisa?(a): > Piotr Kami?ski wrote: > >> Could you please refrain from presenting your *religious* convictions in >> this list: the notions you believe in as well as the ones that you >> believe >> are false? >> This is a *technical* list, as I understand it, solely dedicated to the >> technical side of teaching the *Python* programming language and >> *programming* in general. I would like to keep it this way ... > > followed by FIFTY TWO lines of pseudo-philosophical waffling about his > own religious beliefs. > > That's really funny. You made me laugh :) > > Piotr, I'm sorry that your religious faith is so fragile that it can't > bear to be exposed to even the *existence* of contrary opinions, but > that's not my problem. > "followed by FIFTY TWO lines of pseudo-philosophical waffling about his own religious beliefs.(...)" I guess then that according to this line of thought the mentioned articles on Karl Popper and the Great Hunger in Ukraine - and the arguments expressed there - are too my *exclusively own* religious beliefs... The statement on the nonscientificness of (Neo)marxism must have been terribly painful to you, that you've skipped it completely and escaped forwards into ridiculing me... I think it's better to use FIFTY TWO lines of my (and other persons') arguments than to use just TWO lines of "...pseudo-philosophical waffling about his own religious beliefs" making use of no arguments supporting them, just *negating* the belief system of Christianity. Surely, Steven, "(...)your religious faith is so fragile that it can't bear to be exposed to even the *existence* of contrary opinions(...)" *supported with arguments*, without you *simply ridiculing* the adversary's factual, historical evidence and arguments. Your inner anti-Christian leftist *bigotry* and *zeal* in ridiculing and simply *spitting on* the belief system and its followers, are not my problem. Instead, I wanted to signal the inappropriateness of your behaviour and I did it. That's it. I don't have the time and willingness to keep the conversation going in your style, i.e. ridiculing the *person* of the opponent, his *beliefs* and the *arguments in favour* of them. I guess I would be definitely more successful if I had called you with an f... word or told you - more or less in this way: your constant, simplistic adversarial style (arguing *often exclusively* for the sake of arguing) is offensive, however it is I that choose not to be offended. To be clear, I'm talking of the ways that your nasty and biassed against Christianity character has been dealt with recently in the general Python list. On having this *treatment* applied to you, you usually get silent for a day or two and start to speak in a much, much meeker, less arrogant, provocative and offensive way. I realise that you need a heavy verbal thrashing, not my "fragile, laughable" factual arguments presented in a *polite*, seemingly feeble way, you "brave and always right" Internet troll and a Christianity hater. Shortly put, I am not a boor or lout, therefore I like to write longer texts with factual arguments in them, not one- or two-sentence-long, *primitive* *negations*, i.e. statements of your imaginary, unsubstantiated in any way whatsoever ideological and *moral* superiority. Why don't you, for a change, start ridiculing the Jewish or the Islamic faiths... I reckon their responses won't be so "lengthy, fragile", polite and non-violent... Stop pushing around Christianity using it as your doormat and take off your anti-Christian horse blinkers.. And it is always worth repeating (and some of you may eagerly point out my comments on the use of the word "repeatedly", I'm fine with such criticism - I criticise, so I am prepared to being exposed to criticising, and the criticising itself) : "(...)Notice that he (Karl Popper) gives reasons (the theory of *falsifiability*) why he thinks Marxist historical materialism and its idea of the progress of humanity is *unscientific*. That does not put the ideas of *"progressiveness"* of the New Left in a good light, does it? Especially when compared with Popper's views on Christianity. That must seem scary and blasphemous for leftists to distinguish the similarities between (Neo)marxism and Christianity... Thus that is why some philosophers see the varied (neo)marxist movements as denominations of the *non-traditional* Marxist *religion*, in a way similar to the diverse denominations of Christianity.(...) " Bye (that is, as it originally meant in its full form: God be with you), a biassed follower of yet another religion, a religion pretending to be a branch of science. Piotr From piotr-kam at o2.pl Sat Jun 11 11:33:15 2011 From: piotr-kam at o2.pl (=?utf-8?B?UGlvdHIgS2FtacWEc2tp?=) Date: Sat, 11 Jun 2011 11:33:15 +0200 Subject: [Tutor] Lists In-Reply-To: <4DF2D447.7030708@pearwood.info> References: <512866.29728.qm@web59401.mail.ac4.yahoo.com> <4DF1F11E.5030808@pearwood.info> <4DF2D447.7030708@pearwood.info> Message-ID: Dnia 11-06-2011 o 04:34:47 Steven D'Aprano napisa?(a): > Piotr Kami?ski wrote: > >> Could you please refrain from presenting your *religious* convictions in >> this list: the notions you believe in as well as the ones that you >> believe >> are false? >> This is a *technical* list, as I understand it, solely dedicated to the >> technical side of teaching the *Python* programming language and >> *programming* in general. I would like to keep it this way ... > > followed by FIFTY TWO lines of pseudo-philosophical waffling about his > own religious beliefs. > > That's really funny. You made me laugh :) > > Piotr, I'm sorry that your religious faith is so fragile that it can't > bear to be exposed to even the *existence* of contrary opinions, but > that's not my problem. > "followed by FIFTY TWO lines of pseudo-philosophical waffling about his own religious beliefs.(...)" I guess then that according to this line of thought the mentioned articles on Karl Popper and the Great Hunger in Ukraine - and the arguments expressed there - are too my *exclusively own* religious beliefs... The statement on the nonscientificness of (Neo)marxism must have been terribly painful to you, that you've skipped it completely and escaped forwards into ridiculing me... I think it's better to use FIFTY TWO lines of my (and other persons') arguments than to use just TWO lines of "...pseudo-philosophical waffling about his own religious beliefs" making use of no arguments supporting them, just *negating* the belief system of Christianity. Surely, Steven, "(...)your religious faith is so fragile that it can't bear to be exposed to even the *existence* of contrary opinions(...)" *supported with arguments*, without you *simply ridiculing* the adversary's factual, historical evidence and arguments. Your inner anti-Christian leftist *bigotry* and *zeal* in ridiculing and simply *spitting on* the belief system and its followers, are not my problem. Instead, I wanted to signal the inappropriateness of your behaviour and I did it. That's it. I don't have the time and willingness to keep the conversation going in your style, i.e. ridiculing the *person* of the opponent, his *beliefs* and the *arguments in favour* of them. I guess I would be definitely more successful if I had called you with an f... word or told you - more or less in this way: your constant, simplistic adversarial style (arguing *often exclusively* for the sake of arguing) is offensive, however it is I that choose not to be offended. To be clear, I'm talking of the ways that your nasty and biassed against Christianity character has been dealt with recently in the general Python list. On having this *treatment* applied to you, you usually get silent for a day or two and start to speak in a much, much meeker, less arrogant, provocative and offensive way. I realise that you need a heavy verbal thrashing, not my "fragile, laughable" factual arguments presented in a *polite*, seemingly feeble way, you "brave and always right" Internet troll and a Christianity hater. Shortly put, I am not a boor or lout, therefore I like to write longer texts with factual arguments in them, not one- or two-sentence-long, *primitive* *negations*, i.e. statements of your imaginary, unsubstantiated in any way whatsoever ideological and *moral* superiority. Why don't you, for a change, start ridiculing the Jewish or the Islamic faiths... I reckon their responses won't be so "lengthy, fragile", polite and non-violent... Stop pushing around Christianity using it as your doormat and take off your anti-Christian horse blinkers.. And it is always worth repeating (and some of you may eagerly point out my comments on the use of the word "repeatedly", I'm fine with such criticism - I criticise, so I am prepared to being exposed to criticising, and the criticising itself) : "(...)Notice that he (Karl Popper) gives reasons (the theory of *falsifiability*) why he thinks Marxist historical materialism and its idea of the progress of humanity is *unscientific*. That does not put the ideas of *"progressiveness"* of the New Left in a good light, does it? Especially when compared with Popper's views on Christianity. That must seem scary and blasphemous for leftists to distinguish the similarities between (Neo)marxism and Christianity... Thus that is why some philosophers see the varied (neo)marxist movements as denominations of the *non-traditional* Marxist *religion*, in a way similar to the diverse denominations of Christianity.(...) " Bye (that is, as it originally meant in its full form: God be with you), a biassed follower of yet another religion, a religion pretending to be a branch of science. Piotr From piotr-kam at o2.pl Sat Jun 11 11:33:15 2011 From: piotr-kam at o2.pl (=?utf-8?B?UGlvdHIgS2FtacWEc2tp?=) Date: Sat, 11 Jun 2011 11:33:15 +0200 Subject: [Tutor] Lists In-Reply-To: <4DF2D447.7030708@pearwood.info> References: <512866.29728.qm@web59401.mail.ac4.yahoo.com> <4DF1F11E.5030808@pearwood.info> <4DF2D447.7030708@pearwood.info> Message-ID: Dnia 11-06-2011 o 04:34:47 Steven D'Aprano napisa?(a): > Piotr Kami?ski wrote: > >> Could you please refrain from presenting your *religious* convictions in >> this list: the notions you believe in as well as the ones that you believe >> are false? >> This is a *technical* list, as I understand it, solely dedicated to the >> technical side of teaching the *Python* programming language and >> *programming* in general. I would like to keep it this way ... > > followed by FIFTY TWO lines of pseudo-philosophical waffling about his own religious beliefs. > > That's really funny. You made me laugh :) > > Piotr, I'm sorry that your religious faith is so fragile that it can't bear to be exposed to even the *existence* of contrary opinions, but that's not my problem. > "followed by FIFTY TWO lines of pseudo-philosophical waffling about his own religious beliefs.(...)" I guess then that according to this line of thought the mentioned articles on Karl Popper and the Great Hunger in Ukraine - and the arguments expressed there - are too my *exclusively own* religious beliefs... The statement on the nonscientificness of (Neo)marxism must have been terribly painful to you, that you've skipped it completely and escaped forwards into ridiculing me... I think it's better to use FIFTY TWO lines of my (and other persons') arguments than to use just TWO lines of "...pseudo-philosophical waffling about his own religious beliefs" making use of no arguments supporting them, just *negating* the belief system of Christianity. Surely, Steven, "(...)your religious faith is so fragile that it can't bear to be exposed to even the *existence* of contrary opinions(...)" *supported with arguments*, without you *simply ridiculing* the adversary's factual, historical evidence and arguments. Your inner anti-Christian leftist *bigotry* and *zeal* in ridiculing and simply *spitting on* the belief system and its followers, are not my problem. Instead, I wanted to signal the inappropriateness of your behaviour and I did it. That's it. I don't have the time and willingness to keep the conversation going in your style, i.e. ridiculing the *person* of the opponent, his *beliefs* and the *arguments in favour* of them. I guess I would be definitely more successful if I had called you with an f... word or told you - more or less in this way: your constant, simplistic adversarial style (arguing *often exclusively* for the sake of arguing) is offensive, however it is I that choose not to be offended. To be clear, I'm talking of the ways that your nasty and biassed against Christianity character has been dealt with recently in the general Python list. On having this *treatment* applied to you, you usually get silent for a day or two and start to speak in a much, much meeker, less arrogant, provocative and offensive way. I realise that you need a heavy verbal thrashing, not my "fragile, laughable" factual arguments presented in a *polite*, seemingly feeble way, you "brave and always right" Internet troll and a Christianity hater. Shortly put, I am not a boor or lout, therefore I like to write longer texts with factual arguments in them, not one- or two-sentence-long, *primitive* *negations*, i.e. statements of your imaginary, unsubstantiated in any way whatsoever ideological and *moral* superiority. Why don't you, for a change, start ridiculing the Jewish or the Islamic faiths... I reckon their responses won't be so "lengthy, fragile", polite and non-violent... Stop pushing around Christianity using it as your doormat and take off your anti-Christian horse blinkers.. And it is always worth repeating (and some of you may eagerly point out my comments on the use of the word "repeatedly", I'm fine with such criticism - I criticise, so I am prepared to being exposed to criticising, and the criticising itself) : "(...)Notice that he (Karl Popper) gives reasons (the theory of *falsifiability*) why he thinks Marxist historical materialism and its idea of the progress of humanity is *unscientific*. That does not put the ideas of *"progressiveness"* of the New Left in a good light, does it? Especially when compared with Popper's views on Christianity. That must seem scary and blasphemous for leftists to distinguish the similarities between (Neo)marxism and Christianity... Thus that is why some philosophers see the varied (neo)marxist movements as denominations of the *non-traditional* Marxist *religion*, in a way similar to the diverse denominations of Christianity.(...) " Bye (that is, as it originally meant in its full form: God be with you), a biassed follower of yet another religion, a religion pretending to be a branch of science. Piotr From alan.gauld at btinternet.com Sat Jun 11 17:30:50 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 11 Jun 2011 16:30:50 +0100 Subject: [Tutor] Lists References: <512866.29728.qm@web59401.mail.ac4.yahoo.com><4DF1F11E.5030808@pearwood.info> <4DF2D447.7030708@pearwood.info> Message-ID: "Piotr Kami?ski" wrote >>> This is a *technical* list, as I understand it, solely dedicated >>> to the >>> technical side of teaching the *Python* programming language and >>> *programming* in general. I would like to keep it this way ... Since this seems to be something we can all agree on can we consider this discussion closed and get back to Python? If you wish to continue the philosophical debate please take it off list. Alan g. List moderator. From alan.gauld at btinternet.com Sat Jun 11 17:35:33 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 11 Jun 2011 16:35:33 +0100 Subject: [Tutor] Building games References: <4DF352D9.3030200@enkelthed.dk> Message-ID: "Tommy Bell" wrote > Now, regarding the title, building games, i need to be able to place > buildings, like squares that is placed with the mouse and can be > clicked and these kind of things. > > Can anyone recommend places to go or books to read? Not specifically for Python but there are many books on games programming in other languages. But it is an advanced and spacialist topic in its own right. Indeed there are entire undergraduate graduate degree level courses of 3 or 4 years duration on the subject. By all means have a go but be aware that writing a professional quality game is as much of a technical challenge as writing say, an operating system, or office application. But a general search for games programming titles should throw up some good resources: both books and web sites. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From piotr-kam at o2.pl Sat Jun 11 17:48:20 2011 From: piotr-kam at o2.pl (=?utf-8?B?UGlvdHIgS2FtacWEc2tp?=) Date: Sat, 11 Jun 2011 17:48:20 +0200 Subject: [Tutor] Lists In-Reply-To: <4DF37488.40209@online.de> References: <512866.29728.qm@web59401.mail.ac4.yahoo.com> <4DF1F11E.5030808@pearwood.info> <4DF2D447.7030708@pearwood.info> <4DF37488.40209@online.de> Message-ID: Hello, I've been told that some of you, or everybody got my e-mail four times. I'm sorry for the inconvenience. It seems there was a temporary failure of my piotr-kam[at]o2.pl mail account. I tried to send the e-mail three times, and each time got the "Undelivered Mail Returned to Sender" message. Eventually, I used the piotr.kaminski[at]poczta.onet.eu account and it got sent to the Tutor list. Piotr From piotr-kam at o2.pl Sat Jun 11 17:51:03 2011 From: piotr-kam at o2.pl (=?utf-8?B?UGlvdHIgS2FtacWEc2tp?=) Date: Sat, 11 Jun 2011 17:51:03 +0200 Subject: [Tutor] Lists In-Reply-To: References: <512866.29728.qm@web59401.mail.ac4.yahoo.com> <4DF1F11E.5030808@pearwood.info> <4DF2D447.7030708@pearwood.info> Message-ID: Dnia 11-06-2011 o 17:30:50 Alan Gauld napisa?(a): > "Piotr Kami?ski" wrote > >>>> This is a *technical* list, as I understand it, solely dedicated to >>>> the >>>> technical side of teaching the *Python* programming language and >>>> *programming* in general. I would like to keep it this way ... > > Since this seems to be something we can all agree on > can we consider this discussion closed and get back > to Python? > > If you wish to continue the philosophical debate please > take it off list. > > Alan g. > List moderator. OK. I like this style of talking - no feelings hurt, *including Christian ones as well*. Thank you. Piotr. From wolf.halton at gmail.com Sat Jun 11 18:32:24 2011 From: wolf.halton at gmail.com (Wolf Halton) Date: Sat, 11 Jun 2011 12:32:24 -0400 Subject: [Tutor] Building games In-Reply-To: <4DF352D9.3030200@enkelthed.dk> References: <4DF352D9.3030200@enkelthed.dk> Message-ID: I think pygame would let you do a simple graphical game. On Jun 11, 2011 7:54 AM, "Tommy Bell" wrote: > Hello > > I've been programming for a few years, mainly scripts and small > applications that monitor folders and performs actions based on content > of files and so on. > > I recently got the idea of trying to do a small game that is capable of > illustrating some common problems in my field, now the game design is > not the problem. I've done that, I've also gotten so far as to have > windows and having some simple animations, like bouncing balls and > things that react to key-presses. > > Now, regarding the title, building games, i need to be able to place > buildings, like squares that is placed with the mouse and can be clicked > and these kind of things. > > Can anyone recommend places to go or books to read? the books i've found > so far are mostly about 2d-games like asteroids or something similar. > Not quite what I was hoping, and pygame.org has alot of good sources, > but outside of simply taking apart an existing game and looking at how > they did it, are there any ressources to help me learn? > > I apologize if this is not the correct place to ask for this. > > Regards > Tommy > _______________________________________________ > 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 kb1pkl at aim.com Sat Jun 11 18:44:53 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Sat, 11 Jun 2011 12:44:53 -0400 Subject: [Tutor] Building games In-Reply-To: References: <4DF352D9.3030200@enkelthed.dk> Message-ID: <4DF39B85.9040809@aim.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 06/11/2011 12:32 PM, Wolf Halton wrote: > I think pygame would let you do a simple graphical game. > pygame can do plenty of complex graphics too. FWIW, you might have a better time using something like PySFML(2) or pyglet (I like pyglet much more than pygame, seems more pythonic) which wrap OpenGL instead of SDL, allowing for more stuff. Not to mention if you ever need a GUI there are a ton for OpenGL (even Qt, if you wanted). Of course, it's up to the OP. On 06/11/2011 07:34 AM, Tommy Bell wrote: > Now, regarding the title, building games, i need to be able to place > buildings, like squares that is placed with the mouse and can be > clicked and these kind of things. > In pygame/pyglet you'd want to be capturing mouse-click events and then acting on the location of the click, seeing if it's in the area of the square, etc.. Game programming is rather event-driven, similar to GUI programming. > Can anyone recommend places to go or books to read? the books i've > found so far are mostly about 2d-games like asteroids or something > similar. Not quite what I was hoping, and pygame.org has alot of good > sources, but outside of simply taking apart an existing game and > looking at how they did it, are there any ressources to help me > learn? The docs for pygame and pyglet are great, use them. Of course, reading the source of existing games is a great way to see how things are done, and is always a good learning experience. Cheers, - -- Corey Richardson -----BEGIN PGP SIGNATURE----- Version: GnuPG v2.0.17 (GNU/Linux) iQEcBAEBAgAGBQJN85uFAAoJEAFAbo/KNFvpaNoIAI0OeY7lnqdTR4AsdOdwZK0k HrZ5xuEaXVyO6UArYvVynoB6cZF+hNGiYmIiv2IO/aYLCjU0WWAvSLfLGD4zgWFR NnHdZvJ7SwfR4In4cYo2A6tkhNwHJpk2zSTgXqT07zDFvgCmyGGpTSjkHR6nWPdH jowbVm4i34K3ToPbIH1bl36+NG3OW5CynNRiOgz8bibjAtS+UrwvUFTojN3dsQ4O 9YfJ9OIXP0HMUQ71Gv4nBQFWKu6Q0qhXgTpF6JFtu9wbYiJWKj5oWNHyEdYm70Za zKeepAe9uNR2KZslQ6oB+AO2V2F2WoOoEARP6pBWmKg9lPNYCEt95HEYfe4a4MY= =ZH7D -----END PGP SIGNATURE----- From davidheiserca at gmail.com Sat Jun 11 19:02:09 2011 From: davidheiserca at gmail.com (davidheiserca at gmail.com) Date: Sat, 11 Jun 2011 10:02:09 -0700 Subject: [Tutor] STUPID telnet connection question References: <4DF1F79A.20403@pearwood.info> Message-ID: <01C1680B57B443A6A3893BC32AB6FBB0@dheiser> I think Steven and Alan misunderstood the Rayon's question. Rayon is using his telnet script to pass commands to a device ONE AT A TIME. Then he breaks the connection and reconnects for the next command.. He is asking how to open a telnet connection, pass MULTIPLE commands, then close the session. In my opinion, both of your responses border on rude. This mailing list is supposedly for beginners who often don't even know enough to formulate a clear question. If some of the more senior members ridicule the beginner's stupid questions, how will he or anyone else learn anything. If I were a shy beginning programmer, these responses would probably cause me to think twice before asking any stupid questions. Why put myself out there for ridicule? There are no stupid questions! There are only stupid teachers. ----- Original Message ----- From: "Steven D'Aprano" To: Sent: Friday, June 10, 2011 3:53 AM Subject: Re: [Tutor] telnet connection question > Rayon wrote: >> HI All, Is there any way that I can use python telnetlib to connect to a >> telnet >> session. > > It would be a pretty rubbish telnet library if it didn't let you make > telnet connections. > > I don't understand why you are asking this question, since you have > successfully made connections and are complaining that they are too slow. > > >> Send commands and get back data without closing the connection. > > It would be a pretty rubbish telnet library if you couldn't send telnet > commands. What makes you think it might not? > > >> I need the response to be faster and the login process is taking up too >> much >> time. > > Then get a faster link. > > Seriously, this is a silly question. It's like saying "I need a longer > piece of string". Okay, fine. How long would you like? Why is the piece > you have too short? We can't answer those questions. > > How are you logging in? How much time are you talking about? How fast is > your link? > > >> I was thinking I could use a queue to pass in data but I am not sure how >> i >> would get it out. > > What data do you need to pass in, and why do you think a queue will help > you? > > > > -- > Steven > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From steve at pearwood.info Sat Jun 11 20:52:15 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 12 Jun 2011 04:52:15 +1000 Subject: [Tutor] STUPID telnet connection question In-Reply-To: <01C1680B57B443A6A3893BC32AB6FBB0@dheiser> References: <4DF1F79A.20403@pearwood.info> <01C1680B57B443A6A3893BC32AB6FBB0@dheiser> Message-ID: <4DF3B95F.8000907@pearwood.info> davidheiserca at gmail.com wrote: > > I think Steven and Alan misunderstood the Rayon's question. > > Rayon is using his telnet script to pass commands to a device ONE AT A > TIME. Then he breaks the connection and reconnects for the next command.. > > He is asking how to open a telnet connection, pass MULTIPLE commands, > then close the session. Do you know this for a fact, or are you guessing? Perhaps you are right. To be honest, such an interpretation never even crossed my mind. I wouldn't have imagined that somebody who knows enough to get a telnet connection working *at all* would do this: login write(command) write(exit) login write(command) write(exit) login write(command) write(exit) instead of login write(command) write(command) write(command) write(exit) Or have I misunderstood what you are suggesting? > In my opinion, both of your responses border on rude. This mailing list > is supposedly for beginners who often don't even know enough to > formulate a clear question. If some of the more senior members ridicule > the beginner's stupid questions, how will he or anyone else learn anything. Perhaps our responses were a little brusque. But unlike others, we took the time to answer as best we could, and point Rayon towards the information we need to give a better answer. Would you rather that we just ignored him? What message does that send to Rayon? I for one would *much* prefer to be told to RTFM (or ask a better question) than to be ignored. > If I were a shy beginning programmer, these responses would probably > cause me to think twice before asking any stupid questions. Why put > myself out there for ridicule? Good! You should think twice before asking a stupid question! Don't just fire off the first incoherent question that pops into your head. Try your best to ask a good question: rudeness goes both ways. We are all volunteers, giving our time and experience for free. If people want our help, they should do their best to ask a clear question and not waste everybody's time with contradictory, unclear questions. People will forgive a lot if it is clear that you're making an effort. > There are no stupid questions! There are only stupid teachers. That is a thought-terminating clich?. Look it up on Wikipedia if you don't know what it means. Of course there are genuinely stupid questions. I've asked my share of them myself, and I'm sure I'll continue to doing so. Some stupid questions indicate ignorance, which can be fixed. Others indicate carelessness, laziness, or -- let's be honest to ourselves -- actual stupidity. Or a combination of all four. "Was it you or your brother who died in the war?", as the old joke goes. Or if you prefer a real example, I can hardly do better than to quote Charles Babbage: On two occasions I have been asked,?"Pray, Mr. Babbage, if you put into the machine wrong figures, will the right answers come out?" In one case a member of the Upper, and in the other a member of the Lower, House put this question. I am not able rightly to apprehend the kind of confusion of ideas that could provoke such a question. So please, no more with the cheesy platitude that there are no stupid questions. -- Steven From kinuthia.muchane at gmail.com Sat Jun 11 22:50:49 2011 From: kinuthia.muchane at gmail.com (=?UTF-8?B?S8SpbsWpdGhpYSBNxaljaGFuZQ==?=) Date: Sat, 11 Jun 2011 23:50:49 +0300 Subject: [Tutor] Lists In-Reply-To: References: <512866.29728.qm@web59401.mail.ac4.yahoo.com> <4DF1F11E.5030808@pearwood.info> <4DF2D447.7030708@pearwood.info> Message-ID: <4DF3D529.7040901@gmail.com> On 06/11/2011 06:51 PM, Piotr Kami?ski wrote: > Dnia 11-06-2011 o 17:30:50 Alan Gauld > napisa?(a): > >> "Piotr Kami?ski" wrote >> >>>>> This is a *technical* list, as I understand it, solely dedicated >>>>> to the >>>>> technical side of teaching the *Python* programming language and >>>>> *programming* in general. I would like to keep it this way ... >> >> Since this seems to be something we can all agree on >> can we consider this discussion closed and get back >> to Python? >> >> If you wish to continue the philosophical debate please >> take it off list. Is someone listening to Bwana Gauld? >> >> Alan g. >> List moderator. > > > OK. > > I like this style of talking - no feelings hurt, *including Christian > ones as well*. > Thank you. > > Piotr. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- K?n?thia From kinuthia.muchane at gmail.com Sat Jun 11 23:11:52 2011 From: kinuthia.muchane at gmail.com (=?UTF-8?B?S8SpbsWpdGhpYSBNxaljaGFuZQ==?=) Date: Sun, 12 Jun 2011 00:11:52 +0300 Subject: [Tutor] STUPID telnet connection question In-Reply-To: <01C1680B57B443A6A3893BC32AB6FBB0@dheiser> References: <4DF1F79A.20403@pearwood.info> <01C1680B57B443A6A3893BC32AB6FBB0@dheiser> Message-ID: <4DF3DA18.8050809@gmail.com> On 06/11/2011 08:02 PM, davidheiserca at gmail.com wrote: > > I think Steven and Alan misunderstood the Rayon's question. What is 1 + 1? David I am with you. > > Rayon is using his telnet script to pass commands to a device ONE AT A > TIME. Then he breaks the connection and reconnects for the next command.. > > He is asking how to open a telnet connection, pass MULTIPLE commands, > then close the session. > > In my opinion, both of your responses border on rude. This mailing > list is supposedly for beginners who often don't even know enough to > formulate a clear question. If some of the more senior members > ridicule the beginner's stupid questions, how will he or anyone else > learn anything. > > If I were a shy beginning programmer, these responses would probably > cause me to think twice before asking any stupid questions. Why put > myself out there for ridicule? > > There are no stupid questions! There are only stupid teachers. > > > > > ----- Original Message ----- From: "Steven D'Aprano" > > To: > Sent: Friday, June 10, 2011 3:53 AM > Subject: Re: [Tutor] telnet connection question > > >> Rayon wrote: >>> HI All, Is there any way that I can use python telnetlib to connect >>> to a telnet >>> session. >> >> It would be a pretty rubbish telnet library if it didn't let you make >> telnet connections. >> >> I don't understand why you are asking this question, since you have >> successfully made connections and are complaining that they are too >> slow. >> >> >>> Send commands and get back data without closing the connection. >> >> It would be a pretty rubbish telnet library if you couldn't send >> telnet commands. What makes you think it might not? >> >> >>> I need the response to be faster and the login process is taking up >>> too much >>> time. >> >> Then get a faster link. >> >> Seriously, this is a silly question. It's like saying "I need a >> longer piece of string". Okay, fine. How long would you like? Why is >> the piece you have too short? We can't answer those questions. >> >> How are you logging in? How much time are you talking about? How fast >> is your link? >> >> >>> I was thinking I could use a queue to pass in data but I am not sure >>> how i >>> would get it out. >> >> What data do you need to pass in, and why do you think a queue will >> help you? >> >> >> >> -- >> 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 -- K?n?thia From tim at johnsons-web.com Sat Jun 11 23:46:29 2011 From: tim at johnsons-web.com (Tim Johnson) Date: Sat, 11 Jun 2011 13:46:29 -0800 Subject: [Tutor] dummy, underscore and unused local variables Message-ID: <20110611214629.GK2556@johnsons-web.com> Consider the following code: for i in range(mylimit): foo() running pychecker gives me a """ Local variable (i) not used """ complaint. If I use for dummy in range(mylimit): .... ## or for _ in range(mylimit): .... I get no complaint from pychecker. I would welcome comments on best practices for this issue. NOTE: I see much on google regarding unused local variables, but I would like to see comments here specifically on the use for `range' On a related note: from the python interpreter if I do >>> help(_) I get Help on bool object: class bool(int) | bool(x) -> bool ...... I'd welcome comments on this as well. :) I expect to be edified is so many ways, some of them unexpected. thanks -- Tim tim at johnsons-web dot com or akwebsoft dot com http://www.akwebsoft.com From johan at accesstel.com.au Sun Jun 12 00:53:31 2011 From: johan at accesstel.com.au (Johan Geldenhuys) Date: Sun, 12 Jun 2011 08:53:31 +1000 Subject: [Tutor] Saving data as jpg file Message-ID: <000501cc288a$69661f40$3c325dc0$@com.au> Hi, I have a Axis IP camera that I can send a HTTP command to and the data returned is the jpg image. When I get this data, I want to save it as a .jpg file, but I think my encoding is not correct, because the image is all distorted. I looked at using PIL, but the device I will install my script on can't be used to install other packages like this. I'll have to include the modules in my own folder. Here is my simple code that I started testing with. """ import urllib2 # Create an OpenerDirector with support for Basic HTTP Authentication... auth_handler = urllib2.HTTPBasicAuthHandler() auth_handler.add_password('.', '192.168.10.190', 'root', 'pass') opener = urllib2.build_opener(auth_handler) # ...and install it globally so it can be used with urlopen. urllib2.install_opener(opener) return_object = urllib2.urlopen('http://192.168.10.190/axis-cgi/jpg/image.cgi?resolution=320 x240&squarepixel=1') html_content = return_object.read() img_file = "E:\work\img1.jpg" f = open(img_file, 'w') f.write(html_content) f.close() """ Any ideas what type of encoding I have to use if that is the problem? Thanks Johan -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeff at dcsoftware.com Sun Jun 12 01:19:27 2011 From: jeff at dcsoftware.com (Jeff Johnson) Date: Sat, 11 Jun 2011 16:19:27 -0700 Subject: [Tutor] Lists In-Reply-To: References: <512866.29728.qm@web59401.mail.ac4.yahoo.com><4DF1F11E.5030808@pearwood.info> <4DF2D447.7030708@pearwood.info> Message-ID: <4DF3F7FF.7040609@dcsoftware.com> Alan: Thank you for all you do. I always look for your posts! You have helped me immensely with Python and I appreciate it! Jeff ------------------- Jeff Johnson jeff at dcsoftware.com Jeff --------------- Jeff Johnson jeff at san-dc.com (623) 582-0323 www.san-dc.com On 06/11/2011 08:30 AM, Alan Gauld wrote: > "Piotr Kami?ski" wrote > >>>> This is a *technical* list, as I understand it, solely dedicated >>>> to the >>>> technical side of teaching the *Python* programming language and >>>> *programming* in general. I would like to keep it this way ... > > Since this seems to be something we can all agree on > can we consider this discussion closed and get back > to Python? > > If you wish to continue the philosophical debate please > take it off list. > > Alan g. > List moderator. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From steve at pearwood.info Sun Jun 12 02:02:15 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 12 Jun 2011 10:02:15 +1000 Subject: [Tutor] dummy, underscore and unused local variables In-Reply-To: <20110611214629.GK2556@johnsons-web.com> References: <20110611214629.GK2556@johnsons-web.com> Message-ID: <4DF40207.4080308@pearwood.info> Tim Johnson wrote: > Consider the following code: > for i in range(mylimit): > foo() > running pychecker gives me a > """ > Local variable (i) not used > """ > complaint. > If I use > for dummy in range(mylimit): > .... > ## or > for _ in range(mylimit): > .... > I get no complaint from pychecker. > I would welcome comments on best practices for this issue. The pychecker warning is just advisory. You can ignore it if you like. But using "dummy" or "_" a variable name you don't care about is good practice, as it tells the reader that they don't need to care about that variable. > On a related note: from the python interpreter if I do >>>> help(_) > I get > Help on bool object: This is a side-effect of a feature used in the Python interpreter. _ is used to hold the last result: >>> 1 + 1 2 >>> _ 2 >>> ['x', 3] + [None, 4] ['x', 3, None, 4] >>> _ ['x', 3, None, 4] So it's just a coincidence that when you called help(_) the previous command happened to result in True or False. If you try again now, you'll probably get something completely different. -- Steven From steve at pearwood.info Sun Jun 12 02:13:49 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 12 Jun 2011 10:13:49 +1000 Subject: [Tutor] Saving data as jpg file In-Reply-To: <000501cc288a$69661f40$3c325dc0$@com.au> References: <000501cc288a$69661f40$3c325dc0$@com.au> Message-ID: <4DF404BD.50507@pearwood.info> Johan Geldenhuys wrote: > Hi, > > I have a Axis IP camera that I can send a HTTP command to and the data > returned is the jpg image. > > When I get this data, I want to save it as a .jpg file, but I think my > encoding is not correct, because the image is all distorted. Are you sure that the data produced by the camera isn't already distorted? I would expect that anything you do wrong with the jpg file (such as the wrong encoding) will corrupt the file, not just distort it. But I see that you are opening the output file in text mode, and you are on Windows: img_file = "E:\work\img1.jpg" f = open(img_file, 'w') You need to open the file in binary mode, as you are writing binary data: f = open(img_file, 'wb') My guess is that this is your problem. Also, using backslashes in pathnames is tricky. You are lucky that the above works correctly, but if you move the file, it might not continue to work. Python uses backslashes to escape special characters, e.g. \n means newline. Try using this as a file name, and you will see what I mean: example = 'C:\temp\report.txt' So you need to be *very* careful of using backslashes in pathnames. The best practice is to either: * escape all the backslashes: img_file = "E:\\work\\img1.jpg" * or use forward slashes: img_file = "E:/work/img1.jpg" Windows will happily accept / instead of \ and you will save yourself a lot of grief in the future. > I looked at using PIL, but the device I will install my script on can't be > used to install other packages like this. I'll have to include the modules > in my own folder. If you can install modules in your own folder, you could put PIL in your folder and then install it. -- Steven From fomcl at yahoo.com Sun Jun 12 15:28:52 2011 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sun, 12 Jun 2011 06:28:52 -0700 (PDT) Subject: [Tutor] Excited about python In-Reply-To: <201106101212.13824.cfuller084@thinkingplanet.net> References: <20110610124101.55700@gmx.com> <201106101212.13824.cfuller084@thinkingplanet.net> Message-ID: <146328.56587.qm@web110715.mail.gq1.yahoo.com> My all-time favourite is Programming in Python 3 (Mark Summerfield) http://www.qtrac.eu/py3book.html Most of it is not for absolute beginners. Some of the chapters contain stuff I still cannot wrap my brain around. I believe the chapter about regexes (which is VERY good) is freely downloadable. Cheers!! Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ________________________________ From: Chris Fuller To: tutor at python.org Sent: Fri, June 10, 2011 7:12:11 PM Subject: Re: [Tutor] Excited about python For a handy reference, you can't beat "Python Essential Reference" by David Beazley (along with the online documentation, of course!). I think this book is obligatory if you are going to be working with Python a lot. I own all four editions :) But you wanted something more in depth with algorithms, etc. The O'Reilly book "Programming Python" by Mark Lutz is a classic and is probably a good bet for you. Core Python by Wesley Chun is also good, and I've seen him on this list from time to time. Also, check out the Python wiki: http://wiki.python.org/moin/PythonBooks Cheers _______________________________________________ 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 Sun Jun 12 15:43:10 2011 From: ryan.strunk at gmail.com (Ryan Strunk) Date: Sun, 12 Jun 2011 08:43:10 -0500 Subject: [Tutor] Floating Point Craziness Message-ID: <015b01cc2906$abf4ee00$03deca00$@gmail.com> Hi everyone, I'm designing a timeline. When the user presses the right arrow, 0.1 is added to the current position. The user can add events to the timeline, and can later scroll back across those events to see what they are. But something I absolutely don't understand is happening: I used the program to place events at 1.1, 2.1, and 3.1. Here is the end of the debug output for arrowing to 3.1 and placing the event: position = 2.7 position = 2.8 position = 2.9 position = 3.0 position = 3.1 event placed. Everything appears straight forward. But then when I check the dictionary's contents: dictionary = {3.1000000000000014: value, 2.1000000000000005: value, 1.0999999999999999: value} Why is this happening? The output is telling me 3.1, but the value isn't being placed there. I've tried rounding the 0.1 interval increase to one decimal point, but the dictionary values are still being improperly placed. Thanks for any help you can provide. Best, Ryan From swiftone at swiftone.org Sun Jun 12 16:56:45 2011 From: swiftone at swiftone.org (Brett Ritter) Date: Sun, 12 Jun 2011 10:56:45 -0400 Subject: [Tutor] Floating Point Craziness In-Reply-To: <015b01cc2906$abf4ee00$03deca00$@gmail.com> References: <015b01cc2906$abf4ee00$03deca00$@gmail.com> Message-ID: > dictionary = {3.1000000000000014: value, 2.1000000000000005: value, > 1.0999999999999999: value} > Why is this happening? The output is telling me 3.1, but the value isn't It's a quirk of how computers store floating point numbers. While humans mentally tend to treat everything as characters (and thus "3.1" is three character: a "3", a ".", and a "1") the computer internally stores everything as bytes (which are basically numbers), and we have a character set that says that such-and-such number can represent "A" or "B", or even "3". For the purposes of efficiency, actual numbers can be STORED as numbers. This is the difference between an "integer" value and a "character" value - not what is stored, but the stored number is interpreted. Internally it's all represented as binary numbers = sums of bits that represent powers of two. So 111 = 64+32+8+4+2+1 which is 1101111 (assuming the math I just did in my head is correct, but you get the idea) (Note that the Python Virtual machine is another layer of translation above this, but that's irrelevant to the basic point) Okay fine, so "1024" stored as a number only requires 10 bits (binary digits) to store, while "1024" as a string is 4 characters, requiring (at least, depending on your character set) 4 bytes to store. None of this explains what you're seeing. So how is a floating number stored? Say, 0.5? The short version (you can google for the longer and more accurate version) is that the decimal part is stored as a denominator. So 0.5 would be 2 (because 1/2 = .5) and 0.125 = 8 (because /18 = 0.125) and .75 would be the 2 bit and the 4 bit (because 1/2 + 1/4 = 0.75) That works great for powers of two, but how do you represent something like 0.1? 1/10 isn't easily represented in binary fractions. Answer: you don't. The computer instead gets the best approximation it can. When you deal with most common representations, you never notice the difference, but it's still there. Floating point math is an issue for all programs that require high precision, and there are additional libraries (including in Python) to deal with it, but they aren't the default (again, both in and out of Python) for various reasons. In your case I suspect you'll just want to use a format to output the number and you'll see exactly what you expect. It only becomes a problem in high-precision areas, which 0.1 increments don't tend to be. Hope that helps! -- Brett Ritter / SwiftOne swiftone at swiftone.org From steve at pearwood.info Sun Jun 12 19:13:05 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 13 Jun 2011 03:13:05 +1000 Subject: [Tutor] Floating Point Craziness In-Reply-To: <015b01cc2906$abf4ee00$03deca00$@gmail.com> References: <015b01cc2906$abf4ee00$03deca00$@gmail.com> Message-ID: <4DF4F3A1.3010706@pearwood.info> Ryan Strunk wrote: > Hi everyone, > I'm designing a timeline. When the user presses the right arrow, 0.1 is > added to the current position. The user can add events to the timeline, and > can later scroll back across those events to see what they are. But > something I absolutely don't understand is happening: > I used the program to place events at 1.1, 2.1, and 3.1. Here is the end of > the debug output for arrowing to 3.1 and placing the event: > position = 2.7 > position = 2.8 > position = 2.9 > position = 3.0 > position = 3.1 > event placed. > Everything appears straight forward. It only *appears* straight forward, it actually isn't. That's because the printed output is rounded so as to look nice. Compare: >>> x = 1/10.0 >>> print(x) # displayed as nicely as possible 0.1 >>> print('%.25f' % x) # display 25 decimal places 0.1000000000000000055511151 For speed and simplicity, floats are stored by the computer using fractional powers of two. That's fine for numbers which are powers of two (1/2, 1/4, 1/256, and sums of such) but numbers that humans like to use tend to be powers of 10, not 2. Unfortunately, many common fractions cannot be written exactly in binary. You're probably familiar with the fact that fractions like 1/3 cannot be written exactly in decimal: 1/3 = 0.33333333... goes on forever The same is true for some numbers in binary: 1/10 in decimal = 1/16 + 1/32 + 1/256 + ... also goes on forever. Written in fractional bits: 1/10 decimal = 0.00011001100110011... in binary Since floats can only store a finite number of bits, 1/10 cannot be stored exactly. It turns out that the number stored is a tiny bit larger than 1/10: >>> Fraction.from_float(0.1) - Fraction(1)/10 Fraction(1, 180143985094819840) Rounding doesn't help: 0.1 is already rounded as close to 1/10 as it can possibly get. Now, when you print the dictionary containing those floats, Python displays (almost) the full precision: >>> print {1: 0.1} {1: 0.10000000000000001} In newer versions of Python, it may do a nicer job of printing the float so that the true value is hidden. E.g. in Python 3.1 I see: >>> print({1: 0.1}) {1: 0.1} but don't be fooled: Python's print display is pulling the wool over your eyes, the actual value is closer to 0.10000000000000001. One consequence of that is that adding 0.1 ten times does not give 1 exactly, but slightly less than 1: >>> x = 0.1 >>> 1 - sum([x]*10) 1.1102230246251565e-16 (P.S. this is why you should never use floats for currency. All those missing and excess fractions of a cent add up to real money.) To avoid this, you can: * Upgrade to a newer version of Python that lies to you more often, so that you can go on living in blissful ignorance (until such time as you run into a more serious problem with floats); * Use the fraction module, or the decimal module, but they are slower than floats; or * Instead of counting your timeline in increments of 0.1, scale everything by 10 so the increment is 1. That is, instead of: 2.0 2.1 2.2 2.3 ... you will have 20 21 22 23 24 ... * Or you just get used to the fact that some numbers are not exact in floating point. -- Steven From amonroe at columbus.rr.com Sun Jun 12 19:53:57 2011 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sun, 12 Jun 2011 13:53:57 -0400 Subject: [Tutor] [OT] Re: Floating Point Craziness In-Reply-To: <4DF4F3A1.3010706@pearwood.info> References: <015b01cc2906$abf4ee00$03deca00$@gmail.com> <4DF4F3A1.3010706@pearwood.info> Message-ID: <18488783263.20110612135357@columbus.rr.com> > * Or you just get used to the fact that some numbers are not exact in > floating point. This got me thinking. How many decimal places do you need to accurately, say, aim a laser somewhere in a 180 degree arc accurately enough to hit a dime on the surface of the moon? Alan From piotr-kam at o2.pl Sun Jun 12 22:06:17 2011 From: piotr-kam at o2.pl (=?utf-8?B?UGlvdHIgS2FtacWEc2tp?=) Date: Sun, 12 Jun 2011 22:06:17 +0200 Subject: [Tutor] Lists In-Reply-To: References: <512866.29728.qm@web59401.mail.ac4.yahoo.com> <4DF1F11E.5030808@pearwood.info> <4DF2D447.7030708@pearwood.info> Message-ID: Dnia 11-06-2011 o 17:51:03 Piotr Kami?ski napisa?(a): > Dnia 11-06-2011 o 17:30:50 Alan Gauld > napisa?(a): > >> "Piotr Kami?ski" wrote >> >>>>> This is a *technical* list, as I understand it, solely dedicated to ... >> Since this seems to be something we can all agree on >> can we consider this discussion closed and get back >> to Python? >> >> If you wish to continue the philosophical debate please >> take it off list. >> >> Alan g. >> List moderator. > > > OK. > > I like this style of talking - no feelings hurt, *including Christian > ones as well*. > Thank you. > > Piotr. To be perfectly clear, as I've got the impression that my words were interpreted in various ways by different people: the "thank you" in my reply to Alan Gauld's message, *is not* a sign of subservience/weakness, my seeking his approval or a similar attitude. I thanked him strictly for *the *polite* style of talking* on the list; I do not expect Alan Gauld or any other Tutor list user to agree with or approve of any of my philosophical views. In other words, *in my culture* thanking someone for something (and, by the way: apologising to someone for a mistake made) is strictly a sign of *politeness*, not of some weakness, defeat, being a losing party, a member of a lower social class etc. Over and out. Piotr From walksloud at gmail.com Sun Jun 12 22:55:52 2011 From: walksloud at gmail.com (Andre' Walker-Loud) Date: Sun, 12 Jun 2011 13:55:52 -0700 Subject: [Tutor] [OT] Re: Floating Point Craziness In-Reply-To: <18488783263.20110612135357@columbus.rr.com> References: <015b01cc2906$abf4ee00$03deca00$@gmail.com> <4DF4F3A1.3010706@pearwood.info> <18488783263.20110612135357@columbus.rr.com> Message-ID: Hi Alan, >> * Or you just get used to the fact that some numbers are not exact in >> floating point. > > This got me thinking. How many decimal places do you need to > accurately, say, aim a laser somewhere in a 180 degree arc accurately > enough to hit a dime on the surface of the moon? Here is a quick back of the envelope estimate for you. (While I am still learning the Python, I can answer this one!) The angle subtended by a dime on the earth is (approximately) given by sin( theta ) = d / sqrt( R^2 + d^2 ) where d = 1 cm (the diameter of a dime) R = 384,403 km (the average distance from the center of the earth to the center of the moon - the moon traverses an elliptical path about the earth) To make the approximation simple, take advantage of the series expansion for sin (theta) and 1 / sqrt(R^2 + d^2) first d / sqrt( R^2 + d^2 ) = d / R * 1 / sqrt(1 + d^2 / R^2 ) ~= d / R * (1 - 1/2 * d^2 / R^2 + ...) now d / R = 1 * e-2 / (384403 * e3) ~= 3 * e-11 so the d^2 / R^2 correction will be very small, and won't effect the determination. So we now have sin (theta) ~= d / R This will be a very small angle. The next approximation to make is for small angles sin (theta) ~= theta + ... leaving us with theta ~= d / R To be approximate, assume the precision you need is equal to the size of the dime. This means you need an precision of d theta ~= d/R ~= 3 * e-11 ( = 3 * 10^{-11} if you aren't familiar with the "e" notation) this is the minimum precision you would need in both the "x" and "y" direction to accurately hit the dime on the moon with your laser (at its average distance). Corrections to this estimate will come from the fact that the moon's radius is ~1737 km and the earth's radius is ~6370 km, so you are actually this much closer (R is this much smaller). Of course both the earth is spinning and the moon is moving relative to us, so you would have to account for those extra corrections as well. Hope that wasn't too much info, Andr? From bermanrl at cfl.rr.com Sun Jun 12 23:17:38 2011 From: bermanrl at cfl.rr.com (R. Berman) Date: Sun, 12 Jun 2011 17:17:38 -0400 Subject: [Tutor] Lists In-Reply-To: References: <512866.29728.qm@web59401.mail.ac4.yahoo.com> <4DF1F11E.5030808@pearwood.info> <4DF2D447.7030708@pearwood.info> Message-ID: <01ee01cc2946$2886e380$7994aa80$@rr.com> Having followed this absurd thread from its beginning hopefully to this, the end of it. Everyone replying to your diatribe has been incredibly polite to you. One of the moderators tried to explain the obvious to you. This is a Python group. Python is to most of us a delightful language. To others it is a snake. It is not a god a priest or a rabbi. You are arguing religion and issues pertaining to very elementary sophistry. You are acting the fool. Enough. You have crossed the line and have become the 'Troll mediocre'. Go forth and spew your venom elsewhere. Robert > -----Original Message----- > From: tutor-bounces+bermanrl=cfl.rr.com at python.org [mailto:tutor- > bounces+bermanrl=cfl.rr.com at python.org] On Behalf Of Piotr Kaminski > Sent: Sunday, June 12, 2011 4:06 PM > To: tutor at python.org > Subject: Re: [Tutor] Lists > > Dnia 11-06-2011 o 17:51:03 Piotr Kami?ski > napisa?(a): > > > Dnia 11-06-2011 o 17:30:50 Alan Gauld > > napisa?(a): > > > >> "Piotr Kami?ski" wrote > >> > >>>>> This is a *technical* list, as I understand it, solely > dedicated to > ... > > >> Since this seems to be something we can all agree on > >> can we consider this discussion closed and get back > >> to Python? > >> > >> If you wish to continue the philosophical debate please > >> take it off list. > >> > >> Alan g. > >> List moderator. > > > > > > OK. > > > > I like this style of talking - no feelings hurt, *including > Christian > > ones as well*. > > Thank you. > > > > Piotr. > > > To be perfectly clear, as I've got the impression that my words were > interpreted in various ways by different people: the "thank you" in > my > reply to Alan Gauld's message, *is not* a sign of > subservience/weakness, > my seeking his approval or a similar attitude. > > I thanked him strictly for *the *polite* style of talking* on the > list; I > do not expect Alan Gauld or any other Tutor list user to agree with > or > approve of any of my philosophical views. > > In other words, *in my culture* thanking someone for something (and, > by > the way: apologising to someone for a mistake made) is strictly a > sign of > *politeness*, not of some weakness, defeat, being a losing party, a > member > of a lower social class etc. > > Over and out. > > Piotr > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- I am using the free version of SPAMfighter. We are a community of 7 million users fighting spam. SPAMfighter has removed 237 of my spam emails to date. Get the free SPAMfighter here: http://www.spamfighter.com/len The Professional version does not have this message From johan at accesstel.com.au Sun Jun 12 23:47:49 2011 From: johan at accesstel.com.au (Johan Geldenhuys) Date: Mon, 13 Jun 2011 07:47:49 +1000 Subject: [Tutor] Saving data as jpg file In-Reply-To: <4DF404BD.50507@pearwood.info> References: <000501cc288a$69661f40$3c325dc0$@com.au> <4DF404BD.50507@pearwood.info> Message-ID: <001901cc294a$6150b660$23f22320$@com.au> Hi, I tried using the "wb" to create and write the file. In a simple test I did to open an existing jpg file I know is good, putting the data in my new file and closing it, it worked. I don't have access to the camera now, but will try it tomorrow. Thanks Johan -----Original Message----- From: tutor-bounces+johan=accesstel.com.au at python.org [mailto:tutor-bounces+johan=accesstel.com.au at python.org] On Behalf Of Steven D'Aprano Sent: Sunday, 12 June 2011 10:14 AM To: Tutor at python.org Subject: Re: [Tutor] Saving data as jpg file Johan Geldenhuys wrote: > Hi, > > I have a Axis IP camera that I can send a HTTP command to and the data > returned is the jpg image. > > When I get this data, I want to save it as a .jpg file, but I think my > encoding is not correct, because the image is all distorted. Are you sure that the data produced by the camera isn't already distorted? I would expect that anything you do wrong with the jpg file (such as the wrong encoding) will corrupt the file, not just distort it. But I see that you are opening the output file in text mode, and you are on Windows: img_file = "E:\work\img1.jpg" f = open(img_file, 'w') You need to open the file in binary mode, as you are writing binary data: f = open(img_file, 'wb') My guess is that this is your problem. Also, using backslashes in pathnames is tricky. You are lucky that the above works correctly, but if you move the file, it might not continue to work. Python uses backslashes to escape special characters, e.g. \n means newline. Try using this as a file name, and you will see what I mean: example = 'C:\temp\report.txt' So you need to be *very* careful of using backslashes in pathnames. The best practice is to either: * escape all the backslashes: img_file = "E:\\work\\img1.jpg" * or use forward slashes: img_file = "E:/work/img1.jpg" Windows will happily accept / instead of \ and you will save yourself a lot of grief in the future. > I looked at using PIL, but the device I will install my script on can't be > used to install other packages like this. I'll have to include the modules > in my own folder. If you can install modules in your own folder, you could put PIL in your folder and then install it. -- Steven _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From robert.sjoblom at gmail.com Mon Jun 13 00:27:22 2011 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Mon, 13 Jun 2011 00:27:22 +0200 Subject: [Tutor] [OT] Re: Floating Point Crazines Message-ID: >> * Or you just get used to the fact that some numbers are not exact in >> floating point. > > This got me thinking. How many decimal places do you need to > accurately, say, aim a laser somewhere in a 180 degree arc accurately > enough to hit a dime on the surface of the moon? > > Alan In short: it's pretty much impossible. The mirrors used in the Lunar Laser Ranging experiments are roughly the size of a suitcase (each). Data from the APOLLO (Apache Point Observatory Lunar Laser-ranging Operation) gives us some numbers to go by: it uses 1 gigawatt energy, generating a (roughly) 1-inch long "bullet" of light. By the time it hits the moon it will have distorted to a diameter of 1.25 miles (earth's atmosphere is the biggest culprit). only about 1 in 30 *million* photons will actually hit the retroflector, and by the time it gets back to the telescope on earth the beam is about 9 miles wide. Again, only 1 in 30 million *of the returning* photons will hit the telescope. Now imagine scaling the retroflector in size to a dime. To bring it back on topic: could python handle these numbers reliably? -- best regards, Robert S. From mywrkid at yahoo.com Mon Jun 13 00:40:28 2011 From: mywrkid at yahoo.com (Neha P) Date: Sun, 12 Jun 2011 15:40:28 -0700 (PDT) Subject: [Tutor] subprocess.Popen() OR subprocess.call() ? Message-ID: <76706.18465.qm@web121804.mail.ne1.yahoo.com> Hi all, I am newbie and want to know what is the difference between subprocess.Popen() and subprocess.call() ? when is it best to use each one? Any help appreciated!!? Regards, Neha -------------- next part -------------- An HTML attachment was scrubbed... URL: From markc at flexsystems.net Mon Jun 13 00:47:22 2011 From: markc at flexsystems.net (Mark Cowley - FlexSystems) Date: Sun, 12 Jun 2011 16:47:22 -0600 Subject: [Tutor] Creating Reports in Python Message-ID: Hi I am looking for recommendations for Report writers under Python. Current reports are in Crystal reports if that is an option. Any suggestions are welcome. Thanks Mark -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Jun 13 01:22:18 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 13 Jun 2011 00:22:18 +0100 Subject: [Tutor] subprocess.Popen() OR subprocess.call() ? References: <76706.18465.qm@web121804.mail.ne1.yahoo.com> Message-ID: "Neha P" wrote > I am newbie and want to know what is the difference > between subprocess.Popen() and subprocess.call() ? Simply speaking, call() is a way to make subprocess easier to use. Popen gives you much more powerful options but that flexibility means it's harder to use. > when is it best to use each one? Use the simplest option that works for you. Start with call and if it can't do the job switch to Popen. HTH, From steve at pearwood.info Mon Jun 13 04:11:51 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 13 Jun 2011 12:11:51 +1000 Subject: [Tutor] [OT] Re: Floating Point Crazines In-Reply-To: References: Message-ID: <4DF571E7.5030409@pearwood.info> Robert Sjoblom wrote: >>> * Or you just get used to the fact that some numbers are not exact in >>> floating point. >> This got me thinking. How many decimal places do you need to >> accurately, say, aim a laser somewhere in a 180 degree arc accurately >> enough to hit a dime on the surface of the moon? >> >> Alan > > In short: it's pretty much impossible. [...] > To bring it back on topic: could python handle these numbers reliably? *Physically* impossible, not mathematically. If you prefer, imagine putting a laser and a dime in deep space, far from any dust or atmosphere or gravitational distortion, so that we can assume perfectly Euclidean geometry. Put the dime some distance away, and aim the laser at the centre of it: laser * --------------------------- + dime Your margin of error in the aiming angle is given by the angle subtended by the dime. That is, you don't have to aim exactly at the centre (angle = 0 degrees), but at any angle between -a and +a degrees, whatever a happens to be. That angle a gives the precision needed. (Strictly speaking, we should be talking about solid angles, steradians, rather than degrees. But for this thought experiment, the difference doesn't matter.) Andre Walker-Loud has already given a back-of-the-envelope calculation which estimates that angle as about 1e-11, so the precision needed is about 12 decimal places. Python's floats have 52 *binary* places of precision, or approximately 15 *decimal* places. So even though we may not be able to physically build a machine capable of aiming a laser to a precision of 0.00000000001 degrees, at least we can be comforted by the knowledge that a C double or a Python float is precise enough to handle the job. -- Steven From steve at pearwood.info Mon Jun 13 04:13:32 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 13 Jun 2011 12:13:32 +1000 Subject: [Tutor] Creating Reports in Python In-Reply-To: References: Message-ID: <4DF5724C.3080501@pearwood.info> Mark Cowley - FlexSystems wrote: > Hi > > > > I am looking for recommendations for Report writers under Python. Current > reports are in Crystal reports if that is an option. > > Any suggestions are welcome. You might get more responses on the main python mailing list, python-list at python.org, or comp.lang.python on Usenet, than here. -- Steven From waynejwerner at gmail.com Mon Jun 13 05:31:13 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Sun, 12 Jun 2011 22:31:13 -0500 Subject: [Tutor] [OT] Re: Floating Point Crazines In-Reply-To: <4DF571E7.5030409@pearwood.info> References: <4DF571E7.5030409@pearwood.info> Message-ID: On Sun, Jun 12, 2011 at 9:11 PM, Steven D'Aprano wrote: > Robert Sjoblom wrote: > >> * Or you just get used to the fact that some numbers are not exact in >>>> floating point. >>>> >>> This got me thinking. How many decimal places do you need to >>> accurately, say, aim a laser somewhere in a 180 degree arc accurately >>> enough to hit a dime on the surface of the moon? >>> >>> Alan >>> >> >> In short: it's pretty much impossible. >> > [...] > > To bring it back on topic: could python handle these numbers reliably? >> > > *Physically* impossible, not mathematically. > [...] at least we can be comforted by the knowledge that a C double or a > Python float is precise enough to handle the job. > Which is actually unsurprising, since my calculator has several times the processing power of the computers on board the original lunar lander. Also, the phone in my pocket probably has several thousand times the processing power and millions of times the memory. Pretty amazing! -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From amonroe at columbus.rr.com Mon Jun 13 05:43:01 2011 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sun, 12 Jun 2011 23:43:01 -0400 Subject: [Tutor] [OT] Re: Floating Point Crazines In-Reply-To: <4DF571E7.5030409@pearwood.info> References: <4DF571E7.5030409@pearwood.info> Message-ID: <136524127425.20110612234301@columbus.rr.com> > Python's floats have 52 *binary* places of precision, or approximately > 15 *decimal* places. So even though we may not be able to physically > build a machine capable of aiming a laser to a precision of > 0.00000000001 degrees, at least we can be comforted by the knowledge > that a C double or a Python float is precise enough to handle the job. Comforting, indeed. Thanks :) Alan From vincentbalmori at yahoo.com Mon Jun 13 11:02:33 2011 From: vincentbalmori at yahoo.com (Vincent Balmori) Date: Mon, 13 Jun 2011 02:02:33 -0700 (PDT) Subject: [Tutor] step value Message-ID: <73040.61842.qm@web59404.mail.ac4.yahoo.com> I am stuck on a question for Absolute Beginner's. I googled this and there have been others who have not understood the question and I am also not clear on the question he is asking. This function is a part of a tic tac toe program."Improve the function ask_number() so that the function can be called with a step value. Make the default value of step 1." def ask_number(question, low, high): """Ask for a number within a range.""" response = None while response not in range(low, high): response = int(input(question)) return response -------------- next part -------------- An HTML attachment was scrubbed... URL: From bugcy013 at gmail.com Mon Jun 13 11:59:20 2011 From: bugcy013 at gmail.com (Ganesh Kumar) Date: Mon, 13 Jun 2011 15:29:20 +0530 Subject: [Tutor] python-gobject for debian4 Message-ID: Hi Guys. I want python-gobject package for debian4 (etch). But unfortunately removed for debian4 depository . How to install python-gobject package in debian4.. My Idea is download debian5 repository python-gobject.deb file Install in debian4. I have try is working fine. but the thing is reboot the mache show kernel-panic (KERNEL TO OLD) I search google..its libc6 problem.. But i want python-gobject otherwise my project not working .. How to migrate python-gobject for debian4 please guide me.. -Ganesh. Did I learn something today? If not, I wasted it. From steve at pearwood.info Mon Jun 13 12:07:26 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 13 Jun 2011 20:07:26 +1000 Subject: [Tutor] step value In-Reply-To: <73040.61842.qm@web59404.mail.ac4.yahoo.com> References: <73040.61842.qm@web59404.mail.ac4.yahoo.com> Message-ID: <4DF5E15E.6030401@pearwood.info> Vincent Balmori wrote: > I am stuck on a question for Absolute Beginner's. I googled this and there have > been others who have not understood the question and I am also not clear on the > question he is asking. This function is a part of a tic tac toe program."Improve > the function ask_number() so that the function can be called with a step value. > Make the default value of step 1." It's hard to guess what the author was thinking if he doesn't explain it, but I think what he means is this: The aim of the "ask_number" function is to get the caller -- you -- to enter a number in the range(low, high). That much is easy, and you already have the function doing that. But the range function can take a third, optional argument "step". Instead of (for example) range(1, 20) => [1, 2, 3, 4, 5, 6, ... 17, 18, 19] you can pass a step N and get only every Nth value, e.g.: range(1, 20, 3) => [1, 4, 7, 10, 13, 16, 19] # every third number So, you have a function which calls range() internally: > def ask_number(question, low, high): > """Ask for a number within a range.""" > response = None > while response not in range(low, high): > response = int(input(question)) > return response and your mission is to modify that function so that it takes an optional argument that defaults to 1, and passes that argument to the range() function as step. Does that help? -- Steven From steve at pearwood.info Mon Jun 13 12:09:42 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 13 Jun 2011 20:09:42 +1000 Subject: [Tutor] python-gobject for debian4 In-Reply-To: References: Message-ID: <4DF5E1E6.3040107@pearwood.info> Ganesh Kumar wrote: > Hi Guys. > > I want python-gobject package for debian4 (etch). But unfortunately > removed for debian4 depository . This is not a Python problem. It is especially not a problem about learning Python. You should ask this at either a Debian forum or on the python-gobject mailing list (if any) or ask the maintainer of python-gobject. -- Steven From nathan2012 at 163.com Mon Jun 13 14:02:38 2011 From: nathan2012 at 163.com (Nathan) Date: Mon, 13 Jun 2011 20:02:38 +0800 (CST) Subject: [Tutor] Floating Point Craziness In-Reply-To: <4DF4F3A1.3010706@pearwood.info> References: <4DF4F3A1.3010706@pearwood.info> <015b01cc2906$abf4ee00$03deca00$@gmail.com> Message-ID: <102b1a5.7cb4.13088e1d17f.Coremail.nathan2012@163.com> who can tell me how to unsubscribe the message. At 2011-06-13 01:13:05?"Steven DAprano" wrote: >Ryan Strunk wrote: >> Hi everyone, >> I'm designing a timeline. When the user presses the right arrow, 0.1 is >> added to the current position. The user can add events to the timeline, and >> can later scroll back across those events to see what they are. But >> something I absolutely don't understand is happening: >> I used the program to place events at 1.1, 2.1, and 3.1. Here is the end of >> the debug output for arrowing to 3.1 and placing the event: >> position = 2.7 >> position = 2.8 >> position = 2.9 >> position = 3.0 >> position = 3.1 >> event placed. >> Everything appears straight forward. > > >It only *appears* straight forward, it actually isn't. That's because >the printed output is rounded so as to look nice. Compare: > > >>> x = 1/10.0 > >>> print(x) # displayed as nicely as possible >0.1 > >>> print('%.25f' % x) # display 25 decimal places >0.1000000000000000055511151 > > >For speed and simplicity, floats are stored by the computer using >fractional powers of two. That's fine for numbers which are powers of >two (1/2, 1/4, 1/256, and sums of such) but numbers that humans like to >use tend to be powers of 10, not 2. > >Unfortunately, many common fractions cannot be written exactly in >binary. You're probably familiar with the fact that fractions like 1/3 >cannot be written exactly in decimal: > >1/3 = 0.33333333... goes on forever > >The same is true for some numbers in binary: > >1/10 in decimal = 1/16 + 1/32 + 1/256 + ... > >also goes on forever. Written in fractional bits: > >1/10 decimal = 0.00011001100110011... in binary > >Since floats can only store a finite number of bits, 1/10 cannot be >stored exactly. It turns out that the number stored is a tiny bit larger >than 1/10: > > >>> Fraction.from_float(0.1) - Fraction(1)/10 >Fraction(1, 180143985094819840) > >Rounding doesn't help: 0.1 is already rounded as close to 1/10 as it can >possibly get. > >Now, when you print the dictionary containing those floats, Python >displays (almost) the full precision: > > >>> print {1: 0.1} >{1: 0.10000000000000001} > > >In newer versions of Python, it may do a nicer job of printing the float >so that the true value is hidden. E.g. in Python 3.1 I see: > > > >>> print({1: 0.1}) >{1: 0.1} > >but don't be fooled: Python's print display is pulling the wool over >your eyes, the actual value is closer to 0.10000000000000001. > > >One consequence of that is that adding 0.1 ten times does not give 1 >exactly, but slightly less than 1: > > >>> x = 0.1 > >>> 1 - sum([x]*10) >1.1102230246251565e-16 > > >(P.S. this is why you should never use floats for currency. All those >missing and excess fractions of a cent add up to real money.) > > >To avoid this, you can: > > >* Upgrade to a newer version of Python that lies to you more often, so >that you can go on living in blissful ignorance (until such time as you >run into a more serious problem with floats); > >* Use the fraction module, or the decimal module, but they are slower >than floats; or > >* Instead of counting your timeline in increments of 0.1, scale >everything by 10 so the increment is 1. > >That is, instead of: > >2.0 2.1 2.2 2.3 ... > >you will have > >20 21 22 23 24 ... > > >* Or you just get used to the fact that some numbers are not exact in >floating point. > > > > >-- >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 Mon Jun 13 14:48:02 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 13 Jun 2011 13:48:02 +0100 Subject: [Tutor] Floating Point Craziness References: <4DF4F3A1.3010706@pearwood.info><015b01cc2906$abf4ee00$03deca00$@gmail.com> <102b1a5.7cb4.13088e1d17f.Coremail.nathan2012@163.com> Message-ID: "Nathan" wrote Every message tells you: > who can tell me how to unsubscribe the message. > > >> >>_______________________________________________ >>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 sulinet at postafiok.hu Mon Jun 13 15:08:46 2011 From: sulinet at postafiok.hu (=?ISO-8859-1?Q?V=E1las_P=E9ter?=) Date: Mon, 13 Jun 2011 15:08:46 +0200 Subject: [Tutor] Floating Point Craziness In-Reply-To: References: <015b01cc2906$abf4ee00$03deca00$@gmail.com> Message-ID: 2011/6/12 Brett Ritter > > Okay fine, so "1024" stored as a number only requires 10 bits (binary > digits) to store, Actually, 11. :-) Another point that was still not emphasized enough: that's why Python's documentation at http://docs.python.org/dev/library/stdtypes.html#mapping-types-dict says: "Note however, that since computers store floating-point numbers as approximations it is usually unwise to use them as dictionary keys." -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Mon Jun 13 15:23:19 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 13 Jun 2011 23:23:19 +1000 Subject: [Tutor] Floating Point Craziness In-Reply-To: <102b1a5.7cb4.13088e1d17f.Coremail.nathan2012@163.com> References: <4DF4F3A1.3010706@pearwood.info> <015b01cc2906$abf4ee00$03deca00$@gmail.com> <102b1a5.7cb4.13088e1d17f.Coremail.nathan2012@163.com> Message-ID: <4DF60F47.8080102@pearwood.info> Nathan wrote: > who can tell me how to unsubscribe the message. Look at the bottom of every single message to the mailing list, and you will see this: >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor -- Steven From steve at pearwood.info Mon Jun 13 15:29:44 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 13 Jun 2011 23:29:44 +1000 Subject: [Tutor] Floating Point Craziness In-Reply-To: References: <015b01cc2906$abf4ee00$03deca00$@gmail.com> Message-ID: <4DF610C8.5090809@pearwood.info> V?las P?ter wrote: > 2011/6/12 Brett Ritter > >> Okay fine, so "1024" stored as a number only requires 10 bits (binary >> digits) to store, > > Actually, 11. :-) I see your smiley, but actually more than that. Due to the way computers are designed, numbers are stored in fixed bundles of 8 bits making a byte. A single byte (8 bits) can store between 0 and 255. So to store 1024, you need two bytes, or 16 bits, not 11. In practice, that will usually be four bytes, 32 bits, or even eight. And if you're using Python, where everything is an object, it will actually be fourteen bytes, or 112 bits: >>> sys.getsizeof(1024) 14 -- Steven From sulinet at postafiok.hu Mon Jun 13 15:54:56 2011 From: sulinet at postafiok.hu (=?ISO-8859-1?Q?V=E1las_P=E9ter?=) Date: Mon, 13 Jun 2011 15:54:56 +0200 Subject: [Tutor] Floating Point Craziness In-Reply-To: <4DF610C8.5090809@pearwood.info> References: <015b01cc2906$abf4ee00$03deca00$@gmail.com> <4DF610C8.5090809@pearwood.info> Message-ID: 2011/6/13 Steven D'Aprano > Okay fine, so "1024" stored as a number only requires 10 bits (binary >>> digits) to store, >>> >> >> Actually, 11. :-) >> > > > I see your smiley, but actually more than that. OK, this was the math, I just told that 10 bits were not enough for 2^10. > > And if you're using Python, where everything is an object, it will actually > be fourteen bytes, or 112 bits: > Where is the structure of this object (or Python objects in general) documented? Suppose, I would like to turn an object into a bytearray to study its anatomy. But the converter wants to have an encoding as parameter. How can I do that? P?ter -------------- next part -------------- An HTML attachment was scrubbed... URL: From bayespokerguy at gmail.com Mon Jun 13 16:22:35 2011 From: bayespokerguy at gmail.com (Fred G) Date: Mon, 13 Jun 2011 10:22:35 -0400 Subject: [Tutor] Medical Decision-Making Question Message-ID: Hello-- I'm a pre-med student interested in decision-making as applied to medical decisions. I am trying to build a medical decision-making algorithm and am pretty stuck on a few things. I've built a file that contains a list of many diseases and their associated symptoms. For example, here are the column headers and two sample rows (the "|" = "or"): Disease Symptoms Cold sore_throat|runny_nose|congestion|cough|aches|slight_fever Flu sore_throat|fever|headache|muscle_aches|soreness|congestion|cough|returning_fever My questions are the following: a) How's the best way to make it so I can have a user type in a list of symptoms and then have the computer tell the user the possible diseases that share those symptoms? In other words, on a high-level I have a pretty good idea of what I want my algorithm to do-- but I need help implementing the basic version first. I'd like to do the following: >>>Please enter a list of symptoms >>>[user_input] >>>Possible diseases include: x, y, z b)Once I get that working, could anyone point me to good code already written in Python such that I could have a model (for syntax and overall structure) for figuring out how to make the computer evaluate more factors such as: patient age, patient history, and even downloading archival data for patients in the same demographic group? Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From eire1130 at gmail.com Mon Jun 13 16:48:02 2011 From: eire1130 at gmail.com (James Reynolds) Date: Mon, 13 Jun 2011 10:48:02 -0400 Subject: [Tutor] Medical Decision-Making Question In-Reply-To: References: Message-ID: I would start by getting a lot of the parameters you need in a database such as SQLite (comes with python). So for example, you would have a disease with known symptoms. You could structure your tables with diseases symptoms So, say the disease is a cold in the table you will have a row for cold and columns identifying each symptom (by unique IDs). In your symptom table you would have a row for each symptom and a column for its parameters and probabilities and such. For example, gender exclusive, age exclusive, geographic exclusive, workplace, etc. >From there you can build your select statements on the fly using python's string formating. That's how i would do it anyway. I'm sure there are other ways as well. On Mon, Jun 13, 2011 at 10:22 AM, Fred G wrote: > Hello-- > > I'm a pre-med student interested in decision-making as applied to medical > decisions. I am trying to build a medical decision-making algorithm and am > pretty stuck on a few things. > > I've built a file that contains a list of many diseases and their > associated symptoms. For example, here are the column headers and two > sample rows (the "|" = "or"): > Disease Symptoms > Cold > sore_throat|runny_nose|congestion|cough|aches|slight_fever > Flu > sore_throat|fever|headache|muscle_aches|soreness|congestion|cough|returning_fever > > My questions are the following: > a) How's the best way to make it so I can have a user type in a list of > symptoms and then have the computer tell the user the possible diseases that > share those symptoms? In other words, on a high-level I have a pretty good > idea of what I want my algorithm to do-- but I need help implementing the > basic version first. I'd like to do the following: > >>>Please enter a list of symptoms > >>>[user_input] > >>>Possible diseases include: x, y, z > > b)Once I get that working, could anyone point me to good code already > written in Python such that I could have a model (for syntax and overall > structure) for figuring out how to make the computer evaluate more factors > such as: patient age, patient history, and even downloading archival data > for patients in the same demographic group? > > 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 weaselkeeper at gmail.com Mon Jun 13 17:44:26 2011 From: weaselkeeper at gmail.com (Jim Richardson) Date: Mon, 13 Jun 2011 08:44:26 -0700 Subject: [Tutor] Medical Decision-Making Question In-Reply-To: References: Message-ID: On Mon, Jun 13, 2011 at 7:22 AM, Fred G wrote: > Hello-- > I'm a pre-med student interested in decision-making as applied to medical > decisions. ?I am trying to build a medical decision-making algorithm and am > pretty stuck on a few things. > I've built a file that contains a list of many diseases and their associated > symptoms. ?For example, here are the column headers and two sample rows (the > "|" = "or"): > Disease ? ? ? ? ? ? ? ?Symptoms > Cold > sore_throat|runny_nose|congestion|cough|aches|slight_fever > Flu > sore_throat|fever|headache|muscle_aches|soreness|congestion|cough|returning_fever > My questions are the following: > a) ?How's the best way to make it so I can have a user type in a list of > symptoms and then have the computer tell the user the possible diseases that > share those symptoms? In other words, on a high-level I have a pretty good > idea of what I want my algorithm to do-- but I need help implementing the > basic version first. ?I'd like to do the following: >>>>Please enter a list of symptoms >>>>[user_input] >>>>Possible diseases include: x, y, z > b)Once I get that working, could anyone point me to good code already > written in Python such that I could have a model (for syntax and overall > structure) for figuring out how to make the computer evaluate more factors > such as: patient age, patient history, and even downloading archival data > for patients in the same demographic group? > Thanks! > > One problem with writing the symptoms is misspelling and word choice, is mild fever the same as slight fever? etc. Another way to do that is to present a list, when the user selects one item in that list, (say, fever, mild) the list is restructured to exclude symptoms that would clash with that, like all the other fevers. After a while of clicking on list items, the evaluator can make a best match against diseases. Downside is a fair amount of processing. You could also group symptoms and have severity as a seperate, so you select fever, then mild,high, whatever. Evaluating it is going to be fun, it's a lot more than binary matches. -- http://neon-buddha.net From steve at pearwood.info Mon Jun 13 17:52:47 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 14 Jun 2011 01:52:47 +1000 Subject: [Tutor] Medical Decision-Making Question In-Reply-To: References: Message-ID: <4DF6324F.5050505@pearwood.info> Fred G wrote: > Hello-- > > I'm a pre-med student interested in decision-making as applied to medical > decisions. I am trying to build a medical decision-making algorithm and am > pretty stuck on a few things. Essentially what you want is to build an expert system. I don't want to discourage you, but expert systems are big, complicated pieces of software! They're a form of artificial intelligence. You probably want to think hard about how to narrow the problem you're trying to solve. You could google on "python expert system ai" are similar terms, see what comes up. Other search terms might include "inference engine": you want the software to *infer* a disease from a set of symptoms. Another possibility is to look at "logic programming". Traditionally people do that in Prolog, but there are some tools for doing this in Python. Google on "prolog python", or look at Pyke: http://pyke.sourceforge.net/ More comments below. > I've built a file that contains a list of many diseases and their associated > symptoms. For example, here are the column headers and two sample rows (the > "|" = "or"): > Disease Symptoms > Cold > sore_throat|runny_nose|congestion|cough|aches|slight_fever > Flu > sore_throat|fever|headache|muscle_aches|soreness|congestion|cough|returning_fever > > My questions are the following: > a) How's the best way to make it so I can have a user type in a list of > symptoms and then have the computer tell the user the possible diseases that > share those symptoms? In other words, on a high-level I have a pretty good > idea of what I want my algorithm to do-- but I need help implementing the > basic version first. I'd like to do the following: >>>> Please enter a list of symptoms >>>> [user_input] >>>> Possible diseases include: x, y, z First you need to decide, how would *you* decide which diseases are possible? My *guess* is that you would do something like this: for each symptom given: for each disease: if the symptom appears in the disease, then add disease to the list of possible diseases But should some symptoms count as stronger than others? I don't know. Here is a toy example, presented without explanation because it's 1:50am here in Australia and I'm getting tired. I don't know whether you are a beginner at Python or you've been programming for years, so don't hesitate to ask if you don't understand any of it! # Untested! class Disease: def __init__(self, name, symptoms): self.name = name self.symptoms = symptoms known_diseases = [ Disease('cold', set( "sore throat|runny nose|congestion|cough|aches".split("|")) ), Disease('flu', set( "fever|headache|muscle aches|returning fever".split("|")) ), Disease('ebola', set( "tiredness|death|bruising over 90% of body|black blood".split("|")) ), ] # note: for Python 2, use "raw_input" instead of input symptoms = input("Please enter symptoms separated by commas: ") symptoms = symptoms.lower() symptoms = symptoms.split(",") possible = [] for symptom in symptoms: for disease in known_diseases: if symptom in disease.symptoms: possible.append(disease.name) if possible: print("You may have these diseases:") print(*possible) else: print("Good news! You're going to have a disease named after you!") Obviously in a real project, you would read the diseases from a file, or store them in a database. > b)Once I get that working, could anyone point me to good code already > written in Python such that I could have a model (for syntax and overall > structure) for figuring out how to make the computer evaluate more factors > such as: patient age, patient history, and even downloading archival data > for patients in the same demographic group? Well, I must say you're certainly ambitious! This is a *hard problem*, which is why expert systems usually cost a lot of money. Start by writing down how a human doctor would combine these pieces of information. Think about whether there are "anti-indicators", e.g. "if the patient doesn't have spots, it can't be measles!" (or maybe it can, I'm not a doctor...). Age, history, demographics, etc. can be treated just like symptoms. "If the patient is male, he can't be pregnant." (Although there are such things as false pregnancies, and even men can get that!) My guess is that doctors will first try to think of all the diseases it could be, and then eliminate those it can't be, and then take a probabilistic estimate (i.e. a guess) from those left over. E.g.: If the patient has the symptoms of ebola, and has been to Africa in the last month, or works with monkeys or in germ warfare, then the chances of ebola are 95%; otherwise the chances of ebola are 1%. Google on Bayesian probability and Bayes Theorem. Also look at fuzzy logic. That's another good approach for expert system problem solving. The problem you are likely to face is not that there's no good way to decide which diseases are likely, but that there are too many competing ways. Good luck! -- Steven From 0101amt at gmail.com Mon Jun 13 19:28:36 2011 From: 0101amt at gmail.com (amt) Date: Mon, 13 Jun 2011 20:28:36 +0300 Subject: [Tutor] Floating point exercise 3 from Learn python the hard way Message-ID: Hello, I am a python beginner currently learning from "Learn python the hard way". I'm stuck at exercise 3 and I would like if it's possible to get some help so I can move on. Here is the source code: 1 print "I will now count my chickens:" 2 print "Hens", 25 + 30 /6 3 print "Roosters", 100 - 25 * 3 % 4 #Output is 97 4 print "Now I will count the eggs:" 5 print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6 #Output needs to be 6,83 but Python give me 7 6 print "Is it true that 3 + 2 < 5 - 7? " 7 print 3 + 2 < 5 - 7 8 print "What is 3 + 2?", 3 + 2 9 print "What is 5 - 7?", 5-7 10 print "Oh, that's why it's False." 11 print "How about some more. " 12 print "Is it greater?", 5 > -2 13 print "Is it greater or equal?", 5 >= -2 14 print "Is it less or equal?", 5 <= -2 The author says " Notice the math seems ?wrong?? There are no fractions, only whole numbers. Find out why by researching what a ?floating point? number is." I have to rewrite it to use floating point numbers so it's more accurate. I have read the lines of code and only line 3 and 5 needs to be changed. I came up with: print "Roosters", 100 - float(25) * 3 % 4 This is for line 3 so it is more precised. Is it correct what I did? What do I have to do for line 5? Thanks in advance! Regards, amt. -------------- next part -------------- An HTML attachment was scrubbed... URL: From sulinet at postafiok.hu Mon Jun 13 20:07:43 2011 From: sulinet at postafiok.hu (=?ISO-8859-1?Q?V=E1las_P=E9ter?=) Date: Mon, 13 Jun 2011 20:07:43 +0200 Subject: [Tutor] Floating point exercise 3 from Learn python the hard way In-Reply-To: References: Message-ID: 2011/6/13 amt <0101amt at gmail.com> > I came up with: > print "Roosters", 100 - float(25) * 3 % 4 > > This is for line 3 so it is more precised. Is it correct what I did? I don't think so. All the operations in this line are for integers. % means the remainder of the division, so according to the precedence, the original may be parenthesed as 100-(25*3%4), which is really 97 (75 divided by 4 is 18, and 3 remains). > What do I have to do for line 5? > Hard to say without you share your Python version with us. Division behaves differently in P2.x and P3.x Also note that besides float() there is a more simple way to make a float from an integer: write 1.0 instead of 1, and it becomes a float as well as the result of the operation. Using the function is good if you work with a variable. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Jun 13 20:26:27 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 13 Jun 2011 19:26:27 +0100 Subject: [Tutor] Floating point exercise 3 from Learn python the hard way References: Message-ID: "amt" <0101amt at gmail.com> wrote 1 print "I will now count my chickens:" 2 print "Hens", 25 + 30 /6 3 print "Roosters", 100 - 25 * 3 % 4 #Output is 97 4 print "Now I will count the eggs:" 5 print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6 #Output needs to be 6,83 but Python give me 7 6 print "Is it true that 3 + 2 < 5 - 7? " 7 print 3 + 2 < 5 - 7 8 print "What is 3 + 2?", 3 + 2 9 print "What is 5 - 7?", 5-7 10 print "Oh, that's why it's False." 11 print "How about some more. " 12 print "Is it greater?", 5 > -2 13 print "Is it greater or equal?", 5 >= -2 14 print "Is it less or equal?", 5 <= -2 > I have to rewrite it to use floating point numbers so it's more > accurate. I > have read the lines of code and only line 3 and 5 needs to be > changed. Some things to consider: Can you explain your reasoning? Why do you think line 3 needs to be changed? Why line 5? > I came up with: > print "Roosters", 100 - float(25) * 3 % 4 > > This is for line 3 so it is more precised. In what way do you think this is more precise? I don't understand your comment on line 5. Why would the answer be 6.83? Can you add parentheses to the expression showing how you arrive at 6.83? HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From 0101amt at gmail.com Mon Jun 13 20:34:44 2011 From: 0101amt at gmail.com (amt) Date: Mon, 13 Jun 2011 21:34:44 +0300 Subject: [Tutor] Floating point exercise 3 from Learn python the hard way In-Reply-To: References: Message-ID: Hello, my version is Python 2.6.6 (r266:84292, Sep 15 2010, 15:52:39). The book only talks about Python 2.x. So, how do I solve the exercise? 3. print "Roosters", 100 - 25 * 3 % 4.00 5. print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4.00 + 6 Is this correct? I'm a bit confused at line 5 because python returns 6,75 and wolfram alpha tells me the result of that expression is 6,83. Sorry, my math is VERY rusty. -------------- next part -------------- An HTML attachment was scrubbed... URL: From emadnawfal at gmail.com Mon Jun 13 20:49:35 2011 From: emadnawfal at gmail.com (=?UTF-8?B?RW1hZCBOYXdmYWwgKNi52YXZgCDZhtmI2YHZhCDZgNin2K8p?=) Date: Mon, 13 Jun 2011 21:49:35 +0300 Subject: [Tutor] Medical Decision-Making Question In-Reply-To: References: Message-ID: On Mon, Jun 13, 2011 at 5:22 PM, Fred G wrote: > Hello-- > > I'm a pre-med student interested in decision-making as applied to medical > decisions. I am trying to build a medical decision-making algorithm and am > pretty stuck on a few things. > > I've built a file that contains a list of many diseases and their > associated symptoms. For example, here are the column headers and two > sample rows (the "|" = "or"): > Disease Symptoms > Cold > sore_throat|runny_nose|congestion|cough|aches|slight_fever > Flu > sore_throat|fever|headache|muscle_aches|soreness|congestion|cough|returning_fever > > My questions are the following: > a) How's the best way to make it so I can have a user type in a list of > symptoms and then have the computer tell the user the possible diseases that > share those symptoms? In other words, on a high-level I have a pretty good > idea of what I want my algorithm to do-- but I need help implementing the > basic version first. I'd like to do the following: > >>>Please enter a list of symptoms > >>>[user_input] > >>>Possible diseases include: x, y, z > > b)Once I get that working, could anyone point me to good code already > written in Python such that I could have a model (for syntax and overall > structure) for figuring out how to make the computer evaluate more factors > such as: patient age, patient history, and even downloading archival data > for patients in the same demographic group? > > Thanks! > > There are lots of machine learning algorithms that do exactly what you > want. Take a look at memory-based learning, one of the easiest to understand > ML algorithms, and its TiMBL implementation here: > http://ilk.uvt.nl/timbl/ > > and the Python binding here: http://ilk.uvt.nl/~sander/software/python-timbl.html > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From 0101amt at gmail.com Mon Jun 13 21:28:37 2011 From: 0101amt at gmail.com (amt) Date: Mon, 13 Jun 2011 22:28:37 +0300 Subject: [Tutor] Floating point exercise 3 from Learn python the hard way In-Reply-To: References: Message-ID: > > > Can you explain your reasoning? Why do you think line 3 needs > to be changed? Why line 5? Well the exercise says: "Rewrite ex3.py to use floating point numbers so it?s more accurate (hint: 20.0 is floating point)." I am honestly confused. I have read the exercise and found three lines that could use the floating point(2,3 and line 5). This is were the confusion is appearing. I can understand why at line 5 I use floating point. 6,75 is more precise than saying 7. But I can't understand at line 2 and 3. I mean it makes no difference for me. Saying 30 or 30.0 is the same thing. As well as saying 97 or 97.0. > > I came up with: >> print "Roosters", 100 - float(25) * 3 % 4 >> >> This is for line 3 so it is more precised. >> > > In what way do you think this is more precise? > As I said, I am confused when it comes to line 2 and 3. But I think having more digits after the " ." makes it more precise. > > I don't understand your comment on line 5. > Why would the answer be 6.83? > Can you add parentheses to the expression > showing how you arrive at 6.83? > The answer at line 5 is 7 because I have integers and I think Python approximates. I have done line 5 with pencil and paper: 3 + 2 + 1 - 5 = 1, 1 + 4%2 = 1, 1 - (1/4)= 1, 1 + 6 = 7 If I use floating point the right answer will be 6,75 but I don't know how to get to this answer. On paper I got 7 not 6,75. I'm horrible at math right now, so please forgive me. > 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 > Thanks for helping me out! -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Mon Jun 13 22:44:26 2011 From: emile at fenx.com (Emile van Sebille) Date: Mon, 13 Jun 2011 13:44:26 -0700 Subject: [Tutor] [OT] Re: Floating Point Craziness In-Reply-To: References: <015b01cc2906$abf4ee00$03deca00$@gmail.com> <4DF4F3A1.3010706@pearwood.info> <18488783263.20110612135357@columbus.rr.com> Message-ID: On 6/12/2011 1:55 PM Andre' Walker-Loud said... > Hi Alan, > >>> * Or you just get used to the fact that some numbers are not exact in >>> floating point. >> >> This got me thinking. How many decimal places do you need to >> accurately, say, aim a laser somewhere in a 180 degree arc accurately >> enough to hit a dime on the surface of the moon? > > Here is a quick back of the envelope estimate for you. (While I am still learning the Python, I can answer this one!) > > The angle subtended by a dime on the earth is (approximately) given by > > sin( theta ) = d / sqrt( R^2 + d^2 ) > > where > > d = 1 cm (the diameter of a dime) > R = 384,403 km (the average distance from the center of the earth to the center of the moon - the moon traverses an elliptical path about the earth) > > To make the approximation simple, take advantage of the series expansion for sin (theta) and 1 / sqrt(R^2 + d^2) > > first > > d / sqrt( R^2 + d^2 ) = d / R * 1 / sqrt(1 + d^2 / R^2 ) > ~= d / R * (1 - 1/2 * d^2 / R^2 + ...) > > now > > d / R = 1 * e-2 / (384403 * e3) > ~= 3 * e-11 > > so the d^2 / R^2 correction will be very small, and won't effect the determination. So we now have > > sin (theta) ~= d / R > > This will be a very small angle. The next approximation to make is for small angles > > sin (theta) ~= theta + ... > > leaving us with > > theta ~= d / R > > > To be approximate, assume the precision you need is equal to the size of the dime. This means you need an precision of > > d theta ~= d/R ~= 3 * e-11 ( = 3 * 10^{-11} if you aren't familiar with the "e" notation) > > this is the minimum precision you would need in both the "x" and "y" direction to accurately hit the dime on the moon with your laser (at its average distance). > > Corrections to this estimate will come from the fact that the moon's radius is ~1737 km and the earth's radius is ~6370 km, so you are actually this much closer (R is this much smaller). > > Of course both the earth is spinning and the moon is moving relative to us, so you would have to account for those extra corrections as well. > > > Hope that wasn't too much info, > Of course not. I enjoyed it. However, don't you need to work divergence in, as per wikipedia, "...At the Moon's surface, the beam is only about 6.5 kilometers (four miles) wide[6] and scientists liken the task of aiming the beam to using a rifle to hit a moving dime 3 kilometers (two miles) away." (http://en.wikipedia.org/wiki/Lunar_Laser_Ranging_experiment) Emile From wprins at gmail.com Mon Jun 13 23:10:54 2011 From: wprins at gmail.com (Walter Prins) Date: Mon, 13 Jun 2011 22:10:54 +0100 Subject: [Tutor] Floating point exercise 3 from Learn python the hard way In-Reply-To: References: Message-ID: Hi, On 13 June 2011 20:28, amt <0101amt at gmail.com> wrote: > >> Can you explain your reasoning? Why do you think line 3 needs >> to be changed? Why line 5? > > > Well the exercise says: "Rewrite ex3.py to use floating point numbers so > it?s more accurate (hint: 20.0 is floating point)." > > I am honestly confused. I have read the exercise and found three lines that > could use the floating point(2,3 and line 5). This is were the confusion is > appearing. I can understand why at line 5 I use floating point. 6,75 is more > precise than saying 7. But I can't understand at line 2 and 3. I mean it > makes no difference for me. Saying 30 or 30.0 is the same thing. As well as > saying 97 or 97.0. > OK, the point is that, although to *you* 30 and 30.0 is the same thing, the fact is that to Python they're not the same thing. Cast yourself back to your 1st and 2nd grade math classes, where you learned about integer (whole numbers) and integer maths (e.g integer division), then later on fractions and rational numbers, and later still, irrational numbers and so on. The point is that Python similary interprets a number literal as a certain type, and has a set of rules to decide how to handle arithmetic based on the types of numbers it sees. An expression such as: 1 / 2 consists of 2 integers and a division operator. Now as humans we can instantly interpret this in several ways. Python will have one way that it uses, unless you explicitly force it modify its interpretation. Introducing a float() call converts the paramter so that the output is a float, thus affecting the rest of the expression. Similarly, putting a "dot zero" after a number forces Python to interpret it as a floating point number, thus again affecting the rest of the expression evaluation. Hope that helps. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From kinuthia.muchane at gmail.com Mon Jun 13 23:19:52 2011 From: kinuthia.muchane at gmail.com (=?UTF-8?B?S8SpbsWpdGhpYSBNxaljaGFuZQ==?=) Date: Tue, 14 Jun 2011 00:19:52 +0300 Subject: [Tutor] Floating Point Craziness In-Reply-To: <4DF4F3A1.3010706@pearwood.info> References: <015b01cc2906$abf4ee00$03deca00$@gmail.com> <4DF4F3A1.3010706@pearwood.info> Message-ID: <4DF67EF8.8000806@gmail.com> On 06/12/2011 08:13 PM, Steven D'Aprano wrote: > Ryan Strunk wrote: >> Hi everyone, >> I'm designing a timeline. When the user presses the right arrow, 0.1 is >> added to the current position. The user can add events to the >> timeline, and >> can later scroll back across those events to see what they are. But >> something I absolutely don't understand is happening: >> I used the program to place events at 1.1, 2.1, and 3.1. Here is the >> end of >> the debug output for arrowing to 3.1 and placing the event: >> position = 2.7 >> position = 2.8 >> position = 2.9 >> position = 3.0 >> position = 3.1 >> event placed. >> Everything appears straight forward. > > > It only *appears* straight forward, it actually isn't. That's because > the printed output is rounded so as to look nice. Compare: > > >>> x = 1/10.0 > >>> print(x) # displayed as nicely as possible > 0.1 > >>> print('%.25f' % x) # display 25 decimal places > 0.1000000000000000055511151 > > > For speed and simplicity, floats are stored by the computer using > fractional powers of two. That's fine for numbers which are powers of > two (1/2, 1/4, 1/256, and sums of such) but numbers that humans like > to use tend to be powers of 10, not 2. > > Unfortunately, many common fractions cannot be written exactly in > binary. You're probably familiar with the fact that fractions like 1/3 > cannot be written exactly in decimal: > > 1/3 = 0.33333333... goes on forever Does it? :-) > > The same is true for some numbers in binary: > > 1/10 in decimal = 1/16 + 1/32 + 1/256 + ... > > also goes on forever. Written in fractional bits: > > 1/10 decimal = 0.00011001100110011... in binary > > Since floats can only store a finite number of bits, 1/10 cannot be > stored exactly. It turns out that the number stored is a tiny bit > larger than 1/10: > > >>> Fraction.from_float(0.1) - Fraction(1)/10 > Fraction(1, 180143985094819840) > > Rounding doesn't help: 0.1 is already rounded as close to 1/10 as it > can possibly get. > > Now, when you print the dictionary containing those floats, Python > displays (almost) the full precision: > > >>> print {1: 0.1} > {1: 0.10000000000000001} > > > In newer versions of Python, it may do a nicer job of printing the > float so that the true value is hidden. E.g. in Python 3.1 I see: > > > >>> print({1: 0.1}) > {1: 0.1} > > but don't be fooled: Python's print display is pulling the wool over > your eyes, the actual value is closer to 0.10000000000000001. > > > One consequence of that is that adding 0.1 ten times does not give 1 > exactly, but slightly less than 1: > > >>> x = 0.1 > >>> 1 - sum([x]*10) > 1.1102230246251565e-16 > > > (P.S. this is why you should never use floats for currency. All those > missing and excess fractions of a cent add up to real money.) > > > To avoid this, you can: > > > * Upgrade to a newer version of Python that lies to you more often, so > that you can go on living in blissful ignorance (until such time as > you run into a more serious problem with floats); > > * Use the fraction module, or the decimal module, but they are slower > than floats; or > > * Instead of counting your timeline in increments of 0.1, scale > everything by 10 so the increment is 1. > > That is, instead of: > > 2.0 2.1 2.2 2.3 ... > > you will have > > 20 21 22 23 24 ... > > > * Or you just get used to the fact that some numbers are not exact in > floating point. > > > > -- K?n?thia From alan.gauld at btinternet.com Mon Jun 13 23:27:33 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 13 Jun 2011 22:27:33 +0100 Subject: [Tutor] Floating point exercise 3 from Learn python the hard way References: Message-ID: "amt" <0101amt at gmail.com> wrote in message > I am honestly confused. I have read the exercise and found > three lines that could use the floating point(2,3 and line 5). > I can understand why at line 5 I use floating point. 6,75 is more > precise than saying 7. Exactly, no problem with line 5 (except the odd comment about 6.83) > But I can't understand at line 2 and 3. I mean it makes no > difference > for me. Saying 30 or 30.0 is the same thing. > As well as saying 97 or 97.0. Precisely, thats why I asked the question. >> print "Roosters", 100 - float(25) * 3 % 4 >> >> This is for line 3 so it is more precised. >> > > In what way do you think this is more precise? > > As I said, I am confused when it comes to line 2 and 3. > But I think having more digits after the " ." makes it more > precise. It depends on the definition of precision. As per a recent thread floating point numbers are less precise in an absolute sense for integer values because they are stored as approximations, but the representation with multiple decimal places is a greater precision mathematically speaking. > I don't understand your comment on line 5. > Why would the answer be 6.83? > The answer at line 5 is 7 because I have integers > and I think Python approximates. It doesn't approximate but it does use integer arithmetic exactly. > I have done line 5 with pencil and paper: > 3 + 2 + 1 - 5 = 1, 1+ 4%2 = 1, 1 - (1/4)= 1, 1 + 6 = 7 Right, that's the integer version. > If I use floating point the right answer will be 6,75 but I don't know how to get to this answer. > 3 + 2 + 1 - 5 = 1, > 1+ 4%2 = 1, > 1 - (1/4)= 1, -> 1 - 0.25 = 0.75 0.75 + 6 = 6.75 HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From kinuthia.muchane at gmail.com Mon Jun 13 23:28:08 2011 From: kinuthia.muchane at gmail.com (=?UTF-8?B?S8SpbsWpdGhpYSBNxaljaGFuZQ==?=) Date: Tue, 14 Jun 2011 00:28:08 +0300 Subject: [Tutor] Lists In-Reply-To: <01ee01cc2946$2886e380$7994aa80$@rr.com> References: <512866.29728.qm@web59401.mail.ac4.yahoo.com> <4DF1F11E.5030808@pearwood.info> <4DF2D447.7030708@pearwood.info> <01ee01cc2946$2886e380$7994aa80$@rr.com> Message-ID: <4DF680E8.1030008@gmail.com> On 06/13/2011 12:17 AM, R. Berman wrote: > Having followed this absurd thread from its beginning hopefully to this, the end of it. Everyone replying to your diatribe has been incredibly polite to you. One of the moderators tried to explain the obvious to you. This is a Python group. Python is to most of us a delightful language. To others it is a snake. It is not a god a priest or a rabbi. You are arguing religion and issues pertaining to very elementary sophistry. You are acting the fool. Enough. You have crossed the line and have become the 'Troll mediocre'. Go forth and spew your venom elsewhere. Hehehehe!! :-) I could not reply because I do not know any big words. > Robert > >> -----Original Message----- >> From: tutor-bounces+bermanrl=cfl.rr.com at python.org [mailto:tutor- >> bounces+bermanrl=cfl.rr.com at python.org] On Behalf Of Piotr Kaminski >> Sent: Sunday, June 12, 2011 4:06 PM >> To: tutor at python.org >> Subject: Re: [Tutor] Lists >> >> Dnia 11-06-2011 o 17:51:03 Piotr Kami?ski >> napisa?(a): >> >>> Dnia 11-06-2011 o 17:30:50 Alan Gauld >>> napisa?(a): >>> >>>> "Piotr Kami?ski" wrote >>>> >>>>>>> This is a *technical* list, as I understand it, solely >> dedicated to >> ... >> >>>> Since this seems to be something we can all agree on >>>> can we consider this discussion closed and get back >>>> to Python? >>>> >>>> If you wish to continue the philosophical debate please >>>> take it off list. >>>> >>>> Alan g. >>>> List moderator. >>> >>> OK. >>> >>> I like this style of talking - no feelings hurt, *including >> Christian >>> ones as well*. >>> Thank you. >>> >>> Piotr. >> >> To be perfectly clear, as I've got the impression that my words were >> interpreted in various ways by different people: the "thank you" in >> my >> reply to Alan Gauld's message, *is not* a sign of >> subservience/weakness, >> my seeking his approval or a similar attitude. >> >> I thanked him strictly for *the *polite* style of talking* on the >> list; I >> do not expect Alan Gauld or any other Tutor list user to agree with >> or >> approve of any of my philosophical views. >> >> In other words, *in my culture* thanking someone for something (and, >> by >> the way: apologising to someone for a mistake made) is strictly a >> sign of >> *politeness*, not of some weakness, defeat, being a losing party, a >> member >> of a lower social class etc. >> >> Over and out. >> >> Piotr >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > -- > I am using the free version of SPAMfighter. > We are a community of 7 million users fighting spam. > SPAMfighter has removed 237 of my spam emails to date. > Get the free SPAMfighter here: http://www.spamfighter.com/len > > The Professional version does not have this message > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- K?n?thia From bayespokerguy at gmail.com Tue Jun 14 00:35:04 2011 From: bayespokerguy at gmail.com (Fred G) Date: Mon, 13 Jun 2011 18:35:04 -0400 Subject: [Tutor] Medical Decision-Making Question Message-ID: Thanks guys for all the feedback. re Jim's comments: I completely agree that the difference b/t "slight" fever and "returning" fever, etc will pose some problems. My hunch is that initially I'll just do something like make "fever" be the only one for now w/ the obvious caveat that a few more diseases would not be eliminated than actually should be. Building on this, another challenging problem will be how to code the fact that when a symptom occurs early it usually means something else than if it returns later in the course of an illness. I'm not 100% sure how I'll handle this, but I think the first priority is getting access to a dataset and getting the bot up and running before I focus on this. re Steve's comments: hmm, sounds like I really should take an AI class. This problem is just really exciting and driving me, and I'm glad you pointed out that this will probably take a lot more time than I had predicted. I'm pretty motivated personally to solve it. I had a few more questions about your code: a) Why did you choose not to use a dictionary to store the diseases (keys) and their possible values (symptoms)? That seemed the most intuitive to me, like, what I want to do is have it such that we enter in a few symptoms and then all the keys without those symptoms are automatically eliminated. I've been off and on teaching myself python for the last 6 months and have experience in Java. I mean, I think I want a structure like this: 1) Main class -this class calls the diagnose_disease class based on the set of entered symptoms and demographic information (ie age, location, season (winter, spring, fall, etc), patient history) 2) Diagnose_disease class -this is the heart of the project. Based on the entered symptoms, it keeps narrowing down the list of possible diseases. Ideally it would ask follow-up questions of the user to even further narrow down the list of possible diseases, but that's going to have to wait until I get the rest working. 3) Dictionary Class -this class contains a *dictionary??* of all possible diseases and their associated symptoms. Assuming in a standardized form for now (such that "slight_fever" and "returning_fever" are simply coded as "fever" for now, etc). does this seem like the best way to go about it? re: James. I completely agree that my first step should be getting access to a dataset. I need to know the format, etc of it before I really can progress on this. -------------- next part -------------- An HTML attachment was scrubbed... URL: From foobar8 at gmail.com Tue Jun 14 01:15:41 2011 From: foobar8 at gmail.com (=?ISO-8859-1?Q?Siim_M=E4rtmaa?=) Date: Tue, 14 Jun 2011 02:15:41 +0300 Subject: [Tutor] Excited about python In-Reply-To: <20110610124101.55700@gmx.com> References: <20110610124101.55700@gmx.com> Message-ID: 2011/6/10 Kaustubh Pratap chand : > Can you recommend a book for a person like me which comes with a C > background and the book covers all essential algoithmic methods and > examples? You, might find "Data Structures and Algorithms with Object-Oriented Design Patterns in Python" by Bruno R. Preiss useful. http://www.brpreiss.com/books/opus7/ It is not about python or how it differs from c, but about algorithms, with examples in python. The book is meant for cs students. There are a lot of source examples and other versions in C++, Java, C#, Ruby, Lua, Perl, PHP. So you can compare an avl-tree implementation in python, php and c++. From steve at pearwood.info Tue Jun 14 01:16:00 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 14 Jun 2011 09:16:00 +1000 Subject: [Tutor] Floating Point Craziness In-Reply-To: <4DF67EF8.8000806@gmail.com> References: <015b01cc2906$abf4ee00$03deca00$@gmail.com> <4DF4F3A1.3010706@pearwood.info> <4DF67EF8.8000806@gmail.com> Message-ID: <4DF69A30.4060009@pearwood.info> K?n?thia M?chane wrote: > On 06/12/2011 08:13 PM, Steven D'Aprano wrote: >> Unfortunately, many common fractions cannot be written exactly in >> binary. You're probably familiar with the fact that fractions like 1/3 >> cannot be written exactly in decimal: >> >> 1/3 = 0.33333333... goes on forever > Does it? :-) Yes. 0.3 is not 1/3, it is 3/10, not 3/9. 0.33 is not 1/3, it is 33/100, not 33/99. 0.333 is not 1/3, it is 333/1000, not 333/999. ... 0.3333333333 is not 1/3, it is 3333333333/10000000000 instead of 3333333333/9999999999. And so forth. No matter how many 3s you have, it will always be just short of 1/3. Anything less than an infinite number of decimal places is not 1/3 exactly, but some approximation less than 1/3. -- Steven From alan.gauld at btinternet.com Tue Jun 14 02:00:17 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 14 Jun 2011 01:00:17 +0100 Subject: [Tutor] Medical Decision-Making Question References: Message-ID: "Fred G" wrote > re Steve's comments: hmm, sounds like I really should take an AI > class. > This problem is just really exciting and driving me, and I'm glad > you > pointed out that this will probably take a lot more time than I had > predicted. I assume you know that there are several commerial packages designed for the use of medical staff in surgeries etc? Not being a doctor I can't comment on their quality or accuracy but they cost big bucks... -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From weaselkeeper at gmail.com Tue Jun 14 03:25:33 2011 From: weaselkeeper at gmail.com (Jim Richardson) Date: Mon, 13 Jun 2011 18:25:33 -0700 Subject: [Tutor] Medical Decision-Making Question In-Reply-To: References: Message-ID: On Mon, Jun 13, 2011 at 3:35 PM, Fred G wrote: > Thanks guys for all the feedback. > re Jim's comments: I completely agree that the difference b/t "slight" fever > and "returning" fever, etc will pose some problems. ?My hunch is that > initially I'll just do something like make "fever" be the only one for now > w/ the obvious caveat that a few more diseases would not be eliminated than > actually should be. ?Building on this, another challenging problem will be > how to code the fact that when a symptom occurs early it usually means > something else than if it returns later in the course of an illness. ?I'm > not 100% sure how I'll handle this, but I think the first priority is > getting access to a dataset and getting the bot up and running before I > focus on this. > re Steve's comments: hmm, sounds like I really should take an AI class. > ?This problem is just really exciting and driving me, and I'm glad you > pointed out that this will probably take a lot more time than I had > predicted. ?I'm pretty motivated personally to solve it. ?I had a few more > questions about your code: > a) Why did you choose not to use a dictionary to store the diseases (keys) > and their possible values (symptoms)? ?That seemed the most intuitive to me, > like, what I want to do is have it such that we enter in a few symptoms and > then all the keys without those symptoms are automatically eliminated. ?I've > been off and on teaching myself python for the last 6 months and have > experience in Java. ?I mean, I think I want a structure like this: If you are going to use dicts, I'd suggest you flip it around, have the symptom be the key, and the list of diseases related to a given symptom, be the value. But that sounds more like a map:reduce problem or an sql query problem than a dict one. I haven't used it in over 20 years, and I was no expert then, but this sounds like a prolog problem :) To maintain the pythonical nature of the list, https://bitbucket.org/cfbolz/pyrolog/ is something I found. Looks interesting. > 1) Main class > -this class calls the diagnose_disease class based on the set of entered > symptoms and demographic information (ie age, location, season (winter, > spring, fall, etc), patient history) > 2) Diagnose_disease class > -this is the heart of the project. ?Based on the entered symptoms, it keeps > narrowing down the list of possible diseases. ?Ideally it would ask > follow-up questions of the user to even further narrow down the list of > possible diseases, but that's going to have to wait until I get the rest > working. > 3) Dictionary Class > -this class contains a *dictionary??* of all possible diseases and their > associated symptoms. ?Assuming in a standardized form for now (such that > "slight_fever" and "returning_fever" are simply coded as "fever" for now, > etc). > does this seem like the best way to go about it? > re: James. ?I completely agree that my first step should be getting access > to a dataset. ?I need to know the format, etc of it before I really can > progress on this. > > -- http://neon-buddha.net From walksloud at gmail.com Tue Jun 14 03:29:18 2011 From: walksloud at gmail.com (Andre' Walker-Loud) Date: Mon, 13 Jun 2011 18:29:18 -0700 Subject: [Tutor] [OT] Re: Floating Point Craziness In-Reply-To: References: <015b01cc2906$abf4ee00$03deca00$@gmail.com> <4DF4F3A1.3010706@pearwood.info> <18488783263.20110612135357@columbus.rr.com> Message-ID: On Jun 13, 2011, at 1:44 PM, Emile van Sebille wrote: > On 6/12/2011 1:55 PM Andre' Walker-Loud said... >> Hi Alan, >> >>>> * Or you just get used to the fact that some numbers are not exact in >>>> floating point. >>> >>> This got me thinking. How many decimal places do you need to >>> accurately, say, aim a laser somewhere in a 180 degree arc accurately >>> enough to hit a dime on the surface of the moon? >> >> Here is a quick back of the envelope estimate for you. (While I am still learning the Python, I can answer this one!) >> >> The angle subtended by a dime on the earth is (approximately) given by >> >> sin( theta ) = d / sqrt( R^2 + d^2 ) >> >> where >> >> d = 1 cm (the diameter of a dime) >> R = 384,403 km (the average distance from the center of the earth to the center of the moon - the moon traverses an elliptical path about the earth) >> >> To make the approximation simple, take advantage of the series expansion for sin (theta) and 1 / sqrt(R^2 + d^2) >> >> first >> >> d / sqrt( R^2 + d^2 ) = d / R * 1 / sqrt(1 + d^2 / R^2 ) >> ~= d / R * (1 - 1/2 * d^2 / R^2 + ...) >> >> now >> >> d / R = 1 * e-2 / (384403 * e3) >> ~= 3 * e-11 >> >> so the d^2 / R^2 correction will be very small, and won't effect the determination. So we now have >> >> sin (theta) ~= d / R >> >> This will be a very small angle. The next approximation to make is for small angles >> >> sin (theta) ~= theta + ... >> >> leaving us with >> >> theta ~= d / R >> >> >> To be approximate, assume the precision you need is equal to the size of the dime. This means you need an precision of >> >> d theta ~= d/R ~= 3 * e-11 ( = 3 * 10^{-11} if you aren't familiar with the "e" notation) >> >> this is the minimum precision you would need in both the "x" and "y" direction to accurately hit the dime on the moon with your laser (at its average distance). >> >> Corrections to this estimate will come from the fact that the moon's radius is ~1737 km and the earth's radius is ~6370 km, so you are actually this much closer (R is this much smaller). >> >> Of course both the earth is spinning and the moon is moving relative to us, so you would have to account for those extra corrections as well. >> >> >> Hope that wasn't too much info, >> > > > Of course not. I enjoyed it. However, don't you need to work divergence in, as per wikipedia, "...At the Moon's surface, the beam is only about 6.5 kilometers (four miles) wide[6] and scientists liken the task of aiming the beam to using a rifle to hit a moving dime 3 kilometers (two miles) away." > > (http://en.wikipedia.org/wiki/Lunar_Laser_Ranging_experiment) Of course, I was performing just the 'theoretical' calculation. It is up to others to dtermine if it is actually practical :) Andre > > Emile > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From amonroe at columbus.rr.com Tue Jun 14 04:52:20 2011 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Mon, 13 Jun 2011 22:52:20 -0400 Subject: [Tutor] Medical Decision-Making Question In-Reply-To: References: Message-ID: <113607486148.20110613225220@columbus.rr.com> > a) How's the best way to make it so I can have a user type in a list of > symptoms and then have the computer tell the user the possible diseases that > share those symptoms? Good question. The first decent idea that came to mind was searching through a cartesian join of all diseases & symptoms: { (disease1, symptom1), (disease1, symptom2), (disease2, symptom1), (disease2, symptom2) } Searching for (flu, runny_nose) would not find anything (given the sample data in your original message) so you could rule out flu. Alan From 0101amt at gmail.com Tue Jun 14 15:20:43 2011 From: 0101amt at gmail.com (amt) Date: Tue, 14 Jun 2011 16:20:43 +0300 Subject: [Tutor] Floating point exercise 3 from Learn python the hard way In-Reply-To: References: Message-ID: On Tue, Jun 14, 2011 at 12:27 AM, Alan Gauld wrote: > > I can understand why at line 5 I use floating point. 6,75 is more >> precise than saying 7. >> > > Exactly, no problem with line 5 (except the odd comment about 6.83) The comment on line 5 was a mistake. > > But I can't understand at line 2 and 3. I mean it makes no difference >> for me. Saying 30 or 30.0 is the same thing. >> As well as saying 97 or 97.0. >> > > Precisely, thats why I asked the question. > > As a beginner at line 2 and 3 I see no point of using floating numbers except the fact to serve as an example that if I have a floating point number it affects the rest of the expression evaluation. So, should I keep them or not?It's unclear to me and sadly the author of the book doesn't provide the solutions to the exercises. The only way I can verify myself is using this list. Regards, amt. -------------- next part -------------- An HTML attachment was scrubbed... URL: From lisi.reisz at gmail.com Tue Jun 14 16:37:46 2011 From: lisi.reisz at gmail.com (Lisi) Date: Tue, 14 Jun 2011 15:37:46 +0100 Subject: [Tutor] Floating point exercise 3 from Learn python the hard way In-Reply-To: References: Message-ID: <201106141537.46819.lisi.reisz@gmail.com> I too am working through Learn Python the Hard Way. On Tuesday 14 June 2011 14:20:43 amt wrote: > sadly the author of the > book doesn't provide the solutions to the exercises. He gives the answers to the questions in the main block of the chapter, just not for the extra credit questions. I have taken the attitude that if I can't do any of the extra credit questions, having successfully done the questions in the chapter, I pass on and will come back to them when I know a bit more. Lisi From sander.sweers at gmail.com Tue Jun 14 16:55:10 2011 From: sander.sweers at gmail.com (Sander Sweers) Date: Tue, 14 Jun 2011 16:55:10 +0200 Subject: [Tutor] Floating point exercise 3 from Learn python the hard way In-Reply-To: References: Message-ID: On 14 June 2011 15:20, amt <0101amt at gmail.com> wrote: >>> But I can't understand at line 2 and 3. I mean it makes no difference >>> for me. Saying 30 or 30.0 is the same thing. >>> As well as saying 97 or 97.0. >> >> Precisely, thats why I asked the question. > > As a beginner at line 2 and 3 I see no point of using floating numbers > except the fact to serve as an example? that if I have a floating point > number it affects the rest of the expression evaluation. Correct, 2 and 3 do not need floating point arithmetic. > So, should I keep them or not?It's unclear to me and sadly the author of the > book doesn't provide the solutions to the exercises. The only way I can > verify myself is using this list. If you tell Python to divide 2 integers (whole numbers) by default it will use integer arithmetic. So in your calculation on line 5 you get a result of 7 as Python does not switch to floating point arithmetic. You can ask Python to use floating point arithmetic a couple of ways. For example if you want 2 divided by 3 you can tell Python to use floating point arithmetic by: --1-- >>> float(2) / 3 0.6666666666666666 >>> float(20) / 7 2.857142857142857 --2-- >>> 2.0 / 3 0.6666666666666666 >>> 20.0 / 7 2.857142857142857 What happens here is that Python on one side of the division has a floating point number. This will force it to use floating point arithmetic instead of integer. Generally the second form is used and the first is for demonstration purpose only. >>> 2 / 3 0 >>> 20 / 7 2 Here we have 2 integers and therefor Python uses integer arithmetic and gives 0 and 2 as result. This is because the results of the division can not be stored as an integer so everything after the decimal place gets cut off. In Python 3 this has been changed that by default it will do floating point arithmetic. You can also get this in Python 2 by importing division from __future__. The Python tutorial [1] on floating point arithmetic will give you much more info on floating point arithmatic in Python. Greets Sander [1] http://docs.python.org/tutorial/floatingpoint.html From 0101amt at gmail.com Tue Jun 14 17:46:31 2011 From: 0101amt at gmail.com (amt) Date: Tue, 14 Jun 2011 18:46:31 +0300 Subject: [Tutor] Floating point exercise 3 from Learn python the hard way In-Reply-To: References: Message-ID: Everything is clear now. Thank you for your replies. -------------- next part -------------- An HTML attachment was scrubbed... URL: From Craig.Prinn at bowebellhowell.com Tue Jun 14 20:40:10 2011 From: Craig.Prinn at bowebellhowell.com (Prinn, Craig) Date: Tue, 14 Jun 2011 14:40:10 -0400 Subject: [Tutor] trying to translate and ebcidic file Message-ID: <6B49A56A6E493F4EBA255F6F197F070F050E4FE26A@BBH-MAIL1.bbh.priv> I am looking for a way to translate and ebcidic file to ascii. Is there a pre-existing library for this, or do I need to do this from scratch? If from scratch and ideas on where to start? thanks Craig Prinn Document Solutions Manager Office Phone 919-767-6640 Cell Phone 410-320-9962 Fax 410-243-0973 3600 Clipper Mill Road Suite 404 Baltimore, MD 21211 -------------- next part -------------- An HTML attachment was scrubbed... URL: From susana.delgado_s at utzmg.edu.mx Tue Jun 14 20:59:49 2011 From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez) Date: Tue, 14 Jun 2011 13:59:49 -0500 Subject: [Tutor] Break stament issue Message-ID: Hello members! I'm doing a script that needs to loop to get some information, in order to do that I'm using modules from OGR and Mapnik. These to get data from shapefiles, but some of the files have 0 elements, I wrote a line to validate it, but it hasn't worked, so I added a break to keep working. When I run the scipt I got the next error: Traceback (most recent call last): File "", line 1, in import mapnik_punto_sin_duda File "C:\Python26\mapnik_punto_sin_duda.py", line 23 break ^ IndentationError: unexpected indent But I've read about this stamentet's use and I don't understand the reason I'm failing, the complete script is: import mapnik import os,fnmatch from mapnik import LineSymbolizer,PolygonSymbolizer,PointSymbolizer from osgeo import ogr,gdal,osr #Registra todos los drivers de GDAL file_list = [] #Crear variable para buscar dentro de carpetas en el sistema folders = None #Se asigna el directorio raiz donde se van buscar los archivos, se hace un recorrido en la raiz for root, folders, files in os.walk( "c:\\" ): #Agregar a la lista los elementos que traiga os.path.join, los archivos que terminen en extension .shp for filename in fnmatch.filter(files, '*.shp'): file_list.append(os.path.join(root, filename)) #Recorrer la lista que se creo for row, filepath in enumerate(file_list, start=1): #Dividir la ruta en dos: directorio y nombre de archivo dir(LineSymbolizer().stroke) shapeData = ogr.Open(filepath) shp = 'Error al abrir el archivo' +filepath if shapeData is None: print shp break else: layer = shapeData.GetLayer() defn = layer.GetLayerDefn() geo = defn.GetGeomType() (ruta, filename) = os.path.split(filepath) archivo = os.path.splitext(filename) i = archivo[0]+'.png' m = mapnik.Map(800,500,"+proj=latlong +datum=WGS84") m.background = mapnik.Color('#EBEBEB') s = mapnik.Style() r=mapnik.Rule() if geo == 3: print "Trabajando mapa "+ruta+"\\"+filename+" con geometria "+ str(geo) r.symbols.append(mapnik.PolygonSymbolizer(mapnik.Color('#EB784B'))) r.symbols.append(mapnik.LineSymbolizer(mapnik.Color('rgb(170%,170%,170%)'),0.9)) s.rules.append(r) m.append_style('My Style',s) lyr = mapnik.Layer('world',"+proj=latlong +datum=WGS84") lyr.datasource = mapnik.Shapefile(base=ruta,file=archivo[0]) lyr.styles.append('My Style') m.layers.append(lyr) m.zoom_to_box(lyr.envelope()) mapnik.render_to_file(m,i, 'png') print "La imagen " +i+ " fue creada." elif geo == 2: print "Trabajando mapa "+ruta+"\\"+filename+" con geometria "+ str(geo) r.symbols.append(mapnik.LineSymbolizer(mapnik.Color('#EB784B'),0.9)) s.rules.append(r) m.append_style('My Style',s) lyr = mapnik.Layer('world',"+proj=latlong +datum=WGS84") lyr.datasource = mapnik.Shapefile(base=ruta,file=archivo[0]) lyr.styles.append('My Style') m.layers.append(lyr) m.zoom_to_box(lyr.envelope()) mapnik.render_to_file(m,i, 'png') print "La imagen " +i+ " fue creada." elif geo == 1: print "Trabajando mapa "+ruta+"\\"+filename+" con geometria "+ str(geo) blue = mapnik.PointSymbolizer('C:\Python26\icono.png','png',50,50) blue.allow_overlap = True s=mapnik.Style() r=mapnik.Rule() r.symbols.append(blue) s.rules.append(r) #s.rules.append(blue) m.append_style('My Style',s) lyr = mapnik.Layer('world',"+proj=latlong +datum=WGS84") lyr.datasource = mapnik.Shapefile(base=ruta,file=archivo[0]) lyr.styles.append('My Style') m.layers.append(lyr) m.zoom_to_box(lyr.envelope()) mapnik.render_to_file(m,i, 'png') print "La imagen " +i+ " fue creada." else: print "Algo fallo y no entro a ninguna de las geometrias" print "Listo" -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Tue Jun 14 21:13:22 2011 From: steve at alchemy.com (Steve Willoughby) Date: Tue, 14 Jun 2011 12:13:22 -0700 Subject: [Tutor] trying to translate and ebcidic file In-Reply-To: <6B49A56A6E493F4EBA255F6F197F070F050E4FE26A@BBH-MAIL1.bbh.priv> References: <6B49A56A6E493F4EBA255F6F197F070F050E4FE26A@BBH-MAIL1.bbh.priv> Message-ID: <4DF7B2D2.5080509@alchemy.com> On 14-Jun-11 11:40, Prinn, Craig wrote: > I am looking for a way to translate and ebcidic file to ascii. Is there > a pre-existing library for this, or do I need to do this from scratch? > If from scratch and ideas on where to start? Bear in mind that there's no 100% straight-across translation, because ASCII and EBCDIC each has characters that the other lacks. However, to translate the character codes they share in common, you could do something as simple as using the translation table functionality built in to the string class in Python, setting up a table to convert between one and the other. of course, if you are on a Unix-like system, there's already a command for that, to convert a file "E" from EBCDIC to a file "A" in ASCII: $ dd if=E of=A conv=ascii or the other way: $ dd if=A of=E conv=ebcdic -- 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 susana.delgado_s at utzmg.edu.mx Tue Jun 14 21:14:25 2011 From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez) Date: Tue, 14 Jun 2011 14:14:25 -0500 Subject: [Tutor] Fwd: Break stament issue In-Reply-To: References: Message-ID: ---------- Forwarded message ---------- From: Susana Iraiis Delgado Rodriguez Date: 2011/6/14 Subject: Break stament issue To: tutor at python.org Hello members! I'm doing a script that needs to loop to get some information, in order to do that I'm using modules from OGR and Mapnik. These to get data from shapefiles, but some of the files have 0 elements, I wrote a line to validate it, but it hasn't worked, so I added a break to keep working. When I run the scipt I got the next error: Traceback (most recent call last): File "", line 1, in import mapnik_punto_sin_duda File "C:\Python26\mapnik_punto_sin_duda.py", line 23 break ^ IndentationError: unexpected indent But I've read about this stamentet's use and I don't understand the reason I'm failing, the complete script is: import mapnik import os,fnmatch from mapnik import LineSymbolizer,PolygonSymbolizer,PointSymbolizer from osgeo import ogr,gdal,osr #Registra todos los drivers de GDAL file_list = [] #Crear variable para buscar dentro de carpetas en el sistema folders = None #Se asigna el directorio raiz donde se van buscar los archivos, se hace un recorrido en la raiz for root, folders, files in os.walk( "c:\\" ): #Agregar a la lista los elementos que traiga os.path.join, los archivos que terminen en extension .shp for filename in fnmatch.filter(files, '*.shp'): file_list.append(os.path.join(root, filename)) #Recorrer la lista que se creo for row, filepath in enumerate(file_list, start=1): #Dividir la ruta en dos: directorio y nombre de archivo dir(LineSymbolizer().stroke) shapeData = ogr.Open(filepath) shp = 'Error al abrir el archivo' +filepath if shapeData is None: print shp break else: layer = shapeData.GetLayer() defn = layer.GetLayerDefn() geo = defn.GetGeomType() (ruta, filename) = os.path.split(filepath) archivo = os.path.splitext(filename) i = archivo[0]+'.png' m = mapnik.Map(800,500,"+proj=latlong +datum=WGS84") m.background = mapnik.Color('#EBEBEB') s = mapnik.Style() r=mapnik.Rule() if geo == 3: print "Trabajando mapa "+ruta+"\\"+filename+" con geometria "+ str(geo) r.symbols.append(mapnik.PolygonSymbolizer(mapnik.Color('#EB784B'))) r.symbols.append(mapnik.LineSymbolizer(mapnik.Color('rgb(170%,170%,170%)'),0.9)) s.rules.append(r) m.append_style('My Style',s) lyr = mapnik.Layer('world',"+proj=latlong +datum=WGS84") lyr.datasource = mapnik.Shapefile(base=ruta,file=archivo[0]) lyr.styles.append('My Style') m.layers.append(lyr) m.zoom_to_box(lyr.envelope()) mapnik.render_to_file(m,i, 'png') print "La imagen " +i+ " fue creada." elif geo == 2: print "Trabajando mapa "+ruta+"\\"+filename+" con geometria "+ str(geo) r.symbols.append(mapnik.LineSymbolizer(mapnik.Color('#EB784B'),0.9)) s.rules.append(r) m.append_style('My Style',s) lyr = mapnik.Layer('world',"+proj=latlong +datum=WGS84") lyr.datasource = mapnik.Shapefile(base=ruta,file=archivo[0]) lyr.styles.append('My Style') m.layers.append(lyr) m.zoom_to_box(lyr.envelope()) mapnik.render_to_file(m,i, 'png') print "La imagen " +i+ " fue creada." elif geo == 1: print "Trabajando mapa "+ruta+"\\"+filename+" con geometria "+ str(geo) blue = mapnik.PointSymbolizer('C:\Python26\icono.png','png',50,50) blue.allow_overlap = True s=mapnik.Style() r=mapnik.Rule() r.symbols.append(blue) s.rules.append(r) #s.rules.append(blue) m.append_style('My Style',s) lyr = mapnik.Layer('world',"+proj=latlong +datum=WGS84") lyr.datasource = mapnik.Shapefile(base=ruta,file=archivo[0]) lyr.styles.append('My Style') m.layers.append(lyr) m.zoom_to_box(lyr.envelope()) mapnik.render_to_file(m,i, 'png') print "La imagen " +i+ " fue creada." else: print "Algo fallo y no entro a ninguna de las geometrias" print "Listo" -------------- next part -------------- An HTML attachment was scrubbed... URL: From malaclypse2 at gmail.com Tue Jun 14 21:42:00 2011 From: malaclypse2 at gmail.com (Jerry Hill) Date: Tue, 14 Jun 2011 15:42:00 -0400 Subject: [Tutor] trying to translate and ebcidic file In-Reply-To: <6B49A56A6E493F4EBA255F6F197F070F050E4FE26A@BBH-MAIL1.bbh.priv> References: <6B49A56A6E493F4EBA255F6F197F070F050E4FE26A@BBH-MAIL1.bbh.priv> Message-ID: On Tue, Jun 14, 2011 at 2:40 PM, Prinn, Craig wrote: > I am looking for a way to translate and ebcidic file to ascii. Is there a > pre-existing library for this, or do I need to do this from scratch? If from > scratch and ideas on where to start? If the file is essentially a text file, I would read the contents in, decode the resulting bytes to a unicode string, then encode the unicode string to the encoding of your choice (ascii, utf-8, etc). You'll also need to know which variant of EBCDIC you're dealing with. I'm assuming CCSID 500. Something like this: input_file = open('my_ebcidic_file', 'rb') ebcidic_bytes = input_file.read() unicode_str = ebcidic_bytes.decode('cp500') ascii_str = unicode_str.encode('ascii') You can do it in less steps, but that should give you something to start with. Jerry From eire1130 at gmail.com Tue Jun 14 22:18:20 2011 From: eire1130 at gmail.com (James Reynolds) Date: Tue, 14 Jun 2011 16:18:20 -0400 Subject: [Tutor] Break stament issue In-Reply-To: References: Message-ID: On Tue, Jun 14, 2011 at 2:59 PM, Susana Iraiis Delgado Rodriguez < susana.delgado_s at utzmg.edu.mx> wrote: > Hello members! > > I'm doing a script that needs to loop to get some information, in order to > do that I'm using modules from OGR and Mapnik. These to get data from > shapefiles, but some of the files have 0 elements, I wrote a line to > validate it, but it hasn't worked, so I added a break to keep working. When > I run the scipt I got the next error: > Traceback (most recent call last): > File "", line 1, in > import mapnik_punto_sin_duda > File "C:\Python26\mapnik_punto_sin_duda.py", line 23 > break > ^ > IndentationError: unexpected indent > > But I've read about this stamentet's use and I don't understand the reason > I'm failing, the complete script is: > import mapnik > import os,fnmatch > from mapnik import LineSymbolizer,PolygonSymbolizer,PointSymbolizer > from osgeo import ogr,gdal,osr > > #Registra todos los drivers de GDAL > file_list = [] > #Crear variable para buscar dentro de carpetas en el sistema > folders = None > #Se asigna el directorio raiz donde se van buscar los archivos, se hace un > recorrido en la raiz > for root, folders, files in os.walk( "c:\\" ): > #Agregar a la lista los elementos que traiga os.path.join, los > archivos que terminen en extension .shp > for filename in fnmatch.filter(files, '*.shp'): > file_list.append(os.path.join(root, filename)) > #Recorrer la lista que se creo > for row, filepath in enumerate(file_list, start=1): > #Dividir la ruta en dos: directorio y nombre de archivo > dir(LineSymbolizer().stroke) > shapeData = ogr.Open(filepath) > shp = 'Error al abrir el archivo' +filepath > if shapeData is None: > print shp > break > else: > layer = shapeData.GetLayer() > defn = layer.GetLayerDefn() > geo = defn.GetGeomType() > (ruta, filename) = os.path.split(filepath) > archivo = os.path.splitext(filename) > i = archivo[0]+'.png' > > m = mapnik.Map(800,500,"+proj=latlong +datum=WGS84") > m.background = mapnik.Color('#EBEBEB') > s = mapnik.Style() > r=mapnik.Rule() > > if geo == 3: > print "Trabajando mapa "+ruta+"\\"+filename+" con > geometria "+ str(geo) > > r.symbols.append(mapnik.PolygonSymbolizer(mapnik.Color('#EB784B'))) > > r.symbols.append(mapnik.LineSymbolizer(mapnik.Color('rgb(170%,170%,170%)'),0.9)) > s.rules.append(r) > m.append_style('My Style',s) > lyr = mapnik.Layer('world',"+proj=latlong > +datum=WGS84") > lyr.datasource = > mapnik.Shapefile(base=ruta,file=archivo[0]) > lyr.styles.append('My Style') > m.layers.append(lyr) > m.zoom_to_box(lyr.envelope()) > mapnik.render_to_file(m,i, 'png') > print "La imagen " +i+ " fue creada." > elif geo == 2: > print "Trabajando mapa "+ruta+"\\"+filename+" con > geometria "+ str(geo) > > r.symbols.append(mapnik.LineSymbolizer(mapnik.Color('#EB784B'),0.9)) > s.rules.append(r) > m.append_style('My Style',s) > lyr = mapnik.Layer('world',"+proj=latlong > +datum=WGS84") > lyr.datasource = > mapnik.Shapefile(base=ruta,file=archivo[0]) > lyr.styles.append('My Style') > m.layers.append(lyr) > m.zoom_to_box(lyr.envelope()) > mapnik.render_to_file(m,i, 'png') > print "La imagen " +i+ " fue creada." > elif geo == 1: > print "Trabajando mapa "+ruta+"\\"+filename+" con > geometria "+ str(geo) > blue = > mapnik.PointSymbolizer('C:\Python26\icono.png','png',50,50) > blue.allow_overlap = True > s=mapnik.Style() > r=mapnik.Rule() > r.symbols.append(blue) > s.rules.append(r) > #s.rules.append(blue) > m.append_style('My Style',s) > lyr = mapnik.Layer('world',"+proj=latlong > +datum=WGS84") > lyr.datasource = > mapnik.Shapefile(base=ruta,file=archivo[0]) > lyr.styles.append('My Style') > m.layers.append(lyr) > m.zoom_to_box(lyr.envelope()) > mapnik.render_to_file(m,i, 'png') > print "La imagen " +i+ " fue creada." > else: > print "Algo fallo y no entro a ninguna de las > geometrias" > print "Listo" > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > well i'm not 100% what's going on because it appears to line up when I copy it to my IDE, but you are mixing tabs or # of space indents, you will raise that error, as an example: a= None if a is None: print 'a' print True The print 'a' line is four spaces (my default) and the print True is five. When run it raises the following: print True > ^ > IndentationError: unexpected indent On a side note, if what you want to do is keep working while you work on the rest of it, you should use the pass statement. At least that is what I do. -------------- next part -------------- An HTML attachment was scrubbed... URL: From benderjacob44 at gmail.com Tue Jun 14 23:39:03 2011 From: benderjacob44 at gmail.com (Jacob Bender) Date: Tue, 14 Jun 2011 17:39:03 -0400 Subject: [Tutor] Communicating Between Programs Using Raw Inputs Message-ID: Dear Python Tutors, I was wondering how to break into my one program I made using brute force methods. Here's the code: password = "Helloworld" try= raw_input("What's the password?") while try != password: try = raw_input("Incorrect, what's the password?") I know how to do it in the command line, but not through another program. Generating the random tries for the password isn't the issue, but entering the password(s) in between the two programs is an issue because I don't know how to make programs communicate through raw inputs. Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Wed Jun 15 00:40:26 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 15 Jun 2011 08:40:26 +1000 Subject: [Tutor] Break stament issue In-Reply-To: References: Message-ID: <4DF7E35A.1080908@pearwood.info> Susana Iraiis Delgado Rodriguez wrote: > Hello members! > > I'm doing a script that needs to loop to get some information, in order to > do that I'm using modules from OGR and Mapnik. These to get data from > shapefiles, but some of the files have 0 elements, I wrote a line to > validate it, but it hasn't worked, so I added a break to keep working. When > I run the scipt I got the next error: > Traceback (most recent call last): > File "", line 1, in > import mapnik_punto_sin_duda > File "C:\Python26\mapnik_punto_sin_duda.py", line 23 > break > ^ > IndentationError: unexpected indent This error has nothing to do with break. Look at the error message, and the position of the ^ mark: the error occurs *before* the break statement, in the indentation. I can duplicate the error in Python 2.6 with this: >>> for t in (1, 2, 3): ... print t # four spaces ... break # one tab File "", line 3 break # one tab ^ IndentationError: unexpected indent Newer versions of Python give more helpful error messages: Python 3 reports "TabError: inconsistent use of tabs and spaces in indentation". You can fix this by using the tabnanny script supplied with Python. From the shell (not Python's interactive interpreter!) or the DOS prompt, run: python -m tabnanny -v replacing with the actual filename, and see what it says. -- Steven From steve at pearwood.info Wed Jun 15 00:48:49 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 15 Jun 2011 08:48:49 +1000 Subject: [Tutor] Communicating Between Programs Using Raw Inputs In-Reply-To: References: Message-ID: <4DF7E551.6080204@pearwood.info> Jacob Bender wrote: > Dear Python Tutors, > > I was wondering how to break into my one program I made using brute force > methods. Here's the code: > > password = "Helloworld" > try= raw_input("What's the password?") > while try != password: > try = raw_input("Incorrect, what's the password?") > > I know how to do it in the command line, but not through another program. > Generating the random tries for the password isn't the issue, but entering > the password(s) in between the two programs is an issue because I don't know > how to make programs communicate through raw inputs. Normally you would do this by redirecting standard input. What operating system are you using? In Linux, you would do something like: # run script foo.py taking input from the output of bar.py foo.py < bar.py at the shell. I don't know how to do it in DOS. However, I don't know if this will actually work for raw_input. It may not. Try it and see. Perhaps a better way is to have your program accept a user name and password on the command line, and only prompt for them if not given. Then you can say: foo.py --user=fred --password="y8Mr3 at hzi" Hope this helps, -- Steven From steve at alchemy.com Wed Jun 15 00:54:20 2011 From: steve at alchemy.com (Steve Willoughby) Date: Tue, 14 Jun 2011 15:54:20 -0700 Subject: [Tutor] Communicating Between Programs Using Raw Inputs In-Reply-To: <4DF7E551.6080204@pearwood.info> References: <4DF7E551.6080204@pearwood.info> Message-ID: <4DF7E69C.6000406@alchemy.com> On 14-Jun-11 15:48, Steven D'Aprano wrote: > Normally you would do this by redirecting standard input. What operating > system are you using? In Linux, you would do something like: > > > # run script foo.py taking input from the output of bar.py > foo.py < bar.py Actually, no, that will send the *source code* of bar.py as the input to foo.py. I think you mean: bar.py | foo.py which also should work in DOS as well (although less efficiently). > However, I don't know if this will actually work for raw_input. It may > not. Try it and see. It should. > > Perhaps a better way is to have your program accept a user name and > password on the command line, and only prompt for them if not given. > Then you can say: > > foo.py --user=fred --password="y8Mr3 at hzi" This is one way. Another would be to use the subprocess module in Python which will let one program invoke another program, and have a file-like object on which it can write data, which the child program will see as its standard input (and read in to raw_input). -- 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 Wed Jun 15 01:36:13 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 15 Jun 2011 00:36:13 +0100 Subject: [Tutor] Communicating Between Programs Using Raw Inputs References: Message-ID: "Jacob Bender" wrote > I know how to do it in the command line, but not through another > program. > Generating the random tries for the password isn't the issue, but > entering > the password(s) in between the two programs is an issue because I > don't know > how to make programs communicate through raw inputs. You need to search for stdin and stdout. Try wikipedia. Then google python stdin By linking stdout of one program to stdin of another you can pass data between them. This is one of the things that makes Unix such an insanely great programmers OS, its commands are explicitly designed to do this. But you can make it work with any command that prints to stdout and reads from stdin. If you read the "Talking to the User" topic in my tutorial you will see a sidebar/box that discusses this and gives an example of reading from a file. You need to take that one step further and read from a process. In Unix the easiest way you can do that is to surround the command with backtick marks: python reader.py < `python writer.py` notice the *back* quote marks. There are other ways of doing it inside Python, seee my "Using the OS" topic for those. But backtics and stdin should do what you need. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at alchemy.com Wed Jun 15 01:46:10 2011 From: steve at alchemy.com (Steve Willoughby) Date: Tue, 14 Jun 2011 16:46:10 -0700 Subject: [Tutor] Communicating Between Programs Using Raw Inputs In-Reply-To: References: Message-ID: <4DF7F2C2.7020104@alchemy.com> As always, Alan has given a lot of great advice and useful information. There's just one piece at the end I would question, however: On 14-Jun-11 16:36, Alan Gauld wrote: > python reader.py < `python writer.py` Almost, but not quite. The backticks mean the command is executed and the output substituted back on the command line. The < bracket means to take what follows it as a file NAME (not a data stream). So unless writer.py outputs a filename, you really want something like python writer.py | python reader.py -- 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 wolfrage8765 at gmail.com Wed Jun 15 06:47:27 2011 From: wolfrage8765 at gmail.com (WolfRage) Date: Tue, 14 Jun 2011 21:47:27 -0700 Subject: [Tutor] Already Initialized Object Inheritance? Message-ID: <1308113247.1952.45.camel@wolfrage-LE1600> I can not get this to behave in the manor that I would like. I am trying to have an object refereed to as CursesApp.Screen become the already initialized object "stdscr". To elaborate I would like it to become that object but to also be able to define additional methods and properties, so more along the lines of inherit from "stdscr". Is this even possible? Well I can make it equal to that object I can not add additional methods and properties to it? Additionally, so that I learn; where has my thinking been too short sited? Thank you for your help. -- Jordan ****CODE BELOW**** #!/usr/bin/python3 """With thi method I can make the class "Screen" become "stdscr" but if I refernce any of the new methods or properties the applications promptly fails and notifies me that the method or property does not exist. Another downside of this method is I can not reference self.Screen.* or it crashes.""" import curses class CursesApp: def __init__(self, stdscr): self.Screen(stdscr) #This is the stdscr object. curses.init_pair(1,curses.COLOR_BLUE,curses.COLOR_YELLOW) #self.Screen.bkgd(' ', curses.color_pair(1)) #self.mainLoop() #def mainLoop(self): #while 1: #self.Screen.refresh() #key=self.Screen.getch() #if key==ord('q'): break class Screen: def __init__(self,stdscr): self=stdscr #self.height, self.width = self.getmaxyx() # any reference to these crashes #self.offsety, self.offsetx = -self.height/2, -self.width/2 # any reference to these crashes #self.curx, self.cury = 1, 1 # any reference to these crashes self.clear() self.border(0) while 1: self.refresh() key=self.getch() if key==ord('q'): break def main(): cursesapp = curses.wrapper(setup) def setup(stdscr): CursesApp(stdscr) if __name__ == '__main__': main() ****CODE BELOW**** #!/usr/bin/python3 """With this method I can make "Screen" become "stdscr" but if I obviously can not even define any new methods or properties. But atleast the references can be used through out the class with out crashing.""" import curses class CursesApp: def __init__(self, stdscr): self.Screen=stdscr #This is the stdscr object. curses.init_pair(1,curses.COLOR_BLUE,curses.COLOR_YELLOW) self.Screen.bkgd(' ', curses.color_pair(1)) self.mainLoop() def mainLoop(self): while 1: self.Screen.refresh() key=self.Screen.getch() if key==ord('q'): break def main(): cursesapp = curses.wrapper(setup) def setup(stdscr): CursesApp(stdscr) if __name__ == '__main__': main() From wolfrage8765 at gmail.com Wed Jun 15 08:42:59 2011 From: wolfrage8765 at gmail.com (WolfRage) Date: Tue, 14 Jun 2011 23:42:59 -0700 Subject: [Tutor] Already Initialized Object Inheritance? In-Reply-To: References: <1308113247.1952.45.camel@wolfrage-LE1600> Message-ID: <1308120179.1952.50.camel@wolfrage-LE1600> Unfortunately I am not able to inherit "stdscr" using that method. As Python returns with an error stating that "stdscr" is not defined. This error is returned at run time and by the compiler prior to actual execution. If you would like I can write a quick example that will generate the error message for that method. -- Jordan On Wed, 2011-06-15 at 02:04 -0400, Japhy Bartlett wrote: > When you're subclassing something, you use the syntax: > > class Foo(Bar): > > It seems like you're trying to do: > > class Bar: > class Foo: > > - Japhy > > On Wed, Jun 15, 2011 at 12:47 AM, WolfRage wrote: > > I can not get this to behave in the manor that I would like. I am trying > > to have an object refereed to as CursesApp.Screen become the already > > initialized object "stdscr". To elaborate I would like it to become that > > object but to also be able to define additional methods and properties, > > so more along the lines of inherit from "stdscr". Is this even possible? > > Well I can make it equal to that object I can not add additional methods > > and properties to it? Additionally, so that I learn; where has my > > thinking been too short sited? Thank you for your help. > > -- > > Jordan > > > > ****CODE BELOW**** > > > > #!/usr/bin/python3 > > """With thi method I can make the class "Screen" become "stdscr" but if > > I refernce any of the new methods or properties the applications > > promptly fails and notifies me that the method or property does not > > exist. Another downside of this method is I can not reference > > self.Screen.* or it crashes.""" > > import curses > > class CursesApp: > > def __init__(self, stdscr): > > self.Screen(stdscr) #This is the stdscr object. > > curses.init_pair(1,curses.COLOR_BLUE,curses.COLOR_YELLOW) > > #self.Screen.bkgd(' ', curses.color_pair(1)) > > #self.mainLoop() > > > > #def mainLoop(self): > > #while 1: > > #self.Screen.refresh() > > #key=self.Screen.getch() > > #if key==ord('q'): break > > > > class Screen: > > def __init__(self,stdscr): > > self=stdscr > > #self.height, self.width = self.getmaxyx() # any reference > > to these crashes > > #self.offsety, self.offsetx = -self.height/2, -self.width/2 > > # any reference to these crashes > > #self.curx, self.cury = 1, 1 # any reference to these > > crashes > > self.clear() > > self.border(0) > > while 1: > > self.refresh() > > key=self.getch() > > if key==ord('q'): break > > > > def main(): > > cursesapp = curses.wrapper(setup) > > > > def setup(stdscr): > > CursesApp(stdscr) > > > > if __name__ == '__main__': > > main() > > > > > > > > ****CODE BELOW**** > > > > #!/usr/bin/python3 > > """With this method I can make "Screen" become "stdscr" but if I > > obviously can not even define any new methods or properties. But atleast > > the references can be used through out the class with out crashing.""" > > import curses > > class CursesApp: > > def __init__(self, stdscr): > > self.Screen=stdscr #This is the stdscr object. > > curses.init_pair(1,curses.COLOR_BLUE,curses.COLOR_YELLOW) > > self.Screen.bkgd(' ', curses.color_pair(1)) > > self.mainLoop() > > > > def mainLoop(self): > > while 1: > > self.Screen.refresh() > > key=self.Screen.getch() > > if key==ord('q'): break > > > > def main(): > > cursesapp = curses.wrapper(setup) > > > > def setup(stdscr): > > CursesApp(stdscr) > > > > if __name__ == '__main__': > > main() > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > From metolone+gmane at gmail.com Wed Jun 15 11:20:27 2011 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Wed, 15 Jun 2011 02:20:27 -0700 Subject: [Tutor] trying to translate and ebcidic file References: <6B49A56A6E493F4EBA255F6F197F070F050E4FE26A@BBH-MAIL1.bbh.priv> Message-ID: "Prinn, Craig" wrote in message news:6B49A56A6E493F4EBA255F6F197F070F050E4FE26A at BBH-MAIL1.bbh.priv... > I am looking for a way to translate and ebcidic file to ascii. Is there a > pre-existing library for this, or do I need to do this from scratch? If > from scratch and ideas on where to start? There are a couple of EBCDIC codecs (see list of codecs in http://docs.python.org/library/codecs.html). Try: open('file.txt').read().decode('ibm500').encode('ascii','replace') You'll get '?' for chars ascii doesn't support. -Mark From benderjacob44 at gmail.com Wed Jun 15 13:04:54 2011 From: benderjacob44 at gmail.com (Jacob Bender) Date: Wed, 15 Jun 2011 07:04:54 -0400 Subject: [Tutor] Tutor Digest, Vol 88, Issue 53 In-Reply-To: References: Message-ID: Thanks, and I'll try those. On Wed, Jun 15, 2011 at 12:47 AM, 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. Communicating Between Programs Using Raw Inputs (Jacob Bender) > 2. Re: Break stament issue (Steven D'Aprano) > 3. Re: Communicating Between Programs Using Raw Inputs > (Steven D'Aprano) > 4. Re: Communicating Between Programs Using Raw Inputs > (Steve Willoughby) > 5. Re: Communicating Between Programs Using Raw Inputs (Alan Gauld) > 6. Re: Communicating Between Programs Using Raw Inputs > (Steve Willoughby) > 7. Already Initialized Object Inheritance? (WolfRage) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Tue, 14 Jun 2011 17:39:03 -0400 > From: Jacob Bender > To: Python Tutor > Subject: [Tutor] Communicating Between Programs Using Raw Inputs > Message-ID: > Content-Type: text/plain; charset="iso-8859-1" > > Dear Python Tutors, > > I was wondering how to break into my one program I made using brute force > methods. Here's the code: > > password = "Helloworld" > try= raw_input("What's the password?") > while try != password: > try = raw_input("Incorrect, what's the password?") > > I know how to do it in the command line, but not through another program. > Generating the random tries for the password isn't the issue, but entering > the password(s) in between the two programs is an issue because I don't > know > how to make programs communicate through raw inputs. > > Thanks! > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20110614/0c5ecf31/attachment-0001.html > > > > ------------------------------ > > Message: 2 > Date: Wed, 15 Jun 2011 08:40:26 +1000 > From: Steven D'Aprano > To: tutor at python.org > Subject: Re: [Tutor] Break stament issue > Message-ID: <4DF7E35A.1080908 at pearwood.info> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Susana Iraiis Delgado Rodriguez wrote: > > Hello members! > > > > I'm doing a script that needs to loop to get some information, in order > to > > do that I'm using modules from OGR and Mapnik. These to get data from > > shapefiles, but some of the files have 0 elements, I wrote a line to > > validate it, but it hasn't worked, so I added a break to keep working. > When > > I run the scipt I got the next error: > > Traceback (most recent call last): > > File "", line 1, in > > import mapnik_punto_sin_duda > > File "C:\Python26\mapnik_punto_sin_duda.py", line 23 > > break > > ^ > > IndentationError: unexpected indent > > This error has nothing to do with break. Look at the error message, and > the position of the ^ mark: the error occurs *before* the break > statement, in the indentation. > > I can duplicate the error in Python 2.6 with this: > > > >>> for t in (1, 2, 3): > ... print t # four spaces > ... break # one tab > File "", line 3 > break # one tab > ^ > IndentationError: unexpected indent > > > Newer versions of Python give more helpful error messages: Python 3 > reports "TabError: inconsistent use of tabs and spaces in indentation". > > > You can fix this by using the tabnanny script supplied with Python. From > the shell (not Python's interactive interpreter!) or the DOS prompt, run: > > python -m tabnanny -v > > replacing with the actual filename, and see what it > says. > > > -- > Steven > > > ------------------------------ > > Message: 3 > Date: Wed, 15 Jun 2011 08:48:49 +1000 > From: Steven D'Aprano > To: Python Tutor > Subject: Re: [Tutor] Communicating Between Programs Using Raw Inputs > Message-ID: <4DF7E <4DF7E551.6080204 at pearwood.info>551.6080204@ > pearwood.info> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Jacob Bender wrote: > > Dear Python Tutors, > > > > I was wondering how to break into my one program I made using brute force > > methods. Here's the code: > > > > password = "Helloworld" > > try= raw_input("What's the password?") > > while try != password: > > try = raw_input("Incorrect, what's the password?") > > > > I know how to do it in the command line, but not through another program. > > Generating the random tries for the password isn't the issue, but > entering > > the password(s) in between the two programs is an issue because I don't > know > > how to make programs communicate through raw inputs. > > > Normally you would do this by redirecting standard input. What operating > system are you using? In Linux, you would do something like: > > > # run script foo.py taking input from the output of bar.py > foo.py < bar.py > > > at the shell. I don't know how to do it in DOS. > > However, I don't know if this will actually work for raw_input. It may > not. Try it and see. > > Perhaps a better way is to have your program accept a user name and > password on the command line, and only prompt for them if not given. > Then you can say: > > foo.py --user=fred --password="y8Mr3 at hzi" > > > Hope this helps, > > > > -- > Steven > > > > ------------------------------ > > Message: 4 > Date: Tue, 14 Jun 2011 15:54:20 -0700 > From: Steve Willoughby > To: tutor at python.org > Subject: Re: [Tutor] Communicating Between Programs Using Raw Inputs > Message-ID: <4DF7E69C.6000406 at alchemy.com> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 14-Jun-11 15:48, Steven D'Aprano wrote: > > > Normally you would do this by redirecting standard input. What operating > > system are you using? In Linux, you would do something like: > > > > > > # run script foo.py taking input from the output of bar.py > > foo.py < bar.py > > Actually, no, that will send the *source code* of bar.py as the input to > foo.py. I think you mean: > > bar.py | foo.py > > which also should work in DOS as well (although less efficiently). > > > However, I don't know if this will actually work for raw_input. It may > > not. Try it and see. > > It should. > > > > > Perhaps a better way is to have your program accept a user name and > > password on the command line, and only prompt for them if not given. > > Then you can say: > > > > foo.py --user=fred --password="y8Mr3 at hzi" > > This is one way. Another would be to use the subprocess module in > Python which will let one program invoke another program, and have a > file-like object on which it can write data, which the child program > will see as its standard input (and read in to raw_input). > > -- > 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 > > > ------------------------------ > > Message: 5 > Date: Wed, 15 Jun 2011 00:36:13 +0100 > From: "Alan Gauld" > To: tutor at python.org > Subject: Re: [Tutor] Communicating Between Programs Using Raw Inputs > Message-ID: > Content-Type: text/plain; format=flowed; charset="iso-8859-1"; > reply-type=original > > > "Jacob Bender" wrote > > > I know how to do it in the command line, but not through another > > program. > > Generating the random tries for the password isn't the issue, but > > entering > > the password(s) in between the two programs is an issue because I > > don't know > > how to make programs communicate through raw inputs. > > You need to search for stdin and stdout. Try wikipedia. > Then google python stdin > > By linking stdout of one program to stdin of another you can pass > data between them. This is one of the things that makes Unix > such an insanely great programmers OS, its commands are > explicitly designed to do this. But you can make it work with > any command that prints to stdout and reads from stdin. > > If you read the "Talking to the User" topic in my tutorial you > will see a sidebar/box that discusses this and gives an example > of reading from a file. You need to take that one step further and > read from a process. In Unix the easiest way you can do that is > to surround the command with backtick marks: > > python reader.py < `python writer.py` > > notice the *back* quote marks. > > There are other ways of doing it inside Python, seee my > "Using the OS" topic for those. But backtics and stdin should > do what you need. > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > > > ------------------------------ > > Message: 6 > Date: Tue, 14 Jun 2011 16:46:10 -0700 > From: Steve Willoughby > To: tutor at python.org > Subject: Re: [Tutor] Communicating Between Programs Using Raw Inputs > Message-ID: <4DF7F2C2.7020104 at alchemy.com> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > As always, Alan has given a lot of great advice and useful information. > There's just one piece at the end I would question, however: > > > On 14-Jun-11 16:36, Alan Gauld wrote: > > python reader.py < `python writer.py` > > Almost, but not quite. The backticks mean the command is executed and > the output substituted back on the command line. The < bracket means to > take what follows it as a file NAME (not a data stream). So unless > writer.py outputs a filename, you really want something like > > python writer.py | python reader.py > > > > -- > 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 > > > ------------------------------ > > Message: 7 > Date: Tue, 14 Jun 2011 21:47:27 -0700 > From: WolfRage > To: Python Tutor > Subject: [Tutor] Already Initialized Object Inheritance? > Message-ID: <1308113247.1952.45.camel at wolfrage-LE1600> > Content-Type: text/plain; charset="UTF-8" > > I can not get this to behave in the manor that I would like. I am trying > to have an object refereed to as CursesApp.Screen become the already > initialized object "stdscr". To elaborate I would like it to become that > object but to also be able to define additional methods and properties, > so more along the lines of inherit from "stdscr". Is this even possible? > Well I can make it equal to that object I can not add additional methods > and properties to it? Additionally, so that I learn; where has my > thinking been too short sited? Thank you for your help. > -- > Jordan > > ****CODE BELOW**** > > #!/usr/bin/python3 > """With thi method I can make the class "Screen" become "stdscr" but if > I refernce any of the new methods or properties the applications > promptly fails and notifies me that the method or property does not > exist. Another downside of this method is I can not reference > self.Screen.* or it crashes.""" > import curses > class CursesApp: > def __init__(self, stdscr): > self.Screen(stdscr) #This is the stdscr object. > curses.init_pair(1,curses.COLOR_BLUE,curses.COLOR_YELLOW) > #self.Screen.bkgd(' ', curses.color_pair(1)) > #self.mainLoop() > > #def mainLoop(self): > #while 1: > #self.Screen.refresh() > #key=self.Screen.getch() > #if key==ord('q'): break > > class Screen: > def __init__(self,stdscr): > self=stdscr > #self.height, self.width = self.getmaxyx() # any reference > to these crashes > #self.offsety, self.offsetx = -self.height/2, -self.width/2 > # any reference to these crashes > #self.curx, self.cury = 1, 1 # any reference to these > crashes > self.clear() > self.border(0) > while 1: > self.refresh() > key=self.getch() > if key==ord('q'): break > > def main(): > cursesapp = curses.wrapper(setup) > > def setup(stdscr): > CursesApp(stdscr) > > if __name__ == '__main__': > main() > > > > ****CODE BELOW**** > > #!/usr/bin/python3 > """With this method I can make "Screen" become "stdscr" but if I > obviously can not even define any new methods or properties. But atleast > the references can be used through out the class with out crashing.""" > import curses > class CursesApp: > def __init__(self, stdscr): > self.Screen=stdscr #This is the stdscr object. > curses.init_pair(1,curses.COLOR_BLUE,curses.COLOR_YELLOW) > self.Screen.bkgd(' ', curses.color_pair(1)) > self.mainLoop() > > def mainLoop(self): > while 1: > self.Screen.refresh() > key=self.Screen.getch() > if key==ord('q'): break > > def main(): > cursesapp = curses.wrapper(setup) > > def setup(stdscr): > CursesApp(stdscr) > > if __name__ == '__main__': > main() > > > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 88, Issue 53 > ************************************* > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Wed Jun 15 13:35:05 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 15 Jun 2011 21:35:05 +1000 Subject: [Tutor] Already Initialized Object Inheritance? In-Reply-To: <1308120179.1952.50.camel@wolfrage-LE1600> References: <1308113247.1952.45.camel@wolfrage-LE1600> <1308120179.1952.50.camel@wolfrage-LE1600> Message-ID: <4DF898E9.5050104@pearwood.info> WolfRage wrote: > Unfortunately I am not able to inherit "stdscr" using that method. As > Python returns with an error stating that "stdscr" is not defined. This > error is returned at run time and by the compiler prior to actual > execution. If you would like I can write a quick example that will > generate the error message for that method. You shouldn't need to ask that question, just do it. My guess is that the error you get is a NameError. The solution to that is to fix the name error, not to run off chasing wild geese. Object inheritance? This has nothing to do with that! What is stdscr? Where does it come from? How is it defined? Please copy and paste the *exact* error message you get, including the full traceback. -- Steven From micha_el2003 at yahoo.com Wed Jun 15 13:42:57 2011 From: micha_el2003 at yahoo.com (Michael bridges) Date: Wed, 15 Jun 2011 04:42:57 -0700 (PDT) Subject: [Tutor] using python to write web page Message-ID: <557213.35730.qm@web161306.mail.bf1.yahoo.com> i would like to use python to write a web page like writing an html file that is displayed in a browser without having to run a server. found a few options, but need to have server running. https://skulpt.googlecode.com/hg/skulpt gives 404 error From andres at chandia.net Wed Jun 15 14:01:01 2011 From: andres at chandia.net (=?iso-8859-1?Q?=22Andr=E9s_Chand=EDa=22?=) Date: Wed, 15 Jun 2011 14:01:01 +0200 Subject: [Tutor] using python to write web page In-Reply-To: <557213.35730.qm@web161306.mail.bf1.yahoo.com> References: <557213.35730.qm@web161306.mail.bf1.yahoo.com> Message-ID: <0274f086edd4fe19f0f929e468ca9bd9.squirrel@mail.chandia.net> Or maybe, you're lokking something like this: http://wiki.python.org/moin/PythonEditors On Wed, June 15, 2011 13:42, Michael bridges wrote: i would like to use python to write a web page like writing an html file that is displayed in a browser without having to run a server. found a few options, but need to have server running. https://skulpt.googlecode.com/hg/skulpt gives 404 error _______________________________________________ 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 Wed Jun 15 13:56:16 2011 From: andres at chandia.net (=?iso-8859-1?Q?=22Andr=E9s_Chand=EDa=22?=) Date: Wed, 15 Jun 2011 13:56:16 +0200 Subject: [Tutor] using python to write web page In-Reply-To: <557213.35730.qm@web161306.mail.bf1.yahoo.com> References: <557213.35730.qm@web161306.mail.bf1.yahoo.com> Message-ID: <1a538fd9a4628c81c2910160d323ba00.squirrel@mail.chandia.net> cherrypy is what you are looking for check this site: http://www.chandia.net:8080/ you cn download the code from here, so you can use it as you want: NMT-2.6-20110529.tar_.gz On Wed, June 15, 2011 13:42, Michael bridges wrote: i would like to use python to write a web page like writing an html file that is displayed in a browser without having to run a server. found a few options, but need to have server running. https://skulpt.googlecode.com/hg/skulpt gives 404 error _______________________________________________ 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 Craig.Prinn at bowebellhowell.com Wed Jun 15 18:11:27 2011 From: Craig.Prinn at bowebellhowell.com (Prinn, Craig) Date: Wed, 15 Jun 2011 12:11:27 -0400 Subject: [Tutor] Converting ebcidic to ascii In-Reply-To: References: Message-ID: <6B49A56A6E493F4EBA255F6F197F070F050E4FE454@BBH-MAIL1.bbh.priv> Thanks Mark that did the trick, couldn't quite figure out the syntax before. Craig Prinn Document Solutions Manager Office Phone 919-767-6640 Cell Phone 410-320-9962 Fax 410-243-0973 3600 Clipper Mill Road Suite 404 Baltimore, MD 21211 -----Original Message----- From: tutor-bounces+craig.prinn=bowebellhowell.com at python.org [mailto:tutor-bounces+craig.prinn=bowebellhowell.com at python.org] On Behalf Of tutor-request at python.org Sent: Wednesday, June 15, 2011 6:00 AM To: tutor at python.org Subject: Tutor Digest, Vol 88, Issue 54 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: Already Initialized Object Inheritance? (WolfRage) 2. Re: trying to translate and ebcidic file (Mark Tolonen) ---------------------------------------------------------------------- Message: 1 Date: Tue, 14 Jun 2011 23:42:59 -0700 From: WolfRage To: Japhy Bartlett Cc: Python Tutor Subject: Re: [Tutor] Already Initialized Object Inheritance? Message-ID: <1308120179.1952.50.camel at wolfrage-LE1600> Content-Type: text/plain; charset="UTF-8" Unfortunately I am not able to inherit "stdscr" using that method. As Python returns with an error stating that "stdscr" is not defined. This error is returned at run time and by the compiler prior to actual execution. If you would like I can write a quick example that will generate the error message for that method. -- Jordan On Wed, 2011-06-15 at 02:04 -0400, Japhy Bartlett wrote: > When you're subclassing something, you use the syntax: > > class Foo(Bar): > > It seems like you're trying to do: > > class Bar: > class Foo: > > - Japhy > > On Wed, Jun 15, 2011 at 12:47 AM, WolfRage wrote: > > I can not get this to behave in the manor that I would like. I am trying > > to have an object refereed to as CursesApp.Screen become the already > > initialized object "stdscr". To elaborate I would like it to become that > > object but to also be able to define additional methods and properties, > > so more along the lines of inherit from "stdscr". Is this even possible? > > Well I can make it equal to that object I can not add additional methods > > and properties to it? Additionally, so that I learn; where has my > > thinking been too short sited? Thank you for your help. > > -- > > Jordan > > > > ****CODE BELOW**** > > > > #!/usr/bin/python3 > > """With thi method I can make the class "Screen" become "stdscr" but if > > I refernce any of the new methods or properties the applications > > promptly fails and notifies me that the method or property does not > > exist. Another downside of this method is I can not reference > > self.Screen.* or it crashes.""" > > import curses > > class CursesApp: > > def __init__(self, stdscr): > > self.Screen(stdscr) #This is the stdscr object. > > curses.init_pair(1,curses.COLOR_BLUE,curses.COLOR_YELLOW) > > #self.Screen.bkgd(' ', curses.color_pair(1)) > > #self.mainLoop() > > > > #def mainLoop(self): > > #while 1: > > #self.Screen.refresh() > > #key=self.Screen.getch() > > #if key==ord('q'): break > > > > class Screen: > > def __init__(self,stdscr): > > self=stdscr > > #self.height, self.width = self.getmaxyx() # any reference > > to these crashes > > #self.offsety, self.offsetx = -self.height/2, -self.width/2 > > # any reference to these crashes > > #self.curx, self.cury = 1, 1 # any reference to these > > crashes > > self.clear() > > self.border(0) > > while 1: > > self.refresh() > > key=self.getch() > > if key==ord('q'): break > > > > def main(): > > cursesapp = curses.wrapper(setup) > > > > def setup(stdscr): > > CursesApp(stdscr) > > > > if __name__ == '__main__': > > main() > > > > > > > > ****CODE BELOW**** > > > > #!/usr/bin/python3 > > """With this method I can make "Screen" become "stdscr" but if I > > obviously can not even define any new methods or properties. But atleast > > the references can be used through out the class with out crashing.""" > > import curses > > class CursesApp: > > def __init__(self, stdscr): > > self.Screen=stdscr #This is the stdscr object. > > curses.init_pair(1,curses.COLOR_BLUE,curses.COLOR_YELLOW) > > self.Screen.bkgd(' ', curses.color_pair(1)) > > self.mainLoop() > > > > def mainLoop(self): > > while 1: > > self.Screen.refresh() > > key=self.Screen.getch() > > if key==ord('q'): break > > > > def main(): > > cursesapp = curses.wrapper(setup) > > > > def setup(stdscr): > > CursesApp(stdscr) > > > > if __name__ == '__main__': > > main() > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > ------------------------------ Message: 2 Date: Wed, 15 Jun 2011 02:20:27 -0700 From: "Mark Tolonen" To: tutor at python.org Subject: Re: [Tutor] trying to translate and ebcidic file Message-ID: Content-Type: text/plain; format=flowed; charset="iso-8859-1"; reply-type=original "Prinn, Craig" wrote in message news:6B49A56A6E493F4EBA255F6F197F070F050E4FE26A at BBH-MAIL1.bbh.priv... > I am looking for a way to translate and ebcidic file to ascii. Is there a > pre-existing library for this, or do I need to do this from scratch? If > from scratch and ideas on where to start? There are a couple of EBCDIC codecs (see list of codecs in http://docs.python.org/library/codecs.html). Try: open('file.txt').read().decode('ibm500').encode('ascii','replace') You'll get '?' for chars ascii doesn't support. -Mark ------------------------------ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor End of Tutor Digest, Vol 88, Issue 54 ************************************* From susana.delgado_s at utzmg.edu.mx Wed Jun 15 19:47:25 2011 From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez) Date: Wed, 15 Jun 2011 12:47:25 -0500 Subject: [Tutor] Break stament issue In-Reply-To: References: Message-ID: Hello members!! Steven, I already changed the settings in the IDE to avoid the trouble when I type the code. In the other hand I added the pass statement so the script keep working even though it finds an error, but the scripts ignore the pass statement. Console prints: Traceback (most recent call last): File "", line 1, in File "mapnik_punto_sin_duda.py", line 44, in lyr.datasource = mapnik.Shapefile(base=ruta,file=archivo[0]) File "C:\mapnik-0.7.1\python\2.6\site-packages\mapnik\__init__.py", line 282, in Shapefile return CreateDatasource(keywords) RuntimeError: wrong file code : -1997790976 2011/6/14 James Reynolds > > > On Tue, Jun 14, 2011 at 2:59 PM, Susana Iraiis Delgado Rodriguez < > susana.delgado_s at utzmg.edu.mx> wrote: > >> Hello members! >> >> I'm doing a script that needs to loop to get some information, in order to >> do that I'm using modules from OGR and Mapnik. These to get data from >> shapefiles, but some of the files have 0 elements, I wrote a line to >> validate it, but it hasn't worked, so I added a break to keep working. When >> I run the scipt I got the next error: >> Traceback (most recent call last): >> File "", line 1, in >> import mapnik_punto_sin_duda >> File "C:\Python26\mapnik_punto_sin_duda.py", line 23 >> break >> ^ >> IndentationError: unexpected indent >> >> But I've read about this stamentet's use and I don't understand the reason >> I'm failing, the complete script is: >> import mapnik >> import os,fnmatch >> from mapnik import LineSymbolizer,PolygonSymbolizer,PointSymbolizer >> from osgeo import ogr,gdal,osr >> >> #Registra todos los drivers de GDAL >> file_list = [] >> #Crear variable para buscar dentro de carpetas en el sistema >> folders = None >> #Se asigna el directorio raiz donde se van buscar los archivos, se hace un >> recorrido en la raiz >> for root, folders, files in os.walk( "c:\\" ): >> #Agregar a la lista los elementos que traiga os.path.join, los >> archivos que terminen en extension .shp >> for filename in fnmatch.filter(files, '*.shp'): >> file_list.append(os.path.join(root, filename)) >> #Recorrer la lista que se creo >> for row, filepath in enumerate(file_list, start=1): >> #Dividir la ruta en dos: directorio y nombre de archivo >> dir(LineSymbolizer().stroke) >> shapeData = ogr.Open(filepath) >> shp = 'Error al abrir el archivo' +filepath >> if shapeData is None: >> print shp >> break >> else: >> layer = shapeData.GetLayer() >> defn = layer.GetLayerDefn() >> geo = defn.GetGeomType() >> (ruta, filename) = os.path.split(filepath) >> archivo = os.path.splitext(filename) >> i = archivo[0]+'.png' >> >> m = mapnik.Map(800,500,"+proj=latlong +datum=WGS84") >> m.background = mapnik.Color('#EBEBEB') >> s = mapnik.Style() >> r=mapnik.Rule() >> >> if geo == 3: >> print "Trabajando mapa "+ruta+"\\"+filename+" con >> geometria "+ str(geo) >> >> r.symbols.append(mapnik.PolygonSymbolizer(mapnik.Color('#EB784B'))) >> >> r.symbols.append(mapnik.LineSymbolizer(mapnik.Color('rgb(170%,170%,170%)'),0.9)) >> s.rules.append(r) >> m.append_style('My Style',s) >> lyr = mapnik.Layer('world',"+proj=latlong >> +datum=WGS84") >> lyr.datasource = >> mapnik.Shapefile(base=ruta,file=archivo[0]) >> lyr.styles.append('My Style') >> m.layers.append(lyr) >> m.zoom_to_box(lyr.envelope()) >> mapnik.render_to_file(m,i, 'png') >> print "La imagen " +i+ " fue creada." >> elif geo == 2: >> print "Trabajando mapa "+ruta+"\\"+filename+" con >> geometria "+ str(geo) >> >> r.symbols.append(mapnik.LineSymbolizer(mapnik.Color('#EB784B'),0.9)) >> s.rules.append(r) >> m.append_style('My Style',s) >> lyr = mapnik.Layer('world',"+proj=latlong >> +datum=WGS84") >> lyr.datasource = >> mapnik.Shapefile(base=ruta,file=archivo[0]) >> lyr.styles.append('My Style') >> m.layers.append(lyr) >> m.zoom_to_box(lyr.envelope()) >> mapnik.render_to_file(m,i, 'png') >> print "La imagen " +i+ " fue creada." >> elif geo == 1: >> print "Trabajando mapa "+ruta+"\\"+filename+" con >> geometria "+ str(geo) >> blue = >> mapnik.PointSymbolizer('C:\Python26\icono.png','png',50,50) >> blue.allow_overlap = True >> s=mapnik.Style() >> r=mapnik.Rule() >> r.symbols.append(blue) >> s.rules.append(r) >> #s.rules.append(blue) >> m.append_style('My Style',s) >> lyr = mapnik.Layer('world',"+proj=latlong >> +datum=WGS84") >> lyr.datasource = >> mapnik.Shapefile(base=ruta,file=archivo[0]) >> lyr.styles.append('My Style') >> m.layers.append(lyr) >> m.zoom_to_box(lyr.envelope()) >> mapnik.render_to_file(m,i, 'png') >> print "La imagen " +i+ " fue creada." >> else: >> print "Algo fallo y no entro a ninguna de las >> geometrias" >> print "Listo" >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > > > > > > > > > > > > > > > > > > > > > > > > > > > well i'm not 100% what's going on because it appears to line up when I copy > it to my IDE, but you are mixing tabs or # of space indents, you will raise > that error, as an example: > a= None > if a is None: > print 'a' > print True > > The print 'a' line is four spaces (my default) and the print True is five. > When run it raises the following: > > print True >> ^ >> IndentationError: unexpected indent > > > On a side note, if what you want to do is keep working while you work on > the rest of it, you should use the pass statement. At least that is what I > do. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From vincentbalmori at yahoo.com Wed Jun 15 21:35:49 2011 From: vincentbalmori at yahoo.com (Vincent Balmori) Date: Wed, 15 Jun 2011 12:35:49 -0700 (PDT) Subject: [Tutor] Step Value Message-ID: <451595.67875.qm@web59406.mail.ac4.yahoo.com> I am still working on that one question in the absolute beginners with the the ask_number function and step value. Honestly, I still have no idea what to do. This is one of my many attempts, but I know that it's wrong. def ask_number(question, low, high): """Ask for a number within a range.""" response = None if response in range(low, high, 1): return response while response not in range(low, high): response = int(input(question)) return response I tried to find clues by looking at the later section that calls on the ask_number function: def human_move(board, human): """Get human move.""" legal = legal_moves(board) move = None while move not in legal: move = ask_number("Where will you move? (0 - 8):", 0, NUM_SQUARES) if move not in legal: print("\nThat square is already occupied, foolish human. Choose another.\n") print("Fine...") return move -------------- next part -------------- An HTML attachment was scrubbed... URL: From eire1130 at gmail.com Wed Jun 15 21:57:35 2011 From: eire1130 at gmail.com (James Reynolds) Date: Wed, 15 Jun 2011 15:57:35 -0400 Subject: [Tutor] Step Value In-Reply-To: <451595.67875.qm@web59406.mail.ac4.yahoo.com> References: <451595.67875.qm@web59406.mail.ac4.yahoo.com> Message-ID: Without looking at your code, What is it that you know that's wrong about it? Are you getting a return value which you know is incorrect, is the program throwing error and you aren't sure why? or do you just suspect it is wrong but you aren't sure? When posing a question, it's helpful to know the things above because those answering might not know exactly what your problem is. with regards to the step value of range, here, "if response in range(low, high, 1)" the default step value of range() is 1, so you don't need to have that. range(1,3) will give you a list [1,2], for example. On Wed, Jun 15, 2011 at 3:35 PM, Vincent Balmori wrote: > I am still working on that one question in the absolute beginners with the > the ask_number function and step value. Honestly, I still have no idea what > to do. This is one of my many attempts, but I know that it's wrong. > > def ask_number(question, low, high): > """Ask for a number within a range.""" > response = None > if response in range(low, high, 1): > return response > while response not in range(low, high): > response = int(input(question)) > return response > > I tried to find clues by looking at the later section that calls on the > ask_number function: > > def human_move(board, human): > """Get human move.""" > legal = legal_moves(board) > move = None > while move not in legal: > move = ask_number("Where will you move? (0 - 8):", 0, NUM_SQUARES) > if move not in legal: > print("\nThat square is already occupied, foolish human. > Choose another.\n") > print("Fine...") > return move > > _______________________________________________ > 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 vincentbalmori at yahoo.com Wed Jun 15 22:02:53 2011 From: vincentbalmori at yahoo.com (Vincent Balmori) Date: Wed, 15 Jun 2011 13:02:53 -0700 (PDT) Subject: [Tutor] step value Message-ID: <744120.29347.qm@web59408.mail.ac4.yahoo.com> The question to that code I am trying to solve is "Improve the function ask_number() so that the function can be called with a step value. Make the default value of step 1." -------------- next part -------------- An HTML attachment was scrubbed... URL: From g.nius.ck at gmail.com Wed Jun 15 23:41:15 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Wed, 15 Jun 2011 17:41:15 -0400 Subject: [Tutor] Connection Error Message-ID: I was playing around with socket. It raised a connection error when I tried to connect a non-local client to a linux server. It timed out when I tried to connect a Linux client to a Windows server. I did succeed when I: connected a Linux client to a local server connected a Windows client to a local server and connected a Android client to a Windows server The client program I was using was Alert_Sender and Alert_Sender_mobile. The server program I was using was Alert_Server. Alert_Recv is also a client, but I plan to always be on the same machine as the Alert_Server. Server and Client are modules I designed to greatly simplify the socket module (feel free to download for you own use.) -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: Alert_Server.py Type: application/octet-stream Size: 1628 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: Alert_Recv.py Type: application/octet-stream Size: 1769 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: Alert_Sender.py Type: application/octet-stream Size: 881 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: Alert_Sender_Mobile.py Type: application/octet-stream Size: 505 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: server.pyc Type: application/octet-stream Size: 8467 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: client.py Type: application/octet-stream Size: 3591 bytes Desc: not available URL: From eire1130 at gmail.com Thu Jun 16 00:22:06 2011 From: eire1130 at gmail.com (James Reynolds) Date: Wed, 15 Jun 2011 18:22:06 -0400 Subject: [Tutor] step value In-Reply-To: <744120.29347.qm@web59408.mail.ac4.yahoo.com> References: <744120.29347.qm@web59408.mail.ac4.yahoo.com> Message-ID: I am copying and pasting your code here from the previous email: def ask_number(question, low, high): > """Ask for a number within a range.""" > response = None > if response in range(low, high, 1): > return response > while response not in range(low, high): > response = int(input(question)) > return response > I tried to find clues by looking at the later section that calls on the > ask_number function: > def human_move(board, human): > """Get human move.""" > legal = legal_moves(board) > move = None > while move not in legal: > move = ask_number("Where will you move? (0 - 8):", 0, NUM_SQUARES) > if move not in legal: > print("\nThat square is already occupied, foolish human. > Choose another.\n") > print("Fine...") > return move As to the question, I think what you are missing is, how do you make a default value in a function parameter? So, for example, let's say I have a function called, enchilada with a few parameters. guac, spicey, so it might look like this: def enchildada(guac, spicey): do stuff with guac and spiceyness. return tasty_ness And I can call that function like this: a = enchilada(True, True) But, let's say I want there to be a default vale for Spicey. Maybe I have heartburn and I happen to enjoy heartburn every day at around noontime, so my default option for spcicey is True. I would then write the function like this: def enchildada(guac, spicey=True): do stuff with guac and spiceyness. return tasty_nes Now, when I call my enchilada function, I can call it like this: a = enchilada(True) and the default value for spicey is True and it returns a tasty encilada. But, lets say my heartburn is beyond all rationality and I want a non-spicey enchilada, i can override that default: a = enchilada(True, False) That is what the author meant by a default value and this just becomes a variable you enter into the range function (so, a default of 1, and you can change this to 2,3,etc) On Wed, Jun 15, 2011 at 4:02 PM, Vincent Balmori wrote: > The question to that code I am trying to solve is > > "Improve the function *ask_number()* so that the function can be called > with a step value. Make the default value of step *1*." > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Jun 16 01:25:13 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 16 Jun 2011 00:25:13 +0100 Subject: [Tutor] using python to write web page References: <557213.35730.qm@web161306.mail.bf1.yahoo.com> Message-ID: "Michael bridges" wrote >i would like to use python to write a web page like > writing an html file that is displayed in a browser > without having to run a server. OK, So whats the problem? Python can create html files so if you only want to create an html file just do it: content = """

Hello world

""" open("myfile.htm","w").write(contents) > found a few options, but need to have server running. That depends on how you are loading the page into the browser. If you use FileOpen from the menu you can read the file as usual. If you want to access it over a network you either need to mount the remote file system or you need a web server of some sort. Creating an html file in Python is trivial(see above) How you access it is another mattwer entirely and for that we need more info. > https://skulpt.googlecode.com/hg/skulpt > gives 404 error I have no idea what you are trying to tell us with that bit of information. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Jun 16 01:28:17 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 16 Jun 2011 00:28:17 +0100 Subject: [Tutor] Step Value References: <451595.67875.qm@web59406.mail.ac4.yahoo.com> Message-ID: "Vincent Balmori" wrote >I am still working on that one question in the absolute beginners >with the the > ask_number function and step value. Honestly, I still have no idea > what to do. Take it stage by stage. Define the function so that it takes a step parameter with a default value of 1. Don;t try to usde that value just modify the definition so that it takes the extra parameter. Send us what you do so we can see it. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Thu Jun 16 01:52:46 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 16 Jun 2011 09:52:46 +1000 Subject: [Tutor] step value In-Reply-To: <744120.29347.qm@web59408.mail.ac4.yahoo.com> References: <744120.29347.qm@web59408.mail.ac4.yahoo.com> Message-ID: <4DF945CE.30508@pearwood.info> Vincent Balmori wrote: > The question to that code I am trying to solve is > > "Improve the function ask_number() so that the function can be called with a > step value. Make the default value of step 1." You need to be able to tell ask_number what step function you want to use. So it isn't enough to hard-code step=1 inside the function, step needs to be set when you call the function. Currently you can do this: result = ask_number(question, low, high) You need to be able to do this: result = ask_number(question, low, high, step) where step is *optional*. So you need to: * change the ask_number function to accept a fourth argument; * make it optional rather than required; * give it a sensible default value; * within the function, that value must then be passed to range -- Steven From alan.gauld at btinternet.com Thu Jun 16 01:54:13 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Thu, 16 Jun 2011 00:54:13 +0100 (BST) Subject: [Tutor] using python to write web page In-Reply-To: <90865.90971.qm@web161308.mail.bf1.yahoo.com> References: <90865.90971.qm@web161308.mail.bf1.yahoo.com> Message-ID: <759106.94112.qm@web86707.mail.ird.yahoo.com> From: Michael bridges To: Alan Gauld Sent: Thursday, 16 June, 2011 0:43:35 Subject: Re: [Tutor] using python to write web page > i do not want to write html, not in whole or in part, nor in reference. > just 100% python. not from a server. The code I showed was 100% Python that created an html file that could be opened in a browser without a server. > i want to write the python only code and have python > only code make the web page that can be read on > any computer with a web browser. Thats exactly what my code does. > no server use, no server down load, no server at all. Thats exactly what my code does. > no python interrupter. No idea what you mean here? If you mean no Python interpreter how do you expect to execute the python code? If you mean you want to read the resultant file without using Python then.... thats exactly what my code does. So does my sample code meet your needs, or is there some other requirement that you haven't explained yet? --- On Wed, 6/15/11, Alan Gauld wrote: > Python can create html files so if you only want to create > an html file just do it: > > content = """ > >

Hello world

> """ > > open("myfile.htm","w").write(contents) > Alan G -------------- next part -------------- An HTML attachment was scrubbed... URL: From naheedcse at gmail.com Thu Jun 16 02:46:56 2011 From: naheedcse at gmail.com (naheed arafat) Date: Thu, 16 Jun 2011 06:46:56 +0600 Subject: [Tutor] using python to write web page In-Reply-To: <557213.35730.qm@web161306.mail.bf1.yahoo.com> References: <557213.35730.qm@web161306.mail.bf1.yahoo.com> Message-ID: Got a question in this context. If i would like to edit an html file. suppose i want to edit the values of href tags or the img tags, what should i do? should I 1. read the file as string, 2.parse it for the tags, 3.edit the tags 4.and then replace the tags by the editted tags 5.delete the main file 6. write a new one with the same name? Or there is any python module to get this job done? -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Thu Jun 16 02:53:02 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 16 Jun 2011 10:53:02 +1000 Subject: [Tutor] using python to write web page In-Reply-To: References: <557213.35730.qm@web161306.mail.bf1.yahoo.com> Message-ID: <4DF953EE.7080502@pearwood.info> naheed arafat wrote: > Got a question in this context. If i would like to edit an html file. > suppose i want to edit the values of href tags or the img tags, what should > i do? This question is more general than just editing HTML files. The same question, and answer, applies to editing *any* file small enough to fit in memory. (If you want to edit 30 GB video files, you don't want to do this...) * read the file * make the changes you want to make * write the file back That's good enough for quick scripts, but for serious applications you want to be more careful about avoiding data loss. For example you might do this: * read the file * make the changes you want to make * write the file to a temporary file * atomically replace the original with the new version or this: * read the file * make the changes you want to make * save a backup copy of the original * write the file over the original * if that succeeds, remove the backup copy or similar. -- Steven From swiftone at swiftone.org Thu Jun 16 03:02:21 2011 From: swiftone at swiftone.org (Brett Ritter) Date: Wed, 15 Jun 2011 21:02:21 -0400 Subject: [Tutor] using python to write web page In-Reply-To: References: <557213.35730.qm@web161306.mail.bf1.yahoo.com> Message-ID: On Wed, Jun 15, 2011 at 8:46 PM, naheed arafat wrote: > Or there is any python module to get this job done? The normal way this sort of thing is handled is that the HTML is in some form of template, where the tags you are talking about editing are variables. A common example is a web-based form where you want to present either a blank form or the same form pre-populated. So rather than generating the HTML, then editing it to be different you instead simple set the variables and generate the HTML and the result reflects whatever the variables were set to. There are multiple modules for such templates. This is assuming that you generate the HTML in the first place instead of trying to edit someone elses existing HTML. In that case you'd proceed as you described. -- Brett Ritter / SwiftOne swiftone at swiftone.org From wolfrage8765 at gmail.com Thu Jun 16 04:20:32 2011 From: wolfrage8765 at gmail.com (WolfRage) Date: Wed, 15 Jun 2011 19:20:32 -0700 Subject: [Tutor] Already Initialized Object Inheritance? In-Reply-To: References: <1308113247.1952.45.camel@wolfrage-LE1600> Message-ID: <1308190832.1952.87.camel@wolfrage-LE1600> Christopher, Thank you for the explanation of the error. I see now why I am unable to reference it outside of __init__'s scope. No, I did not mean to do that. I will include further details in my reply to Steven. Please feel free to jump in on that conversation to continue my learning. Thank you for your help and time thus far. -- Jordan On Wed, 2011-06-15 at 09:45 -0400, Christopher King wrote: > Oh, I think I see the error. > self=stdscr > This will just make the variable called self be assigned to > stdscr with in __init__ This will not make the object actually turn > into stdscr > Or maybe you meant do that, because I don't know what stdscr or > the curses module is > > On Wed, Jun 15, 2011 at 12:47 AM, WolfRage > wrote: > I can not get this to behave in the manor that I would like. I > am trying > to have an object refereed to as CursesApp.Screen become the > already > initialized object "stdscr". To elaborate I would like it to > become that > object but to also be able to define additional methods and > properties, > so more along the lines of inherit from "stdscr". Is this even > possible? > Well I can make it equal to that object I can not add > additional methods > and properties to it? Additionally, so that I learn; where has > my > thinking been too short sited? Thank you for your help. > -- > Jordan > > ****CODE BELOW**** > > #!/usr/bin/python3 > """With thi method I can make the class "Screen" become > "stdscr" but if > I refernce any of the new methods or properties the > applications > promptly fails and notifies me that the method or property > does not > exist. Another downside of this method is I can not reference > self.Screen.* or it crashes.""" > import curses > class CursesApp: > def __init__(self, stdscr): > self.Screen(stdscr) #This is the stdscr object. > > curses.init_pair(1,curses.COLOR_BLUE,curses.COLOR_YELLOW) > #self.Screen.bkgd(' ', curses.color_pair(1)) > #self.mainLoop() > > #def mainLoop(self): > #while 1: > #self.Screen.refresh() > #key=self.Screen.getch() > #if key==ord('q'): break > > class Screen: > def __init__(self,stdscr): > self=stdscr > #self.height, self.width = self.getmaxyx() # any > reference > to these crashes > #self.offsety, self.offsetx = -self.height/2, > -self.width/2 > # any reference to these crashes > #self.curx, self.cury = 1, 1 # any reference to > these > crashes > self.clear() > self.border(0) > while 1: > self.refresh() > key=self.getch() > if key==ord('q'): break > > def main(): > cursesapp = curses.wrapper(setup) > > def setup(stdscr): > CursesApp(stdscr) > > if __name__ == '__main__': > main() > > > > ****CODE BELOW**** > > #!/usr/bin/python3 > """With this method I can make "Screen" become "stdscr" but if > I > obviously can not even define any new methods or properties. > But atleast > the references can be used through out the class with out > crashing.""" > import curses > class CursesApp: > def __init__(self, stdscr): > self.Screen=stdscr #This is the stdscr object. > > curses.init_pair(1,curses.COLOR_BLUE,curses.COLOR_YELLOW) > self.Screen.bkgd(' ', curses.color_pair(1)) > self.mainLoop() > > def mainLoop(self): > while 1: > self.Screen.refresh() > key=self.Screen.getch() > if key==ord('q'): break > > def main(): > cursesapp = curses.wrapper(setup) > > def setup(stdscr): > CursesApp(stdscr) > > if __name__ == '__main__': > main() > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > From wolfrage8765 at gmail.com Thu Jun 16 04:20:39 2011 From: wolfrage8765 at gmail.com (WolfRage) Date: Wed, 15 Jun 2011 19:20:39 -0700 Subject: [Tutor] Tutor Digest, Vol 88, Issue 56 In-Reply-To: References: Message-ID: <1308190839.1952.88.camel@wolfrage-LE1600> > From: Steven D'Aprano > To: Python Tutor > Subject: Re: [Tutor] Already Initialized Object Inheritance? > Message-ID: <4DF898E9.5050104 at pearwood.info> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > WolfRage wrote: > > Unfortunately I am not able to inherit "stdscr" using that method. As > > Python returns with an error stating that "stdscr" is not defined. This > > error is returned at run time and by the compiler prior to actual > > execution. If you would like I can write a quick example that will > > generate the error message for that method. > > You shouldn't need to ask that question, just do it. Ahh... sorry? ****CODE BELOW**** #!/usr/bin/python3 """With this method I can make the class "Screen" become "stdscr" but if I refernce any of the new methods or properties the applications promptly fails and notifies me that the attribute does not exist.""" import curses class CursesApp: def __init__(self, stdscr): self.Screen=stdscr #This is the stdscr object. curses.init_pair(1,curses.COLOR_BLUE,curses.COLOR_YELLOW) self.Screen.bkgd(' ', curses.color_pair(1)) self.mainLoop() def mainLoop(self): while 1: self.Screen.refresh() key=self.Screen.getch() if key==ord('q'): break self.Screen.height=10 #This is the line that crashes, because it is not an attribute of "stdscr". class Screen: def __init__(self): self.height, self.width = self.getmaxyx() self.offsety, self.offsetx = -self.height/2, -self.width/2 self.curx, self.cury = 1, 1 def main(): cursesapp = curses.wrapper(setup) def setup(stdscr): CursesApp(stdscr) if __name__ == '__main__': main() ****CODE ABOVE**** > > My guess is that the error you get is a NameError. The solution to that > is to fix the name error, not to run off chasing wild geese. Object > inheritance? This has nothing to do with that! Hmm... You seem to think that I should know this automatically, but obviously I do not. Did I write the correct mailing-list? Is this not a place to learn? Exclamation points are very similar to all caps. The error is actually an attribute does not exist error, output as requested is further down in the email. Although you would think I would cause a name collision, but Python ignores the class defined as Screen; even if I initialize it, because it is already defined. So this does not cause a NameError, but it does cause a TypeError, because "self.Screen" is a "curses.curses window" which is not a callable object. The code demonstrating this error is also listed below at the end of the email. > What is stdscr? Where does it come from? How is it defined? "stdscr" is a Curses window object. Window objects in Curses are usually created with the "curses.newwin()" function. However "stdscr" is special in that it is created when "curses.initscr()" is run. "curses.initscr()" creates a window object and returns it, "stdscr", that takes up the available space in the terminal or screen. "curses.initscr()" is not present in the code because it is executed by "curses.wrapper()", as part of the terminal safe initialization process for Curses. Hopefully this answers your three questions satisfactorily. Reference: http://docs.python.org/library/curses.html > > Please copy and paste the *exact* error message you get, including the > full traceback. > ****CODE/ERROR OUTPUT BELOW**** $ python3 quick_test.py Traceback (most recent call last): File "quick_test.py", line 31, in main() File "quick_test.py", line 25, in main cursesapp = curses.wrapper(setup) File "/usr/lib/python3.2/curses/wrapper.py", line 43, in wrapper return func(stdscr, *args, **kwds) File "quick_test.py", line 28, in setup CursesApp(stdscr) File "quick_test.py", line 9, in __init__ self.mainLoop() File "quick_test.py", line 16, in mainLoop self.Screen.height=10 #This is the line that crashes, because it is not an attribute of "stdscr". AttributeError: '_curses.curses window' object has no attribute 'height' ****CODE/ERROR OUTPUT ABOVE**** > > -- > Steven ****CODE BELOW**** #!/usr/bin/python3 """With this method we cause a TypeError, because the window object is not callable.""" import curses class CursesApp: def __init__(self, stdscr): self.Screen=stdscr #This is the stdscr object. curses.init_pair(1,curses.COLOR_BLUE,curses.COLOR_YELLOW) self.Screen() #So now we will initialize "self.Screen()" and we will cause the TypeError. self.Screen.bkgd(' ', curses.color_pair(1)) self.mainLoop() def mainLoop(self): while 1: self.Screen.refresh() key=self.Screen.getch() if key==ord('q'): break self.Screen.height=10 #We never get here because we caused a TypeError. class Screen: def __init__(self): self.height, self.width = self.getmaxyx() self.offsety, self.offsetx = -self.height/2, -self.width/2 self.curx, self.cury = 1, 1 def main(): cursesapp = curses.wrapper(setup) def setup(stdscr): CursesApp(stdscr) if __name__ == '__main__': main() ****CODE ABOVE**** ****CODE/ERROR OUTPUT BELOW**** $ python3 quick_test.py Traceback (most recent call last): File "quick_test.py", line 32, in main() File "quick_test.py", line 26, in main cursesapp = curses.wrapper(setup) File "/usr/lib/python3.2/curses/wrapper.py", line 43, in wrapper return func(stdscr, *args, **kwds) File "quick_test.py", line 29, in setup CursesApp(stdscr) File "quick_test.py", line 8, in __init__ self.Screen() #So now we will initialize "self.Screen()" and we will cause the TypeError. TypeError: '_curses.curses window' object is not callable ****CODE/ERROR OUTPUT ABOVE**** But this leaves me with four problems and I still would like a solution if one is possible. Thank you for your time and help in understanding what I am doing wrong. -- Jordan From wolfrage8765 at gmail.com Thu Jun 16 08:41:57 2011 From: wolfrage8765 at gmail.com (WolfRage) Date: Wed, 15 Jun 2011 23:41:57 -0700 Subject: [Tutor] Already Initialized Object Inheritance? Message-ID: <1308206517.1952.97.camel@wolfrage-LE1600> All, I have found a way to use __getattr__() to redirect failed calls to the variable that holds 'stdscr'. I will draw up some better potential code tomorrow, and then you can provide me feedback, for a potentially better method. Or perhaps optimized code. I think I also understand OOP a little better and realize I was making some simple silly mistakes with things like trying to call static methods versus initializing a object and thus my examples need a drastic re-work to make them make more sense. Thank you Steven and Christopher for your help so far. I should have the new code out tomorrow night. But now it is time for bed. -- Jordan From alan.gauld at btinternet.com Thu Jun 16 10:09:40 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Thu, 16 Jun 2011 09:09:40 +0100 (BST) Subject: [Tutor] using python to write web page In-Reply-To: <790750.28001.qm@web161306.mail.bf1.yahoo.com> References: <790750.28001.qm@web161306.mail.bf1.yahoo.com> Message-ID: <389513.85883.qm@web86705.mail.ird.yahoo.com> ________________________________ From: Michael bridges To: ALAN GAULD Sent: Thursday, 16 June, 2011 1:07:14 Subject: Re: [Tutor] using python to write web page > your python code includes html. OK, Now I understand. > i write the python only code --> web page > [ do not care if it is html, xhtml, java, javascript, or whatever] But a "web page" is by definition html. Thats what makes it a web page. Most browsers can display plain text too but they will usually mess up the formatting so that it is hard to read. If you want to do that then just create a normal text file. But if you want the browser4 to display it with any kind of formatting you must use html, thats all the browser understands. > if i wanted to write html in the python i would just write the html > not sure how else the restate, rewrite The reasons for writing the html from Python are that you can insert dynamic content into the html, such as names or values from a database, or from another file: ##################### contentStart = """"

Here are the current members of my club:

""" contentEnd = """ """ data = ["Eric Idle", "Michael Palin", "Graham Chapman"] with open("mywebpage.htm","w") as webpage: webpage.write(contentStart) webpage.write("
    \n") for name in data: webpage.write("
  • %s
  • " % name) webpage.write("
\n") webpage.write(contentEnd) ####################### Now you can regenerate the web file by just adding names to data. (and you could populate data from a text file or database etc) But if you want that to display sensibly in a web browser you need to use html. HTH, Alan G. --- On Wed, 6/15/11, ALAN GAULD wrote: >From: ALAN GAULD >Subject: Re: [Tutor] using python to write web page >To: "Michael bridges" >Cc: "tutor at python.org" >Date: Wednesday, June 15, 2011, 4:54 PM > > > > >From: Michael bridges > >To: Alan Gauld >Sent: Thursday, 16 June, 2011 0:43:35 >Subject: Re: [Tutor] using python to write web page > >> i do not want to write html, not in whole or in part, nor in reference. >> just 100% python. not from a server. > >The code I showed was 100% Python that created an html file >that could be opened in a browser without a server. > >> i want to write the python only code and have python >> only code make the web page that can be read on >> any computer with a web browser. > >Thats exactly what my code does. > >> no server use, no server down load, no server at all. > >Thats exactly what my code does. > >> no python interrupter. > >No idea what you mean here? >If you mean no Python interpreter how do you expect to >execute the python code? >If you mean you want to read the resultant file without >using Python then.... thats exactly what my code does. > >So does my sample code meet your needs, or is there >some other requirement that you haven't explained yet? > > >--- On Wed, 6/15/11, Alan Gauld wrote: > >> Python can create html files so if you only want to create >> an html file just do it: >> >> content = """ >> >>

Hello world

>> """ >> >> open("myfile.htm","w").write(contents) >> > >Alan G > -------------- next part -------------- An HTML attachment was scrubbed... URL: From delegbede at dudupay.com Thu Jun 16 11:00:20 2011 From: delegbede at dudupay.com (Dipo Elegbede) Date: Thu, 16 Jun 2011 10:00:20 +0100 Subject: [Tutor] GTALK and PYTHON Message-ID: Hi All, I want to write an application in python with which I can log into gtalk. Kindly point me to any documentation with which I can move on. Advices too would be of great help.. Thanks. -- Elegbede Muhammed Oladipupo OCA +2348077682428 +2347042171716 www.dudupay.com Mobile Banking Solutions | Transaction Processing | Enterprise Application Development -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Thu Jun 16 11:45:01 2011 From: wprins at gmail.com (Walter Prins) Date: Thu, 16 Jun 2011 10:45:01 +0100 Subject: [Tutor] using python to write web page In-Reply-To: <557213.35730.qm@web161306.mail.bf1.yahoo.com> References: <557213.35730.qm@web161306.mail.bf1.yahoo.com> Message-ID: Have a look at the Pyjamas project: http://pyjs.org/ It sounds like what you want. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Jun 16 12:26:36 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 16 Jun 2011 11:26:36 +0100 Subject: [Tutor] using python to write web page References: <557213.35730.qm@web161306.mail.bf1.yahoo.com> Message-ID: "Walter Prins" wrote > Have a look at the Pyjamas project: http://pyjs.org/ It sounds like > what > you want. I hadn't considered using pyjamas outside a web server environment but I guess you could since it just creates an html/javascript file. It depends on what the OP wants to put in his "web page" but Pyjamas would certainly allow him to create an html page from pure Python which is what he says he wants. But for static data, raw html is IMHO easier to use. Pyjamas is more useful for building web applications than for generating single pages. But if he prefers to use python for everything pyjamas may well work for him. good call, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Thu Jun 16 15:33:44 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 16 Jun 2011 23:33:44 +1000 Subject: [Tutor] Tutor Digest, Vol 88, Issue 56 In-Reply-To: <1308190839.1952.88.camel@wolfrage-LE1600> References: <1308190839.1952.88.camel@wolfrage-LE1600> Message-ID: <4DFA0638.2040808@pearwood.info> WolfRage wrote: > ****CODE BELOW**** > #!/usr/bin/python3 > """With this method I can make the class "Screen" become "stdscr" but if > I refernce any of the new methods or properties the applications > promptly fails and notifies me that the attribute does not exist.""" That's because it doesn't exist. stdscr is a curses window, which does not have an attribute "height". I think you want self.Screen.getmaxyx() which will return a tuple (height, width) of the window. -- Steven From timomlists at gmail.com Thu Jun 16 18:48:18 2011 From: timomlists at gmail.com (Timo) Date: Thu, 16 Jun 2011 18:48:18 +0200 Subject: [Tutor] GTALK and PYTHON In-Reply-To: References: Message-ID: <4DFA33D2.9020307@gmail.com> On 16-06-11 11:00, Dipo Elegbede wrote: > Hi All, > > I want to write an application in python with which I can log into gtalk. > > Kindly point me to any documentation with which I can move on. Not to be rude, but did you use Google before asking here? There are a lot of examples and how-to's. You could also look at the program Emesene, they have a feature to login to GTalk. Cheers, Timo > > Advices too would be of great help.. > > Thanks. > > -- > Elegbede Muhammed Oladipupo > OCA > +2348077682428 > +2347042171716 > www.dudupay.com > Mobile Banking Solutions | Transaction Processing | Enterprise > Application Development > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From steve at alchemy.com Thu Jun 16 18:52:21 2011 From: steve at alchemy.com (Steve Willoughby) Date: Thu, 16 Jun 2011 09:52:21 -0700 Subject: [Tutor] Weird tkFont behavior Message-ID: <4DFA34C5.4060404@alchemy.com> I'm probably just doing something stupid, but I can't spot the error. I hope someone here can see what I'm looking past, or knows of a known issue with these widgets. I'm writing a GUI app using ttk widgets in Tkinter, which includes text displayed in a regular text widget. Some text in the widget will be in Italics, some bold, some both, some regular. I assigned those font effects as tags for the text widget as you can see in the code below. However, when I run it, about 10% of the time, the text widget will come up with random fonts (e.g., bold italic instead of plain roman), even though I confirmed that it's using 'rm' as the tag when inserting the text into the widget. The initial setup code includes: f = Tkinter.Text(self, ...) f.tag_config('rm', font=tkFont.Font(family='Helvetica', size=10, weight=tkFont.NORMAL, slant-tkFont.ROMAN)) f.tag_config('bf', font=tkFont.Font(family="Helvetica', size=10, weight=tkFont.BOLD, slant=tkFont.ROMAN)) f.tag_config('it', font=tkFont.Font(family="Helvetica', size=10, weight=tkFont.NORMAL, slant=tkFont.ITALIC)) f.tag_config('bi', font=tkFont.Font(family="Helvetica', size=10, weight=tkFont.BOLD, slant=tkFont.ITALIC)) f.tag_config('ref', font=tkFont.Font(family="Helvetica', size=10, weight=tkFont.NORMAL, slant=tkFont.ITALIC), foreground='blue', underline=True) text is inserted simply by: f.insert(END, text, 'rm') and yet some of the time, even though the 'rm' tag is there, I get one of the other fonts I configured for the other tags. Do I need to keep other references to the tkFont objects somewhere else or something? -- 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 mywrkid at yahoo.com Thu Jun 16 19:03:55 2011 From: mywrkid at yahoo.com (Neha P) Date: Thu, 16 Jun 2011 10:03:55 -0700 (PDT) Subject: [Tutor] File parsing Message-ID: <615438.59424.qm@web121808.mail.ne1.yahoo.com> Hi all, I know below query may sound silly, but can somebody suggest any better way of doing this: It would be helpful. I need to read a file line by line and print each line starting from the last word first: ? C:\Python26>type file_reversing_program.txt import sys import string f_obj=open(sys.argv[1],"r") for eachline in f_obj: ? ?eachline=eachline[ :-1]# to eliminate the trailing "\n"? ? ? list_words=eachline.split(" ") ? ?list_words[0]=list_words[0]+"\n"# to add "\n" so that after line 1 is printed, line 2 should start on a new line? ? ? list_words.reverse() ? ? for every_word in list_words: ? ? ? ? ?print every_word,# ?'comma' helps in printing words on same line,hence for last word we append "\n"? f_obj.close() C:\Python26>type input_file.txt "Hi ther, how are you?" I are doing fine, thank you. C:\Python26>file_reversing_program.py input_file.txt you?" are how ther,"Hi you. thank fine, doing are I Is there a better way of doing the above program, mainly the text highlighted in yellow, Also if that is settled can there be a logic for getting the ouput more properly formatted?(for text in blue)?,? say giving an output like ?: "you? are how ther, Hi" you. thank fine, doing are I Thanks, Neha -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Thu Jun 16 19:09:34 2011 From: steve at alchemy.com (Steve Willoughby) Date: Thu, 16 Jun 2011 10:09:34 -0700 Subject: [Tutor] Weird tkFont behavior In-Reply-To: <4DFA34C5.4060404@alchemy.com> References: <4DFA34C5.4060404@alchemy.com> Message-ID: <4DFA38CE.7060604@alchemy.com> On 16-Jun-11 09:52, Steve Willoughby wrote: > I'm probably just doing something stupid, but I can't spot the error. I > hope someone here can see what I'm looking past, or knows of a known > issue with these widgets. I think I solved it, actually.. as I was typing this up, I wondered in passing about this: > of the other fonts I configured for the other tags. Do I need to keep > other references to the tkFont objects somewhere else or something? and I think that was it. I recoded it so that I store the Font objects independently of the tag configuration call, in case they were getting destroyed accidentally somewhere (I know you have to do that with other Tk objects such as images), and now I can't get the app to fail. If interested, here's the new setup code: | f=Tkinter.Text(self, ...) | | self.font_tags = {} | for tag, weight, slant, others in ( | ('rm', tkFont.NORMAL, tkFont.ROMAN, {}), | ('bf', tkFont.BOLD, tkFont.ROMAN, {}), | ('it', tkFont.NORMAL, tkFont.ITALIC, {}), | ('bi', tkFont.BOLD, tkFont.ITALIC, {}), | ('ref',tkFont.NORMAL, tkFont.ITALIC, {'foreground':'blue', 'underline':True}), | ): | self.font_tags[tag] = tkFont.Font(family='Helvetica', size=10, weight=weight, slant=slant) | f.tag_config(tag, font=self.font_tags[tag], **others) (Added "|" in the left column to hopefully get the text to indent right with some mail readers. That's not part of the code, of course.) -- 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 lisi.reisz at gmail.com Thu Jun 16 19:10:58 2011 From: lisi.reisz at gmail.com (Lisi) Date: Thu, 16 Jun 2011 18:10:58 +0100 Subject: [Tutor] Beginner puzzle with unpacking argv Message-ID: <201106161810.58716.lisi.reisz@gmail.com> Copied and pasted: From text of Learn Python the Hard Way 1 from sys import argv 2 3 script, user_name = argv From my script (typed, not copied and pasted, but copied and pasted from my script to here): 1 from sys import argv 2 3 script, user_name = argv I have tried every permutation of white space I could think of that might have looked like the original, but I always get the same error: lisi at Tux:~/Python/LearnPythonTheHardWay$ python ex14.py Traceback (most recent call last): File "ex14.py", line 3, in script, user_name=argv ValueError: need more than 1 value to unpack I haven't got past line 3 yet!! I know that you need the right number of variables, but my script has got as many as the original - it's the same as the original! Help! Lisi From steve at alchemy.com Thu Jun 16 20:03:12 2011 From: steve at alchemy.com (Steve Willoughby) Date: Thu, 16 Jun 2011 11:03:12 -0700 Subject: [Tutor] Beginner puzzle with unpacking argv In-Reply-To: <201106161810.58716.lisi.reisz@gmail.com> References: <201106161810.58716.lisi.reisz@gmail.com> Message-ID: <4DFA4560.7060305@alchemy.com> On 16-Jun-11 10:10, Lisi wrote: > 1 from sys import argv > 2 > 3 script, user_name = argv > > I have tried every permutation of white space I could think of that might have > looked like the original, but I always get the same error: That will work ONLY if argv has at least 2 values in it. Your source code is ok as far as it goes. Try running your script with two command line arguments and see what you get. (The first argument should be the name of your script, incidentally). If your script were named foo.py, then running the command: > foo.py would give you the error you see because argv only has 1 thing in it and you're trying to retrieve two. If you ran it as: > foo.py bar that should work, and script would be "foo.py" and user_name would be "bar". You could check len(argv) first to see how many items you have before you try to get two values from it. For more sophisticated argument handling, you could look at the optparse or argparse modules (but that's beyond the beginner level--something to keep in mind for later). -- 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 joel.goldstick at gmail.com Thu Jun 16 20:03:27 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 16 Jun 2011 14:03:27 -0400 Subject: [Tutor] Beginner puzzle with unpacking argv In-Reply-To: <201106161810.58716.lisi.reisz@gmail.com> References: <201106161810.58716.lisi.reisz@gmail.com> Message-ID: On Thu, Jun 16, 2011 at 1:10 PM, Lisi wrote: > Copied and pasted: > >From text of Learn Python the Hard Way > > 1 from sys import argv > 2 > 3 script, user_name = argv > > >From my script (typed, not copied and pasted, but copied and pasted from > my > script to here): > > 1 from sys import argv > 2 > 3 script, user_name = argv > > I have tried every permutation of white space I could think of that might > have > looked like the original, but I always get the same error: > > lisi at Tux:~/Python/LearnPythonTheHardWay$ python ex14.py > Traceback (most recent call last): > File "ex14.py", line 3, in > script, user_name=argv > ValueError: need more than 1 value to unpack > > I haven't got past line 3 yet!! I know that you need the right number of > variables, but my script has got as many as the original - it's the same as > the original! > > Help! > > Lisi > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > when you run the program you are not giving it any arguments to read. argv[0] is the name of your script. But you are not providing a value for user_name to consume Try this: lisi at Tux:~/Python/LearnPythonTheHardWay$ python ex14.py Lisi -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From eire1130 at gmail.com Thu Jun 16 20:43:58 2011 From: eire1130 at gmail.com (James Reynolds) Date: Thu, 16 Jun 2011 14:43:58 -0400 Subject: [Tutor] File parsing In-Reply-To: <615438.59424.qm@web121808.mail.ne1.yahoo.com> References: <615438.59424.qm@web121808.mail.ne1.yahoo.com> Message-ID: use split on the list to split it up. search each element for something like: if '"' == element[:-1]: if that evaluation is True, I would remove the quote mark from the word on the right side, and place a new one on the left side using something like '"' + element. I would do the same thing for the other side in the same for loop, instead the evaluation would be: if '"' == element[:1]: On Thu, Jun 16, 2011 at 1:03 PM, Neha P wrote: > Hi all, > I know below query may sound silly, but can somebody suggest any better way > of doing this: > It would be helpful. > > I need to read a file line by line and print each line starting from the > last word first: > > C:\Python26>type file_reversing_program.txt > import sys > import string > > f_obj=open(sys.argv[1],"r") > > for eachline in f_obj: > eachline=eachline[ :-1] # to eliminate the trailing "\n" > list_words=eachline.split(" ") > list_words[0]=list_words[0]+"\n" # to add "\n" so that after line 1 is > printed, line 2 should start on a new line > list_words.reverse() > for every_word in list_words: > print every_word, # 'comma' helps in printing words on same > line,hence for last word we append "\n" > > f_obj.close() > > C:\Python26>type input_file.txt > "Hi ther, how are you?" > I are doing fine, thank you. > > C:\Python26>file_reversing_program.py input_file.txt > you?" are how ther, "Hi > you. thank fine, doing are I > > Is there a better way of doing the above program, mainly the text > highlighted in yellow, > Also if that is settled can there be a logic for getting the ouput more > properly formatted (for text in blue) , > say giving an output like : > "you? are how ther, Hi" > you. thank fine, doing are I > > > Thanks, > Neha > > > _______________________________________________ > 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 lists at solderintheveins.co.uk Thu Jun 16 20:52:03 2011 From: lists at solderintheveins.co.uk (Peter Lavelle) Date: Thu, 16 Jun 2011 19:52:03 +0100 Subject: [Tutor] Beginner puzzle with unpacking argv In-Reply-To: <4DFA4560.7060305@alchemy.com> References: <201106161810.58716.lisi.reisz@gmail.com> <4DFA4560.7060305@alchemy.com> Message-ID: <4DFA50D3.3010104@solderintheveins.co.uk> If you need to process command line arguments then the argparse module may also be useful to you. More info can be found here: http://docs.python.org/library/argparse.html Regards Peter Lavelle On 16/06/11 19:03, Steve Willoughby wrote: > On 16-Jun-11 10:10, Lisi wrote: > >> 1 from sys import argv >> 2 >> 3 script, user_name = argv >> >> I have tried every permutation of white space I could think of that >> might have >> looked like the original, but I always get the same error: > > That will work ONLY if argv has at least 2 values in it. Your source > code is ok as far as it goes. Try running your script with two > command line arguments and see what you get. (The first argument > should be the name of your script, incidentally). > > If your script were named foo.py, then running the command: > > foo.py > > would give you the error you see because argv only has 1 thing in it > and you're trying to retrieve two. If you ran it as: > > foo.py bar > > that should work, and script would be "foo.py" and user_name would be > "bar". > > You could check len(argv) first to see how many items you have before > you try to get two values from it. > > For more sophisticated argument handling, you could look at the > optparse or argparse modules (but that's beyond the beginner > level--something to keep in mind for later). > -- LinkedIn Profile: http://linkedin.com/in/pmjlavelle Twitter: http://twitter.com/pmjlavelle From mywrkid at yahoo.com Thu Jun 16 20:51:37 2011 From: mywrkid at yahoo.com (Neha P) Date: Thu, 16 Jun 2011 11:51:37 -0700 (PDT) Subject: [Tutor] File parsing In-Reply-To: References: <615438.59424.qm@web121808.mail.ne1.yahoo.com> Message-ID: <759502.72762.qm@web121805.mail.ne1.yahoo.com> Thanks James I guess i have to use the same code for text in yellow... seems like ther's no other way...? Regards, Neha ________________________________ From: James Reynolds To: Neha P Cc: "tutor at python.org" Sent: Thursday, June 16, 2011 2:43 PM Subject: Re: [Tutor] File parsing use split on the list to split it up. search each element for something like: if '"' == element[:-1]: if that evaluation is True, I would remove the quote mark from the word on the right side, and place a new one on the left side using something like '"' + element. I would do the same thing for the other side in the same for loop, instead the evaluation would be: if '"' == element[:1]: On Thu, Jun 16, 2011 at 1:03 PM, Neha P wrote: Hi all, >I know below query may sound silly, but can somebody suggest any better way of doing this: > >It would be helpful. > > >I need to read a file line by line and print each line starting from the last word first: >? >C:\Python26>type file_reversing_program.txt > >import sys >import string > > >f_obj=open(sys.argv[1],"r") > > >for eachline in f_obj: >? ?eachline=eachline[ :-1]# to eliminate the trailing "\n"? >? ? list_words=eachline.split(" ") >? ?list_words[0]=list_words[0]+"\n"# to add "\n" so that after line 1 is printed, line 2 should start on a new line? >? ? list_words.reverse() >? ? for every_word in list_words: >? ? ? ? ?print every_word,# ?'comma' helps in printing words on same line,hence for last word we append "\n"? > > >f_obj.close() > > >C:\Python26>type input_file.txt > >"Hi ther, how are you?" >I are doing fine, thank you. > > >C:\Python26>file_reversing_program.py input_file.txt > >you?" are how ther,"Hi >you. thank fine, doing are I > > >Is there a better way of doing the above program, mainly the text highlighted in yellow, >Also if that is settled can there be a logic for getting the ouput more properly formatted?(for text in blue)?,? >say giving an output like ?: >"you? are how ther, Hi" >you. thank fine, doing are I > > > > > >Thanks, >Neha > >_______________________________________________ >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 lisi.reisz at gmail.com Thu Jun 16 21:48:03 2011 From: lisi.reisz at gmail.com (Lisi) Date: Thu, 16 Jun 2011 20:48:03 +0100 Subject: [Tutor] File parsing In-Reply-To: <615438.59424.qm@web121808.mail.ne1.yahoo.com> References: <615438.59424.qm@web121808.mail.ne1.yahoo.com> Message-ID: <201106162048.04029.lisi.reisz@gmail.com> Thanks, Neha. I am sending this back on list so that those who are more knowledgeable than I am can help you. On Thursday 16 June 2011 18:47:39 Neha P wrote: > Hi Lisi, > Below is the code and I have prefixed(-->) to the line code which i'm > mainly concerned about and have commented using # > > > > for eachline in f_obj: > > # to eliminate the trailing "\n" > --> eachline=eachline[ : -1] > list_words=eachline.split(" ") > # to add "\n" so that after line 1 is printed, line 2 should start on a new > line""" --> list_words[0]=list_words[0]+"\n" > list_words.reverse() > # 'comma' helps in printing words on same > # line, hence for last word have to append "\n" as done in above stmt > for every_word in list_words: > print every_word, > > > Thanks, > Neha > > > > > ________________________________ > From: Lisi > To: Neha P > Sent: Thursday, June 16, 2011 1:19 PM > Subject: Re: [Tutor] File parsing > > On Thursday 16 June 2011 18:03:55 Neha P wrote: > > Hi all, > > I know below query may sound silly, but can somebody suggest any better > > way of doing this: > > > > It would be helpful. > > > > I need to read a file line by line and print each line starting from the > > last word first: > > C:\Python26>type file_reversing_program.txt > > > > import sys > > import string > > > > f_obj=open(sys.argv[1],"r") > > > > for eachline in f_obj: > > eachline=eachline[ :-1]# to eliminate the trailing "\n" > > list_words=eachline.split(" ") > > list_words[0]=list_words[0]+"\n"# to add "\n" so that after line 1 is > > printed, line 2 should start on a new line list_words.reverse() > > for every_word in list_words: > > print every_word,# 'comma' helps in printing words on same > > line,hence for last word we append "\n" > > > > f_obj.close() > > > > C:\Python26>type input_file.txt > > > > "Hi ther, how are you?" > > I are doing fine, thank you. > > > > C:\Python26>file_reversing_program.py input_file.txt > > > > you?" are how ther,"Hi > > you. thank fine, doing are I > > > > Is there a better way of doing the above program, mainly the text > > highlighted in yellow, Also if that is settled can there be a logic for > > getting the ouput more properly formatted (for text in blue) , say giving > > an output like : > > "you? are how ther, Hi" > > you. thank fine, doing are I > > > > > > > > Thanks, > > Neha > > Colours haven't transmitted (I use plain text). > > Could you identify the blocks of text by some other means? > > Thanks, > Lisi From spawgi at gmail.com Thu Jun 16 21:56:34 2011 From: spawgi at gmail.com (spawgi at gmail.com) Date: Fri, 17 Jun 2011 01:26:34 +0530 Subject: [Tutor] File parsing In-Reply-To: <759502.72762.qm@web121805.mail.ne1.yahoo.com> References: <615438.59424.qm@web121808.mail.ne1.yahoo.com> <759502.72762.qm@web121805.mail.ne1.yahoo.com> Message-ID: Hello Neha, I think this script will do what you want and will also fix some of the issues in your original code - -------------------------------------------------------- 1 #! /usr/bin/python 2 3 import curses.ascii 4 import string 5 import sys 6 7 with open(sys.argv[1],'r') as input: 8 for eachline in input: 9 eachline = eachline.strip('\n') 10 if curses.ascii.isalpha(eachline[0]): 11 first_char = '' 12 else: 13 first_char = eachline[0] 14 last_char = eachline[len(eachline)-1] 15 eachline = eachline.lstrip(first_char) 16 eachline = eachline.rstrip(last_char) 17 words = eachline.split(' ') 18 outline = first_char 19 for word in reversed(words): 20 outline = outline + str(word) + ' ' 21 outline = outline.rstrip() + last_char + '\n' 22 print outline ----------------------------------------------------------------------------------- It is much more explicit. It considers some special cases and gives the output in the format desired by you. Regards, SWP On Fri, Jun 17, 2011 at 12:21 AM, Neha P wrote: > Thanks James > > I guess i have to use the same code for text in yellow... seems like ther's > no other way... > > Regards, > Neha > ------------------------------ > *From:* James Reynolds > *To:* Neha P > *Cc:* "tutor at python.org" > *Sent:* Thursday, June 16, 2011 2:43 PM > *Subject:* Re: [Tutor] File parsing > > use split on the list to split it up. search each element for something > like: > > if '"' == element[:-1]: > > if that evaluation is True, I would remove the quote mark from the word on > the right side, and place a new one on the left side using something like > '"' + element. > > I would do the same thing for the other side in the same for loop, instead > the evaluation would be: > > if '"' == element[:1]: > > > > > On Thu, Jun 16, 2011 at 1:03 PM, Neha P wrote: > > Hi all, > I know below query may sound silly, but can somebody suggest any better way > of doing this: > It would be helpful. > > I need to read a file line by line and print each line starting from the > last word first: > > C:\Python26>type file_reversing_program.txt > import sys > import string > > f_obj=open(sys.argv[1],"r") > > for eachline in f_obj: > eachline=eachline[ :-1] # to eliminate the trailing "\n" > list_words=eachline.split(" ") > list_words[0]=list_words[0]+"\n" # to add "\n" so that after line 1 is > printed, line 2 should start on a new line > list_words.reverse() > for every_word in list_words: > print every_word, # 'comma' helps in printing words on same > line,hence for last word we append "\n" > > f_obj.close() > > C:\Python26>type input_file.txt > "Hi ther, how are you?" > I are doing fine, thank you. > > C:\Python26>file_reversing_program.py input_file.txt > you?" are how ther, "Hi > you. thank fine, doing are I > > Is there a better way of doing the above program, mainly the text > highlighted in yellow, > Also if that is settled can there be a logic for getting the ouput more > properly formatted (for text in blue) , > say giving an output like : > "you? are how ther, Hi" > you. thank fine, doing are I > > > Thanks, > Neha > > > _______________________________________________ > 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 > > -- http://spawgi.wordpress.com We can do it and do it better. -------------- next part -------------- An HTML attachment was scrubbed... URL: From spawgi at gmail.com Thu Jun 16 21:59:20 2011 From: spawgi at gmail.com (spawgi at gmail.com) Date: Fri, 17 Jun 2011 01:29:20 +0530 Subject: [Tutor] File parsing In-Reply-To: References: <615438.59424.qm@web121808.mail.ne1.yahoo.com> <759502.72762.qm@web121805.mail.ne1.yahoo.com> Message-ID: Output on your sample input - $./file_reversing_program.py input.txt "you? are how there, Hi" you thank fine, doing am I. On Fri, Jun 17, 2011 at 1:26 AM, wrote: > Hello Neha, > > I think this script will do what you want and will also fix some of the > issues in your original code - > -------------------------------------------------------- > 1 #! /usr/bin/python > 2 > 3 import curses.ascii > 4 import string > 5 import sys > 6 > 7 with open(sys.argv[1],'r') as input: > 8 for eachline in input: > 9 eachline = eachline.strip('\n') > 10 if curses.ascii.isalpha(eachline[0]): > 11 first_char = '' > 12 else: > 13 first_char = eachline[0] > 14 last_char = eachline[len(eachline)-1] > 15 eachline = eachline.lstrip(first_char) > 16 eachline = eachline.rstrip(last_char) > 17 words = eachline.split(' ') > 18 outline = first_char > 19 for word in reversed(words): > 20 outline = outline + str(word) + ' ' > 21 outline = outline.rstrip() + last_char + '\n' > 22 print outline > > ----------------------------------------------------------------------------------- > > It is much more explicit. It considers some special cases and gives the > output in the format desired by you. > > Regards, > SWP > > On Fri, Jun 17, 2011 at 12:21 AM, Neha P wrote: > >> Thanks James >> >> I guess i have to use the same code for text in yellow... seems like >> ther's no other way... >> >> Regards, >> Neha >> ------------------------------ >> *From:* James Reynolds >> *To:* Neha P >> *Cc:* "tutor at python.org" >> *Sent:* Thursday, June 16, 2011 2:43 PM >> *Subject:* Re: [Tutor] File parsing >> >> use split on the list to split it up. search each element for something >> like: >> >> if '"' == element[:-1]: >> >> if that evaluation is True, I would remove the quote mark from the word on >> the right side, and place a new one on the left side using something like >> '"' + element. >> >> I would do the same thing for the other side in the same for loop, instead >> the evaluation would be: >> >> if '"' == element[:1]: >> >> >> >> >> On Thu, Jun 16, 2011 at 1:03 PM, Neha P wrote: >> >> Hi all, >> I know below query may sound silly, but can somebody suggest any better >> way of doing this: >> It would be helpful. >> >> I need to read a file line by line and print each line starting from the >> last word first: >> >> C:\Python26>type file_reversing_program.txt >> import sys >> import string >> >> f_obj=open(sys.argv[1],"r") >> >> for eachline in f_obj: >> eachline=eachline[ :-1] # to eliminate the trailing "\n" >> list_words=eachline.split(" ") >> list_words[0]=list_words[0]+"\n" # to add "\n" so that after line 1 >> is printed, line 2 should start on a new line >> list_words.reverse() >> for every_word in list_words: >> print every_word, # 'comma' helps in printing words on same >> line,hence for last word we append "\n" >> >> f_obj.close() >> >> C:\Python26>type input_file.txt >> "Hi ther, how are you?" >> I are doing fine, thank you. >> >> C:\Python26>file_reversing_program.py input_file.txt >> you?" are how ther, "Hi >> you. thank fine, doing are I >> >> Is there a better way of doing the above program, mainly the text >> highlighted in yellow, >> Also if that is settled can there be a logic for getting the ouput more >> properly formatted (for text in blue) , >> say giving an output like : >> "you? are how ther, Hi" >> you. thank fine, doing are I >> >> >> Thanks, >> Neha >> >> >> _______________________________________________ >> 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 >> >> > > > -- > http://spawgi.wordpress.com > We can do it and do it better. > -- http://spawgi.wordpress.com We can do it and do it better. -------------- next part -------------- An HTML attachment was scrubbed... URL: From lisi.reisz at gmail.com Thu Jun 16 21:43:07 2011 From: lisi.reisz at gmail.com (Lisi) Date: Thu, 16 Jun 2011 20:43:07 +0100 Subject: [Tutor] Beginner puzzle with unpacking argv In-Reply-To: References: <201106161810.58716.lisi.reisz@gmail.com> Message-ID: <201106162043.07547.lisi.reisz@gmail.com> On Thursday 16 June 2011 19:03:27 Joel Goldstick wrote: > On Thu, Jun 16, 2011 at 1:10 PM, Lisi wrote: > > Copied and pasted: > > >From text of Learn Python the Hard Way > > > > 1 from sys import argv > > 2 > > 3 script, user_name = argv > > > > >From my script (typed, not copied and pasted, but copied and pasted from > > > > my > > script to here): > > > > 1 from sys import argv > > 2 > > 3 script, user_name = argv > > > > I have tried every permutation of white space I could think of that might > > have > > looked like the original, but I always get the same error: > > > > lisi at Tux:~/Python/LearnPythonTheHardWay$ python ex14.py > > Traceback (most recent call last): > > File "ex14.py", line 3, in > > script, user_name=argv > > ValueError: need more than 1 value to unpack > > > > I haven't got past line 3 yet!! I know that you need the right number of > > variables, but my script has got as many as the original - it's the same > > as the original! > when you run the program you are not giving it any arguments to read. > argv[0] is the name of your script. But you are not providing a value for > user_name to consume > > Try this: > > lisi at Tux:~/Python/LearnPythonTheHardWay$ python ex14.py Lisi Thanks to all of you, guys. :-)) So it wasn't the script that was wrong, it was the command I was giving. Doh! It now runs fine as far as I have gone, so I can now finish typing the rest of the script in. Hopefully without too many stupid mistakes. :-( Lisi From G.nius.ck at gmail.com Thu Jun 16 23:43:36 2011 From: G.nius.ck at gmail.com (G.nius.ck at gmail.com) Date: Thu, 16 Jun 2011 21:43:36 +0000 Subject: [Tutor] File parsing In-Reply-To: Message-ID: <20cf303f699255edf104a5db293d@google.com> instead of 14 last_char = eachline[len(eachline)-1] do 14 last_char = eachline[-1] #Which is shorter but the same thing On , spawgi at gmail.com wrote: > Hello Neha, > I think this script will do what you want and will also fix some of the > issues in your original code - > -------------------------------------------------------- > 1 #! /usr/bin/python > 2 > 3 import curses.ascii > 4 import string > 5 import sys > 6 > 7 with open(sys.argv[1],'r') as input: > 8 for eachline in input: > 9 eachline = eachline.strip('\n') > 10 if curses.ascii.isalpha(eachline[0]): > 11 first_char = '' > 12 else: > 13 first_char = eachline[0] > 14 last_char = eachline[len(eachline)-1] > 15 eachline = eachline.lstrip(first_char) > 16 eachline = eachline.rstrip(last_char) > 17 words = eachline.split(' ') > 18 outline = first_char > 19 for word in reversed(words): > 20 outline = outline + str(word) + ' ' > 21 outline = outline.rstrip() + last_char + '\n' > 22 print outline > ----------------------------------------------------------------------------------- > It is much more explicit. It considers some special cases and gives the > output in the format desired by you. > Regards, > SWP > On Fri, Jun 17, 2011 at 12:21 AM, Neha P mywrkid at yahoo.com> wrote: > Thanks James > I guess i have to use the same code for text in yellow... seems like > ther's no other way... > Regards, > Neha > From: James Reynolds eire1130 at gmail.com> > To: Neha P mywrkid at yahoo.com> > Cc: "tutor at python.org" tutor at python.org> > Sent: Thursday, June 16, 2011 2:43 PM > Subject: Re: [Tutor] File parsing > use split on the list to split it up. search each element for something > like: > if '"' == element[:-1]: > if that evaluation is True, I would remove the quote mark from the word > on the right side, and place a new one on the left side using something > like '"' + element. > I would do the same thing for the other side in the same for loop, > instead the evaluation would be: > if '"' == element[:1]: > On Thu, Jun 16, 2011 at 1:03 PM, Neha P mywrkid at yahoo.com> wrote: > Hi all, > I know below query may sound silly, but can somebody suggest any better > way of doing this: > It would be helpful. > I need to read a file line by line and print each line starting from the > last word first: > C:\Python26>type file_reversing_program.txt > import sys > import string > f_obj=open(sys.argv[1],"r") > for eachline in f_obj: > eachline=eachline[ :-1] # to eliminate the trailing "\n" > list_words=eachline.split(" ") > list_words[0]=list_words[0]+"\n" # to add "\n" so that after line 1 is > printed, line 2 should start on a new line > list_words.reverse() > sans-serif"> for every_word in list_words: > print every_word, # 'comma' helps in printing words on same line,hence > for last word we append "\n" > f_obj.close() > C:\Python26>type input_file.txt > "Hi ther, how are you?" > I are doing fine, thank you. > C:\Python26>file_reversing_program.py input_file.txt > you?" are how ther, "Hi > you. thank fine, doing are I > Is there a better way of doing the above program, mainly the text > highlighted in yellow, > serif">Also if that is settled can there be a logic for getting the ouput > more properly formatted (for text in blue) , > say giving an output like : > "you? are how ther, Hi" > you. thank fine, doing are I > Thanks, > Neha > _______________________________________________ > 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 > -- > http://spawgi.wordpress.com > We can do it and do it better. -------------- next part -------------- An HTML attachment was scrubbed... URL: From vincentbalmori at yahoo.com Fri Jun 17 00:29:21 2011 From: vincentbalmori at yahoo.com (Vincent Balmori) Date: Thu, 16 Jun 2011 15:29:21 -0700 (PDT) Subject: [Tutor] Step Value Message-ID: <89843.91684.qm@web59407.mail.ac4.yahoo.com> "From?Steven D'Aprono: * change the ask_number function to accept a fourth argument; * make it optional rather than required; * give it a sensible default value; * within the function, that value must then be passed to range " Okay, I think I understand it better for the quesiton: "Improve the function?ask_number()?so that the function can be called with a step value. Make the default value of step?1."?Here is the improved function and the human_move function that calls it later on. The thing I am unaware of doing is making the step value 'optional rather than required' though. def ask_number(question, low, high, step): ?? ?"""Ask for a number within a range.""" ?? ?step = 1 ?? ?response = None ?? ?while response not in range(low, high, step): ?? ? ? ?response = int(input(question)) ?? ?return response def human_move(board, human): ?? ?"""Get human move.""" ? ?? ?legal = legal_moves(board) ?? ?move = None ?? ?while move not in legal: ?? ? ? ?move = ask_number("Where will you move? (0 - 8):", 0, NUM_SQUARES, 1) ?? ? ? ?if move not in legal: ?? ? ? ? ? ?print("\nThat square is already occupied, foolish human. ?Choose another.\n") ?? ?print("Fine...") ?? ?return move ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Fri Jun 17 02:55:45 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 17 Jun 2011 10:55:45 +1000 Subject: [Tutor] Step Value In-Reply-To: <89843.91684.qm@web59407.mail.ac4.yahoo.com> References: <89843.91684.qm@web59407.mail.ac4.yahoo.com> Message-ID: <4DFAA611.1070807@pearwood.info> Vincent Balmori wrote: > Okay, I think I understand it better for the quesiton: > "Improve the function ask_number() so that the function can be called with a step value. Make the default value of step 1." Here is the improved function and the human_move function that calls it later on. The thing I am unaware of doing is making the step value 'optional rather than required' though. You're almost there. > def ask_number(question, low, high, step): > """Ask for a number within a range.""" > step = 1 The line above is inappropriate, because it over-writes the value of step that the caller provides. If you call ask_number(question, 1, 100, 5) the line step=1 throws away the value 5 and replaces it with 1. Get rid of that line altogether, you don't want it. The last change that needs to be made is to give step a default value. The way to do that is to put it in the function parameters. He's an example: def spam(n=3): """Return n slices of yummy spam.""" return "spam "*n And here it is in use: >>> spam(4) 'spam spam spam spam ' >>> spam() # just use the default 'spam spam spam ' Can you see what I did to set the default value for n? Read the function definition line "def spam... " carefully. -- Steven From steve at pearwood.info Fri Jun 17 03:30:49 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 17 Jun 2011 11:30:49 +1000 Subject: [Tutor] File parsing In-Reply-To: <759502.72762.qm@web121805.mail.ne1.yahoo.com> References: <615438.59424.qm@web121808.mail.ne1.yahoo.com> <759502.72762.qm@web121805.mail.ne1.yahoo.com> Message-ID: <4DFAAE49.3090205@pearwood.info> Neha P wrote: > Thanks James > > I guess i have to use the same code for text in yellow... seems like ther's no other way... What code in yellow? I see no code in yellow. This is email, don't assume people can see colours. They may have HTML blocked or turned off (very important for security, avoiding some viruses and some types of web-bugs, or just because they hate getting ugly emails with horrible clashing colours). Or they may be colour-blind (about one in twelve men, and one in 200 women), or completely blind and reading email with a screen reader. I will leave you to guess which category I fall into. -- Steven From vincentbalmori at yahoo.com Fri Jun 17 04:26:07 2011 From: vincentbalmori at yahoo.com (Vincent Balmori) Date: Thu, 16 Jun 2011 19:26:07 -0700 (PDT) Subject: [Tutor] Step Value Message-ID: <790326.68712.qm@web59401.mail.ac4.yahoo.com> "def spam(n=3): ? ? """Return n slices of yummy spam.""" ? ? return "spam "*n And here it is in use: >>> spam(4) 'spam spam spam spam ' >>> spam()? # just use the default 'spam spam spam ' Can you see what I did to set the default value for n? Read the function definition line "def spam... " carefully. -- Steven" This is my new code for a default step value based on your feedback Steve: def ask_number(question, low, high, step): ?? ?"""Ask for a number within a range.""" ?? ?response = None ?? ?if step == None: ?? ? ? ?step = 1 ?? ?while response not in range(low, high, step): ?? ? ? ?response = int(input(question)) ?? ?return response -------------- next part -------------- An HTML attachment was scrubbed... URL: From sulinet at postafiok.hu Fri Jun 17 07:14:12 2011 From: sulinet at postafiok.hu (=?ISO-8859-1?Q?V=E1las_P=E9ter?=) Date: Fri, 17 Jun 2011 07:14:12 +0200 Subject: [Tutor] Step Value In-Reply-To: <790326.68712.qm@web59401.mail.ac4.yahoo.com> References: <790326.68712.qm@web59401.mail.ac4.yahoo.com> Message-ID: Please try to reply to the previous letters instead of starting a new thread each time. Thank you! -------------- next part -------------- An HTML attachment was scrubbed... URL: From merrickdav at gmail.com Fri Jun 17 09:28:44 2011 From: merrickdav at gmail.com (David Merrick) Date: Fri, 17 Jun 2011 19:28:44 +1200 Subject: [Tutor] Problem Message-ID: # Critter Caretaker # A virtual pet to care for class Farm(object): #A collection of Critters def talk(self,farm): farm.talk() class Critter(object): """A virtual pet""" def __init__(self, name, hunger = 0, boredom = 0): self.name = name self.hunger = hunger self.boredom = boredom # __ denotes private method def __pass_time(self,farm): self.hunger += 1 self.boredom += 1 self.__str__() def __str__(self,farm): print("Hunger is",self.hunger, "Boredom is " ,self.boredom) print("Unhappines is ",self.hunger + self.boredom," and Mood is ",self.mood) @property def mood(self,farm): unhappiness = self.hunger + self.boredom if unhappiness < 5: m = "happy" elif 5 <= unhappiness <= 10: m = "okay" elif 11 <= unhappiness <= 15: m = "frustrated" else: m = "mad" return m def talk(self,farm): print("I'm", self.name, "and I feel", self.mood, "now.\n") self.__pass_time() def eat(self,farm): food = int(input("Enter how much food you want to feed your critter: ")) print("Brruppp. Thank you.") self.hunger -= food # hunger = 0 at iniatition # self.hunger = self.boredom - food if self.hunger < 0: self.hunger = 0 self.__pass_time() def play(self,farm): fun = int(input("Enter how much fun you want your critter to have: ")) print("Wheee!") self.boredom -= fun # boredom = 0 at iniatition # self.boredom = self.boredom - fun if self.boredom < 0: self.boredom = 0 self.__pass_time() def main(): ## crit_name = input("What do you want to name your critter?: ") ## crit = Critter(crit_name) crit1 = Critter("Sweetie") crit2 = Critter("Dave") farm = [crit1,crit2] choice = None while choice != "0": print \ (""" Critter Caretaker 0 - Quit 1 - Listen to your critter 2 - Feed your critter 3 - Play with your critter """) choice = input("Choice: ") print() # exit if choice == "0": print("Good-bye.") # listen to your critter elif choice == "1": self.talk() # feed your critter elif choice == "2": crit.eat() # play with your critter elif choice == "3": crit.play() # some unknown choice else: print("\nSorry, but", choice, "isn't a valid choice.") main() ("\n\nPress the enter key to exit.") Critter Caretaker 0 - Quit 1 - Listen to your critter 2 - Feed your critter 3 - Play with your critter Choice: 1 Traceback (most recent call last): File "D:\David\Python\programs\critter_farm2.py", line 118, in main() File "D:\David\Python\programs\critter_farm2.py", line 100, in main self.talk() NameError: global name 'self' is not defined >>> -- Dave Merrick merrickdav at gmail.com Ph 03 3423 121 Cell 027 3089 169 -------------- next part -------------- An HTML attachment was scrubbed... URL: From mazen.harake at gmail.com Fri Jun 17 09:37:06 2011 From: mazen.harake at gmail.com (Mazen Harake) Date: Fri, 17 Jun 2011 09:37:06 +0200 Subject: [Tutor] Problem In-Reply-To: References: Message-ID: self doesn't refer to anything? It is undefined because it is in main and not in a method of an object. You have to do crit.talk() where crit is an object (which by the way isn't, you have crit1 and crit2) On 17 June 2011 09:28, David Merrick wrote: > # Critter Caretaker > # A virtual pet to care for > class Farm(object): > #A collection of Critters > > ??? def talk(self,farm): > ??????? farm.talk() > > > > class Critter(object): > > ??? """A virtual pet""" > ??? def __init__(self, name, hunger = 0, boredom = 0): > ??????? self.name = name > ??????? self.hunger = hunger > ??????? self.boredom = boredom > > ??? # __ denotes private method > ??? def __pass_time(self,farm): > ??????? self.hunger += 1 > ??????? self.boredom += 1 > ??????? self.__str__() > > ??? def __str__(self,farm): > ??????? print("Hunger is",self.hunger, "Boredom is " ,self.boredom) > ??????? print("Unhappines is ",self.hunger + self.boredom," and Mood is > ",self.mood) > > > > ??? @property > ??? def mood(self,farm): > ??????? unhappiness = self.hunger + self.boredom > ??????? if unhappiness < 5: > ??????????? m = "happy" > ??????? elif 5 <= unhappiness <= 10: > ??????????? m = "okay" > ??????? elif 11 <= unhappiness <= 15: > ??????????? m = "frustrated" > ??????? else: > ??????????? m = "mad" > ??????? return m > > ??? def talk(self,farm): > ??????? print("I'm", self.name, "and I feel", self.mood, "now.\n") > ??????? self.__pass_time() > > > ??? def eat(self,farm): > ??????? food = int(input("Enter how much food you want to feed your critter: > ")) > ??????? print("Brruppp.? Thank you.") > ??????? self.hunger -= food > ??????? # hunger = 0 at iniatition > ??????? # self.hunger = self.boredom - food > ??????? if self.hunger < 0: > ??????????? self.hunger = 0 > ??????? self.__pass_time() > > > ??? def play(self,farm): > ??????? fun = int(input("Enter how much fun you want your critter to have: > ")) > ??????? print("Wheee!") > ??????? self.boredom -= fun > ??????? # boredom = 0 at iniatition > ??????? # self.boredom = self.boredom - fun > ??????? if self.boredom < 0: > ??????????? self.boredom = 0 > ??????? self.__pass_time() > > > def main(): > ##??? crit_name = input("What do you want to name your critter?: ") > ##??? crit = Critter(crit_name) > > ??? crit1 = Critter("Sweetie") > ??? crit2 = Critter("Dave") > ??? farm = [crit1,crit2] > > ??? choice = None > ??? while choice != "0": > ??????? print \ > ??????? (""" > ??????? Critter Caretaker > > ??????? 0 - Quit > ??????? 1 - Listen to your critter > ??????? 2 - Feed your critter > ??????? 3 - Play with your critter > ??????? """) > > ??????? choice = input("Choice: ") > ??????? print() > > ??????? # exit > ??????? if choice == "0": > ??????????? print("Good-bye.") > > ??????? # listen to your critter > ??????? elif choice == "1": > ??????????? self.talk() > > ??????? # feed your critter > ??????? elif choice == "2": > ??????????? crit.eat() > > ??????? # play with your critter > ??????? elif choice == "3": > ??????????? crit.play() > > ??????? # some unknown choice > ??????? else: > ??????????? print("\nSorry, but", choice, "isn't a valid choice.") > > > > > > main() > ("\n\nPress the enter key to exit.") > > Critter Caretaker > > ??????? 0 - Quit > ??????? 1 - Listen to your critter > ??????? 2 - Feed your critter > ??????? 3 - Play with your critter > > Choice: 1 > > Traceback (most recent call last): > ? File "D:\David\Python\programs\critter_farm2.py", line 118, in > ??? main() > ? File "D:\David\Python\programs\critter_farm2.py", line 100, in main > ??? self.talk() > NameError: global name 'self' is not defined >>>> > > -- > Dave Merrick > > merrickdav at gmail.com > > Ph?? 03 3423 121 > Cell 027 3089 169 > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > From alan.gauld at btinternet.com Fri Jun 17 10:30:37 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 17 Jun 2011 09:30:37 +0100 Subject: [Tutor] Step Value References: <790326.68712.qm@web59401.mail.ac4.yahoo.com> Message-ID: "Vincent Balmori" wrote "def spam(n=3): """Return n slices of yummy spam.""" return "spam "*n > This is my new code for a default step value based on your feedback > Steve: > > def ask_number(question, low, high, step): > """Ask for a number within a range.""" > response = None > if step == None: > step = 1 Nope, you are still missing the point. Look again at how Steven defined his function. What is different about his definition of n and your definition of step? HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Jun 17 11:06:49 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 17 Jun 2011 10:06:49 +0100 Subject: [Tutor] File parsing References: <615438.59424.qm@web121808.mail.ne1.yahoo.com> Message-ID: "Neha P" wrote for eachline in f_obj: eachline=eachline[ :-1]# to eliminate the trailing "\n" Better to use rstrip() here, thee might be extraneous spaces etc to remove too. list_words=eachline.split(" ") list_words[0]=list_words[0]+"\n"# to add "\n" so that after line 1 is printed, line 2 should start on a new line I'd do this at the end after you print the line, otherwise if you later decide to rearrange the words you have to remember to remove the \n from that specific word. You don't really want that word to have a \n you want the printed line to have a \n, so put it on the line not the word. list_words.reverse() for every_word in list_words: print every_word,# 'comma' helps in printing words on same line,hence for last word we append "\n" You could use join() and just print that: print ' '.join(list_words) And print will now add the newline for you. HTH, Alan G. From lisi.reisz at gmail.com Fri Jun 17 18:20:47 2011 From: lisi.reisz at gmail.com (Lisi) Date: Fri, 17 Jun 2011 17:20:47 +0100 Subject: [Tutor] Reading opened files Message-ID: <201106171720.47852.lisi.reisz@gmail.com> Hello :-) I have got as far as I have,i.e. apparently succeeding in both opening and closing two different files, thanks to google, but my struggles to _do_ something with a file that I have opened are getting me nowhere. Here is my latest failure: >>> file=open("/home/lisi/CHOOSING_SHOES.txt", "r") >>> file.close() >>> file=open("/home/lisi/CHOOSING_SHOES.txt", "r") >>> whole=file.read >>> print whole >>> print "%r" % whole >>> print "whole is %r" %whole whole is >>> print "whole is %r" % whole whole is >>> I'd be extremely grateful if one of you was willing to drop a hint, give me some pointers (even e.g. guide me to asking the correct question of Google), or tell me where I am going wrong. In general, the author advises leaving any of the extra credit questions that you are struggling with and coming back to them later. And in general I have found that that works. But this set of extra-credit questions he advises mastering before moving on. And I am stuck on this one at this stage. :-( (I think that I have cracked the others.) Thanks. Lisi From lisi.reisz at gmail.com Fri Jun 17 18:38:03 2011 From: lisi.reisz at gmail.com (Lisi) Date: Fri, 17 Jun 2011 17:38:03 +0100 Subject: [Tutor] Reading opened files (SOLVED) Message-ID: <201106171738.03903.lisi.reisz@gmail.com> So sorry to have troubled you all. The light suddenly dawned. Perhaps because I was more relaxed, having asked the list? Anyhow, I now know how to do it, and it is of course, simple. [Passing on and coming back would obviously have worked, but the author had said not to do that this time. :-( ] Lisi From wprins at gmail.com Fri Jun 17 18:42:29 2011 From: wprins at gmail.com (Walter Prins) Date: Fri, 17 Jun 2011 17:42:29 +0100 Subject: [Tutor] Reading opened files In-Reply-To: <201106171720.47852.lisi.reisz@gmail.com> References: <201106171720.47852.lisi.reisz@gmail.com> Message-ID: On 17 June 2011 17:20, Lisi wrote: > >>> file=open("/home/lisi/CHOOSING_SHOES.txt", "r") > >>> file.close() > >>> file=open("/home/lisi/CHOOSING_SHOES.txt", "r") > >>> whole=file.read > >>> print whole > > >>> print "%r" % whole > > >>> print "whole is %r" %whole > whole is > >>> print "whole is %r" % whole > whole is > >>> > You're missing the () off the whole=file.read() call. Ask youself, what is "file.read"? It is of course a method of the "file" object. And, in fact that's exactly what Python itself is telling you also. So when you say: whole=file.read You're assigning the method itself, to the name "whole". Consequently, you would be able to do: something = whole() ... which would then *call* the function using the name "whole", which would be identical to calling that same function via "file.read". To reiterate, there's a difference between just referencing a method or function and actually calling it. To call it you need to use parentheses. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From eire1130 at gmail.com Fri Jun 17 18:44:28 2011 From: eire1130 at gmail.com (James Reynolds) Date: Fri, 17 Jun 2011 12:44:28 -0400 Subject: [Tutor] Reading opened files In-Reply-To: <201106171720.47852.lisi.reisz@gmail.com> References: <201106171720.47852.lisi.reisz@gmail.com> Message-ID: Your problem is right here: >>> whole=file.read >>> print whole Your re-assigning the method "read()", which is a method of the object "file" to the variable "whole" So, when you print "whole" you can see that it is printing the location of the method in memory. If you were to print file.read you would get the same results. Now, to call the method (or a function) you need to add the parentheses with any arguments that it may need. In your case, you need to do "read()". This principle holds true with any object. So, let's say we created a list object by doing this mylist = [] mylist now has all of the methods that a list has. So, for example, I can append something to the list by going: mylist.append(1) printing my list will show a list like this [1] IDLE 2.6.5 >>> mylist = [] >>> mylist.append(1) >>> print mylist [1] but instead lets say I did this: >>> b = mylist.append >>> print b Which can be handy if i needed to do appending all the time, for example: >>> b(1) >>> print mylist [1, 1] My last piece of advice here is, use the Python documentation in addition to googling. It's actually very readable (I think anyway) On Fri, Jun 17, 2011 at 12:20 PM, Lisi wrote: > Hello :-) > > I have got as far as I have,i.e. apparently succeeding in both opening and > closing two different files, thanks to google, but my struggles to _do_ > something with a file that I have opened are getting me nowhere. Here is > my > latest failure: > > >>> file=open("/home/lisi/CHOOSING_SHOES.txt", "r") > >>> file.close() > >>> file=open("/home/lisi/CHOOSING_SHOES.txt", "r") > >>> whole=file.read > >>> print whole > > >>> print "%r" % whole > > >>> print "whole is %r" %whole > whole is > >>> print "whole is %r" % whole > whole is > >>> > > I'd be extremely grateful if one of you was willing to drop a hint, give me > some pointers (even e.g. guide me to asking the correct question of > Google), > or tell me where I am going wrong. > > In general, the author advises leaving any of the extra credit questions > that > you are struggling with and coming back to them later. And in general I > have > found that that works. But this set of extra-credit questions he advises > mastering before moving on. And I am stuck on this one at this stage. :-( > (I think that I have cracked the others.) > > Thanks. > > Lisi > _______________________________________________ > 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 lisi.reisz at gmail.com Fri Jun 17 18:58:12 2011 From: lisi.reisz at gmail.com (Lisi) Date: Fri, 17 Jun 2011 17:58:12 +0100 Subject: [Tutor] Reading opened files In-Reply-To: References: <201106171720.47852.lisi.reisz@gmail.com> Message-ID: <201106171758.12347.lisi.reisz@gmail.com> On Friday 17 June 2011 17:42:29 Walter Prins wrote: > On 17 June 2011 17:20, Lisi wrote: > > >>> file=open("/home/lisi/CHOOSING_SHOES.txt", "r") > > >>> file.close() > > >>> file=open("/home/lisi/CHOOSING_SHOES.txt", "r") > > >>> whole=file.read > > >>> print whole > > > > > > > > >>> print "%r" % whole > > > > > > > > >>> print "whole is %r" %whole > > > > whole is > > > > >>> print "whole is %r" % whole > > > > whole is > > You're missing the () off the whole=file.read() call. > > Ask youself, what is "file.read"? It is of course a method of the "file" > object. And, in fact that's exactly what Python itself is telling you > also. So when you say: > > whole=file.read > > You're assigning the method itself, to the name "whole". Consequently, you > would be able to do: > > something = whole() > > ... which would then *call* the function using the name "whole", which > would be identical to calling that same function via "file.read". > > To reiterate, there's a difference between just referencing a method or > function and actually calling it. To call it you need to use parentheses. Thanks, Walter. That is also very useful and clear. As with James's answer, I have left this intact for the archives. It should be available for other newbies who are blundering about a bit. Lisi From benderjacob44 at gmail.com Fri Jun 17 19:01:12 2011 From: benderjacob44 at gmail.com (Jacob Bender) Date: Fri, 17 Jun 2011 10:01:12 -0700 Subject: [Tutor] Communicating Between Programs Using A Raw Input (Cont'd) Message-ID: Dear Tutors, Alright, I read up on stdin and stdout and I did find how useful they are. I did have one question however, and that is will I need to modify the code of my password program? Here's the code again: password = "Helloworld" try= raw_input("What's the password?") while try != password: try = raw_input("Incorrect, what's the password?") And if so, then should I use sys.stdin.read() and sys.stdout.write() for the program that generates the random passwords or are there other commands that I should use? Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From vincentbalmori at yahoo.com Fri Jun 17 20:05:47 2011 From: vincentbalmori at yahoo.com (Vincent Balmori) Date: Fri, 17 Jun 2011 11:05:47 -0700 (PDT) Subject: [Tutor] Step Value In-Reply-To: References: <790326.68712.qm@web59401.mail.ac4.yahoo.com> Message-ID: <31871108.post@talk.nabble.com> Here is my updated code. As simple as this may be, I am a little lost again. I appreciate the help and explanations to try to push me to get this on my own, but at this point (especially after one week) this is when me being given the answer with an explanation will help me much more, so I can understand how it works better. def ask_number(question, low, high, step = 1): """Ask for a number within a range.""" response = None while response not in range(low, high, step): response = int(input(question)) return response -Vincent Alan Gauld wrote: > > > "Vincent Balmori" wrote > > "def spam(n=3): > """Return n slices of yummy spam.""" > return "spam "*n > > >> This is my new code for a default step value based on your feedback >> Steve: >> >> def ask_number(question, low, high, step): >> """Ask for a number within a range.""" >> response = None >> if step == None: >> step = 1 > > Nope, you are still missing the point. > Look again at how Steven defined his function. > What is different about his definition of n and your definition of > step? > > 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 > > -- View this message in context: http://old.nabble.com/-Tutor--Step-Value-tp31865967p31871108.html Sent from the Python - tutor mailing list archive at Nabble.com. From alan.gauld at btinternet.com Fri Jun 17 23:03:31 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 17 Jun 2011 22:03:31 +0100 Subject: [Tutor] Step Value References: <790326.68712.qm@web59401.mail.ac4.yahoo.com> <31871108.post@talk.nabble.com> Message-ID: "Vincent Balmori" wrote > Here is my updated code. As simple as this may be, I am a little > lost again. I'm not sure why you are lost because that's pretty much it. > ... at this point (especially after one week) this is when me being > given the answer with an explanation will help me much more, so I > can > understand how it works better. The answer is: > def ask_number(question, low, high, step = 1): > """Ask for a number within a range.""" > response = None > while response not in range(low, high, step): > response = int(input(question)) > return response With the only comment being that you don't really need the response=None line because response always gets set inside the loop. If you don't understand how your code answered the question, feel free to reply with specific issues, like a particular statement you don't get or whatever. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Jun 17 23:07:50 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 17 Jun 2011 22:07:50 +0100 Subject: [Tutor] Communicating Between Programs Using A Raw Input (Cont'd) References: Message-ID: "Jacob Bender" wrote > did have one question however, and that is will I need to modify the > code of > my password program? No, if it uses raw_input and print it will be using atdin and stdout so you can pipe from one program into the other Here's the code again: > > password = "Helloworld" > try= raw_input("What's the password?") > while try != password: > try = raw_input("Incorrect, what's the password?") > Just try it and see. If it doesn't work get back to us - with the output of course :-) -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Jun 17 23:18:34 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 17 Jun 2011 22:18:34 +0100 Subject: [Tutor] Weird tkFont behavior References: <4DFA34C5.4060404@alchemy.com> <4DFA38CE.7060604@alchemy.com> Message-ID: "Steve Willoughby" wrote > I think I solved it, actually.. as I was typing this up, I wondered > in passing about this: > >> of the other fonts I configured for the other tags. Do I need to >> keep >> other references to the tkFont objects somewhere else or something? I was going to suggest trying that and if it didn't work to ask on the tkinter group, they are usually pretty responsive. But I confess I've never used font tags (and didn't even know they existed). Alan G. From steve at alchemy.com Fri Jun 17 23:27:00 2011 From: steve at alchemy.com (Steve Willoughby) Date: Fri, 17 Jun 2011 14:27:00 -0700 Subject: [Tutor] Weird tkFont behavior In-Reply-To: References: <4DFA34C5.4060404@alchemy.com> <4DFA38CE.7060604@alchemy.com> Message-ID: <4DFBC6A4.308@alchemy.com> On 17-Jun-11 14:18, Alan Gauld wrote: > But I confess I've never used font tags (and didn't even know > they existed). Neither did I until now. I had been playing with WxPython previously (which is still a great toolkit I'd recommend when it makes sense), but I've been getting happier to see the improvements to what you can do with just plain Tkinter since the last time I used it seriously. Tkinter and ttk do have the advantage of already being right there in the standard library. -- 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 vicpro2 at yahoo.com Sat Jun 18 00:34:31 2011 From: vicpro2 at yahoo.com (Victor) Date: Fri, 17 Jun 2011 15:34:31 -0700 (PDT) Subject: [Tutor] Need script help with concept Message-ID: <833771.43758.qm@web113502.mail.gq1.yahoo.com> I am in the process of building a script but I do not know if what I am trying to do is possible. So, long story short, I need help. ? The concept: I am want to be able to ask the user a series of questions in the program window. ? But here is the action I want to appear on the screen. ? 0. Question pops up 1. User inputs answer 2. User press enter 3. The first question and answer is replaced with a new question on the screen 4. User answers the second question 5. User press enter 6. Question and answer disappears 7. etc. ? All user inputs are placed in a variable. ? Please help. :-) ? ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From enalicho at gmail.com Sat Jun 18 00:51:15 2011 From: enalicho at gmail.com (Noah Hall) Date: Fri, 17 Jun 2011 23:51:15 +0100 Subject: [Tutor] Need script help with concept In-Reply-To: <833771.43758.qm@web113502.mail.gq1.yahoo.com> References: <833771.43758.qm@web113502.mail.gq1.yahoo.com> Message-ID: On Fri, Jun 17, 2011 at 11:34 PM, Victor wrote: > I am in the process of building a script but I do not know if what I am > trying to do is possible. So, long story short, I need help. > > The concept: > I am want to be able to ask the user a series of questions in the program > window. > > But here is the action I want to appear on the screen. > > 0. Question pops up > 1. User inputs answer > 2. User press enter > 3. The first question and answer is replaced with a new question on the > screen > 4. User answers the second question > 5. User press enter > 6. Question and answer disappears > 7. etc. > > All user inputs are placed in a variable. > > Please help. :-) > One way I read this (not sure if this is what you meant, if so, skip down to the bottom): Very possible, and very easy. Sounds a bit too much like a homework question for me to give you complete help ;), however - Look up raw_input. >>> a_variable = raw_input('Is this a question?') Is this a question?Yes >>> print a_variable Yes Make a program, or attempt to, and post back here with any questions. Of course, if you mean *completely in-place replace* the question, then you will need something like ncurses (if on Linux) - http://docs.python.org/library/curses.html If on Windows, have a look at - http://effbot.org/zone/console-index.htm HTH. -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreengels at gmail.com Sat Jun 18 00:54:16 2011 From: andreengels at gmail.com (Andre Engels) Date: Sat, 18 Jun 2011 00:54:16 +0200 Subject: [Tutor] Step Value In-Reply-To: References: <790326.68712.qm@web59401.mail.ac4.yahoo.com> <31871108.post@talk.nabble.com> Message-ID: On Fri, Jun 17, 2011 at 11:03 PM, Alan Gauld wrote: > > "Vincent Balmori" wrote > >> Here is my updated code. As simple as this may be, I am a little lost >> again. > > I'm not sure why you are lost because that's pretty much it. > >> ... at this point (especially after one week) this is when me being >> given the answer with an explanation will help me much more, so I can >> understand how it works better. > > The answer is: > >> def ask_number(question, low, high, step = 1): >> ? """Ask for a number within a range.""" >> ? response = None >> ? while response not in range(low, high, step): >> ? ? ? response = int(input(question)) >> ? return response > > With the only comment being that you don't really need the > response=None line because response always gets set > inside the loop. But the value of response is used in starting the loop (it is needed to test whether the loop should be gone through a first time), so one _does_ need that line. -- Andr? Engels, andreengels at gmail.com From cbc at unc.edu Sat Jun 18 01:46:49 2011 From: cbc at unc.edu (Chris Calloway) Date: Fri, 17 Jun 2011 19:46:49 -0400 Subject: [Tutor] Seattle PyCamp 2011 Message-ID: <4DFBE769.7000701@unc.edu> University of Washington Marketing and the Seattle Plone Gathering host the inaugural Seattle PyCamp 2011 at The Paul G. Allen Center for Computer Science & Engineering on Monday, August 29 through Friday, September 2, 2011. Register today at http://trizpug.org/boot-camp/seapy11/ 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 five days at PyCamp! PyCamp is conducted on the campus of the University of Washington 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 enalicho at gmail.com Sat Jun 18 02:09:13 2011 From: enalicho at gmail.com (Noah Hall) Date: Sat, 18 Jun 2011 01:09:13 +0100 Subject: [Tutor] Seattle PyCamp 2011 In-Reply-To: <4DFBE769.7000701@unc.edu> References: <4DFBE769.7000701@unc.edu> Message-ID: On Sat, Jun 18, 2011 at 12:46 AM, Chris Calloway wrote: > University of Washington Marketing and the Seattle Plone Gathering host the > inaugural Seattle PyCamp 2011 at The Paul G. Allen Center for Computer > Science & Engineering on Monday, August 29 through Friday, September 2, > 2011. > > Register today at http://trizpug.org/boot-camp/seapy11/ > > 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 five days at PyCamp! PyCamp is > conducted on the campus of the University of Washington in a state of the > art high technology classroom. Just a note, but are these questions jokes? >Know how to use a text editor (not a word processor, but a text editor)? >Know how to use a browser to download a file? >Know how to run a program installer? If not, then I'd consider removing them. This isn't 1984. From alan.gauld at btinternet.com Sat Jun 18 02:32:20 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sat, 18 Jun 2011 01:32:20 +0100 (BST) Subject: [Tutor] Step Value In-Reply-To: References: <790326.68712.qm@web59401.mail.ac4.yahoo.com> <31871108.post@talk.nabble.com> Message-ID: <386163.52701.qm@web86706.mail.ird.yahoo.com> >> def ask_number(question, low, high, step = 1): >> """Ask for a number within a range.""" >> response = None >> while response not in range(low, high, step): >> response = int(input(question)) >> return response > > With the only comment being that you don't really need the > response=None line because response always gets set > inside the loop. > But the value of response is used in starting the loop (it is needed > to test whether the loop should be gone through a first time), so one > _does_ need that line. Doh! Stoopid me, of course it is. So the function is pretty much fine as it is. Apologies, Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Jun 18 02:47:39 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 18 Jun 2011 01:47:39 +0100 Subject: [Tutor] Weird tkFont behavior References: <4DFA34C5.4060404@alchemy.com> <4DFA38CE.7060604@alchemy.com> <4DFBC6A4.308@alchemy.com> Message-ID: "Steve Willoughby" wrote > I've been getting happier to see the improvements to what you can do > with just plain Tkinter since the last time I used it seriously. I agree, Tkinter still gets a lot of bad feedback about its look but with ttk that's no longer justified. wxPython still has the edge for fully featured GUI work but for basic GUI work Tkinter/ttk is easier and works "out of the box" with most python installations. Alan G From alan.gauld at btinternet.com Sat Jun 18 02:59:56 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 18 Jun 2011 01:59:56 +0100 Subject: [Tutor] Need script help with concept References: <833771.43758.qm@web113502.mail.gq1.yahoo.com> Message-ID: "Noah Hall" wrote > Of course, if you mean *completely in-place replace* the question, > then you > will need something like ncurses (if on Linux) - > http://docs.python.org/library/curses.html Well, for this you could just use a lot of print statements(in a loop) or print a lot of newlines... curses would be nicer but not really necessary. But I aghree, it does sound close to homework... Alan G., From steve at pearwood.info Sat Jun 18 03:15:18 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 18 Jun 2011 11:15:18 +1000 Subject: [Tutor] Seattle PyCamp 2011 In-Reply-To: References: <4DFBE769.7000701@unc.edu> Message-ID: <4DFBFC26.3030104@pearwood.info> Noah Hall wrote: > Just a note, but are these questions jokes? > >> Know how to use a text editor (not a word processor, but a text editor)? >> Know how to use a browser to download a file? >> Know how to run a program installer? > > If not, then I'd consider removing them. This isn't 1984. I think the questions are fine. It indicates the level of technical knowledge required -- not much, but more than just the ability to sign in to AOL. In 1984 the newbies didn't know anything about computers *and knew they didn't know*, but now you have people who think that because they can write a letter in Microsoft Office and save as HTML, they're expert at programming. I wish I were joking but I've had to work for some of them. -- Steven From kb1pkl at aim.com Sat Jun 18 03:13:44 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Fri, 17 Jun 2011 21:13:44 -0400 (EDT) Subject: [Tutor] Need script help with concept In-Reply-To: References: <833771.43758.qm@web113502.mail.gq1.yahoo.com> Message-ID: <8CDFB6C19DDFD06-2178-2C0D6@webmail-d082.sysops.aol.com> "Noah Hall" wrote > Of course, if you mean *completely in-place replace* the question, > then you > will need something like ncurses (if on Linux) - > http://docs.python.org/library/curses.html There also exists urwid, which is multiplatform, and is also less painful to use. I hear there is a port for Python 3 somewhere too. http://excess.org/urwid/ (Apologies if email is HTML, using a web client) -- Corey Richardson From enalicho at gmail.com Sat Jun 18 05:03:28 2011 From: enalicho at gmail.com (Noah Hall) Date: Sat, 18 Jun 2011 04:03:28 +0100 Subject: [Tutor] Seattle PyCamp 2011 In-Reply-To: <4DFBFC26.3030104@pearwood.info> References: <4DFBE769.7000701@unc.edu> <4DFBFC26.3030104@pearwood.info> Message-ID: On Sat, Jun 18, 2011 at 2:15 AM, Steven D'Aprano wrote: > Noah Hall wrote: > >> Just a note, but are these questions jokes? >> >>> Know how to use a text editor (not a word processor, but a text editor)? >>> Know how to use a browser to download a file? >>> Know how to run a program installer? >> >> If not, then I'd consider removing them. This isn't 1984. > > I think the questions are fine. It indicates the level of technical > knowledge required -- not much, but more than just the ability to sign in to > AOL. > > In 1984 the newbies didn't know anything about computers *and knew they > didn't know*, but now you have people who think that because they can write > a letter in Microsoft Office and save as HTML, they're expert at > programming. > > I wish I were joking but I've had to work for some of them. That's true, I suppose, but in that case the rest of the questions are out of place. I believe that someone who knows what environmental variables are and how to change them is a huge step up from someone who knows how to *download things*. From enalicho at gmail.com Sat Jun 18 05:06:01 2011 From: enalicho at gmail.com (Noah Hall) Date: Sat, 18 Jun 2011 04:06:01 +0100 Subject: [Tutor] Need script help with concept In-Reply-To: <8CDFB6C19DDFD06-2178-2C0D6@webmail-d082.sysops.aol.com> References: <833771.43758.qm@web113502.mail.gq1.yahoo.com> <8CDFB6C19DDFD06-2178-2C0D6@webmail-d082.sysops.aol.com> Message-ID: On Sat, Jun 18, 2011 at 2:13 AM, Corey Richardson wrote: > "Noah Hall" wrote > >> Of course, if you mean *completely in-place replace* the question, >> then you >> will need something like ncurses (if on Linux) ?- >> http://docs.python.org/library/curses.html > > There also exists urwid, which is multiplatform, and is also less painful to > use. I hear > there is a port for Python 3 somewhere too. http://excess.org/urwid/ > (Apologies if email is HTML, using a web client) I'm pretty sure that's not native to Windows; you'd have to use Cygwin, in which case you might as well use curses. From vincentbalmori at yahoo.com Sat Jun 18 05:21:06 2011 From: vincentbalmori at yahoo.com (Vincent Balmori) Date: Fri, 17 Jun 2011 20:21:06 -0700 (PDT) Subject: [Tutor] Main Function Message-ID: <31873480.post@talk.nabble.com> I answered another question that says "Modify the guess_number program so that the program's code is in a function called main(). Don't forget to call main() so you can play the game." It seems to be working fine, but I would like to have a second opinion if there was a better way to put it together. # Guess My Number # # The computer picks a random number between 1 and 10 # The player tries to guess it and the computer lets # the player know if the guess is too high, too low # or right on the money import random def display_instruct(): print("\tWelcome to 'Guess My Number'!") print("\nI'm thinking of a number between 1 and 10.") print("Try to guess it in as few attempts as possible.\n") # set ask_number function def ask_number(question, low, high, step = 1): """Ask for a number within a range.""" response = None while response not in range(low, high, step): response = int(input(question)) return response # guessing loop def num(): # set the initial values the_number = random.randint(1, 10) tries = 0 guess = None while guess != the_number and tries < 4: guess = ask_number("Take a guess:", 1, 10) if guess > the_number: print("Lower...") else: print("Higher...") tries += 1 if tries == 4: print("\nYou fail!") input("\n\nPress the enter key to exit.") break while guess == the_number: print("\nYou guessed it! The number was", the_number) print("And it only took you", tries, "tries!\n") input("\n\nPress the enter key to exit.") break def main(): display_instruct() num() # start the program main() input("\n\nPress the enter key to quit.") -- View this message in context: http://old.nabble.com/Main-Function-tp31873480p31873480.html Sent from the Python - tutor mailing list archive at Nabble.com. From steve at pearwood.info Sat Jun 18 06:20:28 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 18 Jun 2011 14:20:28 +1000 Subject: [Tutor] Step Value In-Reply-To: <31871108.post@talk.nabble.com> References: <790326.68712.qm@web59401.mail.ac4.yahoo.com> <31871108.post@talk.nabble.com> Message-ID: <4DFC278C.3000400@pearwood.info> Vincent Balmori wrote: > Here is my updated code. As simple as this may be, I am a little lost again. > I appreciate the help and explanations to try to push me to get this on my > own, but at this point (especially after one week) this is when me being > given the answer with an explanation will help me much more, so I can > understand how it works better. > > def ask_number(question, low, high, step = 1): > """Ask for a number within a range.""" > response = None > while response not in range(low, high, step): > response = int(input(question)) > return response You've got it now! Well done. The trick is, you have to include the argument in the function parameter list, AND give it a value. The part "step=1" inside the parentheses of the "def" line does exactly that. def ask_number(question, low, high, step=1): ....................................^^^^^^ Suppose you call the function like this: ask_number("hello", 1, 10) Python takes the arguments you give from left to right and assigns them to the function parameters: question = "hello" low = 1 high = 10 step = ??? no value given Because you haven't supplied a value for step, Python next looks for a default, and finds the value 1, so it uses that instead of raising an exception (and error message). -- Steven From steve at pearwood.info Sat Jun 18 06:29:58 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 18 Jun 2011 14:29:58 +1000 Subject: [Tutor] Break stament issue In-Reply-To: References: Message-ID: <4DFC29C6.7070401@pearwood.info> Susana Iraiis Delgado Rodriguez wrote: > Hello members!! > > Steven, I already changed the settings in the IDE to avoid the trouble when > I type the code. > In the other hand I added the pass statement so the script keep working even > though it finds an error, but the scripts ignore the pass statement. Console > prints: > > Traceback (most recent call last): > File "", line 1, in > File "mapnik_punto_sin_duda.py", line 44, in > lyr.datasource = mapnik.Shapefile(base=ruta,file=archivo[0]) > File "C:\mapnik-0.7.1\python\2.6\site-packages\mapnik\__init__.py", line > 282, > in Shapefile > return CreateDatasource(keywords) > RuntimeError: wrong file code : -1997790976 This looks like an internal error of mapnik. I know nothing about mapnik, but my wild guess is that it expects a filename and you are giving it something else? Or the wrong filename? Or maybe it expects an open file, and you have given it a filename? -- Steven From steve at pearwood.info Sat Jun 18 06:42:05 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 18 Jun 2011 14:42:05 +1000 Subject: [Tutor] Medical Decision-Making Question In-Reply-To: References: Message-ID: <4DFC2C9D.9040404@pearwood.info> Fred G wrote: > Thanks guys for all the feedback. > > re Jim's comments: I completely agree that the difference b/t "slight" fever > and "returning" fever, etc will pose some problems. My hunch is that > initially I'll just do something like make "fever" be the only one for now Any qualitative rating system is going to be subjective. If this expert system is aimed at doctors, you may be able to ask for actual temperatures rather than just "fever". Otherwise, you will have to come up with your own idea for what "slight" vs. "strong" fever might mean. The accuracy of the diagnosis will depend in part on how well the user's idea of "slight" matches yours. > re Steve's comments: hmm, sounds like I really should take an AI class. > This problem is just really exciting and driving me, and I'm glad you > pointed out that this will probably take a lot more time than I had > predicted. I'm pretty motivated personally to solve it. I had a few more > questions about your code: > a) Why did you choose not to use a dictionary to store the diseases (keys) > and their possible values (symptoms)? That seemed the most intuitive to me, Because it was nearly 2am when I came up with the idea and it was just the first thing that popped into my head. Don't imagine that I had sat down and designed the application! :) You're right though that good design of your data structures is vital. -- Steven From lisi.reisz at gmail.com Sat Jun 18 13:52:13 2011 From: lisi.reisz at gmail.com (Lisi) Date: Sat, 18 Jun 2011 12:52:13 +0100 Subject: [Tutor] Closing triple quotation marks. Message-ID: <201106181252.13897.lisi.reisz@gmail.com> I have left the program intact below* because I am afraid that if I cut it I may cut out something that is essential. I am working from an existing program that I have typed out under instructions, but am now trying to replace the commented out section with just one command. The program with the commented out section worked fine. I have been stuck for some hourslast night andagain this morning. I have inserted the print command after the commented out section in order simply to try out whether the triple quotation marks ever work as I thought they did, and the answer is yes they do. If I leave the target.write without the final """, I get the error (which I would indeed expect): lisi at Tux:~/Python/LearnPythonTheHardWay$ python extra-credit_16a.py learning.txt File "extra-credit_16a.py", line 42 ^ SyntaxError: EOF while scanning triple-quoted string lisi at Tux:~/Python/LearnPythonTheHardWay Fair enough. the closing quotation marks are not there. But when they _are_ there, i.e. when that stanza reads: target.write """ line1\nline2\nline3\n """ I get: lisi at Tux:~/Python/LearnPythonTheHardWay$ python extra-credit_16a.py learning.txt File "extra-credit_16a.py", line 38 """ ^ SyntaxError: invalid syntax So where should I be putting those wretched triple quotes? I have been stuck on this for hours. With the target.write stanza there, none of the rest of the program works either. If I comment out the target.write stanza and leave the print stanza above it alone, the whole program runs as I would expect it to. I have searched the Python.org site; I have googled; I am stuck and have run out of ideas. Lisi *Herewith the program: from sys import argv script, filename=argv print "We're going to erase %r." % filename print "If you don't want that, hit CTRL-C (^C)." print "If you do want that, hit RETURN." raw_input("?") print "Opening the file..." target=open(filename, 'w') print "Truncating the file. Goodbye!" target.truncate() print "Now I'm going to ask you for three lines." line1=raw_input("line1: ") line2=raw_input("line2: ") line3=raw_input("line3: ") print "I'm going to write these to the file." # target.write(line1) # target.write("\n") # target.write(line2) # target.write("\n") # target.write(line3) # target.write("\n") print """ line1\nline2\nline3\n """ target.write """ line1\nline2\nline3\n print "And finally we close it." target.close() From steve at pearwood.info Sat Jun 18 14:37:38 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 18 Jun 2011 22:37:38 +1000 Subject: [Tutor] Closing triple quotation marks. In-Reply-To: <201106181252.13897.lisi.reisz@gmail.com> References: <201106181252.13897.lisi.reisz@gmail.com> Message-ID: <4DFC9C12.8010102@pearwood.info> Lisi wrote: [...] > Fair enough. the closing quotation marks are not there. > > But when they _are_ there, i.e. when that stanza reads: > > target.write """ > line1\nline2\nline3\n > """ This is not the problem, but I just thought I'd mention that it's a bit silly to go to the trouble of using newline escape characters inside a triple-quoted string! You can do it if you want, but this would be more naturally written as: """ line 1 line 2 line 3 """ Now, on to your actual error: > I get: > > lisi at Tux:~/Python/LearnPythonTheHardWay$ python extra-credit_16a.py > learning.txt > File "extra-credit_16a.py", line 38 > """ > ^ > SyntaxError: invalid syntax This has nothing to do with the triple quote marks. Simplify the code by shrinking the text inside the quotes to a single line, and you get: target.write "..." and you will get the same SyntaxError. Can you see the problem? No brackets! You need to include parentheses to call the write method: target.write("...") Then you can expand the string to use a triple-quote: target.write(""" line 1 line 2 line 3 """) and all should be good. -- Steven From lisi.reisz at gmail.com Sat Jun 18 15:50:29 2011 From: lisi.reisz at gmail.com (Lisi) Date: Sat, 18 Jun 2011 14:50:29 +0100 Subject: [Tutor] Closing triple quotation marks. In-Reply-To: <4DFC9C12.8010102@pearwood.info> References: <201106181252.13897.lisi.reisz@gmail.com> <4DFC9C12.8010102@pearwood.info> Message-ID: <201106181450.29729.lisi.reisz@gmail.com> On Saturday 18 June 2011 13:37:38 Steven D'Aprano wrote: > Lisi wrote: > [...] > > > Fair enough. the closing quotation marks are not there. > > > > But when they _are_ there, i.e. when that stanza reads: > > > > target.write """ > > line1\nline2\nline3\n > > """ > > This is not the problem, but I just thought I'd mention that it's a bit > silly to go to the trouble of using newline escape characters inside a > triple-quoted string! You can do it if you want, but this would be more > naturally written as: > > """ > line 1 > line 2 > line 3 > """ > > Now, on to your actual error: > > I get: > > > > lisi at Tux:~/Python/LearnPythonTheHardWay$ python extra-credit_16a.py > > learning.txt > > File "extra-credit_16a.py", line 38 > > """ > > ^ > > SyntaxError: invalid syntax > > This has nothing to do with the triple quote marks. Simplify the code by > shrinking the text inside the quotes to a single line, and you get: > > target.write "..." > > > and you will get the same SyntaxError. Can you see the problem? No > brackets! You need to include parentheses to call the write method: > > target.write("...") > > > Then you can expand the string to use a triple-quote: > > target.write(""" > line 1 > line 2 > line 3 > """) > > and all should be good. Thanks very much, Steven. I did at some stage in the dim and distant past try brackets, but I probably put them in the wrong place. But I still can't write to the file. If I do: target.write(line1) The value of the variable line1 is written to the file. But if I put the three variables into the write command, what gets printed is the name of the variables, not their values. I am clearly still doing something wrong. But I can't see what. I have even tried to see whether ''' gave a different result from """, but it doesn't. I have accepted KWrite's idea of what the white space should be, and I have adapted it to all the variations I can think of. At the moment it is: target.write(""" line1 line2 line3 """) I am beginning to feel paranoid! I simply can't see in what way that differs from yours. In case it is relevant, I am using Python 2.5.2 (r252:60911, Jan 24 2010, 14:53:14) [GCC 4.3.2] on Debian 5 with a 2.6.26 kernel. I was trying not to move on until I had mastered everything in this section, but I am beginning to think that that is foolish. I am getting myself more and more bogged down, and it might be more sensible to pass on and come back to it. Again, thank you for your very prompt help. I have, I hope, finally _fully_ taken in that many commands need (). And that it is possible to get a new line just by giving a new line - without the explicit instruction. I.e., hopefully, I have learnt something. Lisi From steve at pearwood.info Sat Jun 18 16:23:30 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 19 Jun 2011 00:23:30 +1000 Subject: [Tutor] Closing triple quotation marks. In-Reply-To: <201106181450.29729.lisi.reisz@gmail.com> References: <201106181252.13897.lisi.reisz@gmail.com> <4DFC9C12.8010102@pearwood.info> <201106181450.29729.lisi.reisz@gmail.com> Message-ID: <4DFCB4E2.7040106@pearwood.info> Lisi wrote: > But I still can't write to the file. > > If I do: > target.write(line1) > > The value of the variable line1 is written to the file. But if I put the > three variables into the write command, what gets printed is the name of the > variables, not their values. I am clearly still doing something wrong. But I > can't see what. I have even tried to see whether ''' gave a different result > from """, but it doesn't. I have accepted KWrite's idea of what the white > space should be, and I have adapted it to all the variations I can think of. What gets written is the string that is passed to write(). Anything inside quotation marks (single, or triple) is a string, not a variable. "line1" has nothing to do with the variable line1, it is merely the letters l i n e followed by digit 1. Python will never try to guess whether you mean a string "x" or a variable x. If it is inside quote marks, it is always a string. There are a number of ways to write the contents of variables to a file. The best way depends on how many variables you have, and whether they are already strings or not. Here are a few: # line1 etc. are already strings, and there are only a few of them: target.write(line1 + '\n') # add a newline after each string target.write(line2 + '\n') target.write(line3 + '\n') # here's another way, using String Interpolation: template = """ %s %s %s """ text = template % (line1, line2, line3) # each %s inside the template is replaced with the contents # of line1, line2 and line3 respectively target.write(text) # finally, if you have many lines, or a variable number of them: lines = [line1, line2, line3] # and possible more... text = '\n'.join(lines) target.write(text) -- Steven From alan.gauld at btinternet.com Sat Jun 18 16:58:23 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 18 Jun 2011 15:58:23 +0100 Subject: [Tutor] Closing triple quotation marks. References: <201106181252.13897.lisi.reisz@gmail.com><4DFC9C12.8010102@pearwood.info> <201106181450.29729.lisi.reisz@gmail.com> Message-ID: "Lisi" wrote > But I still can't write to the file. > > If I do: > target.write(line1) > > The value of the variable line1 is written to the file. That will work provided line1 is a string. > But if I put the three variables into the write command, > what gets printed is the name of the variables, not their values. > At the moment it is: > target.write(""" > line1 > line2 > line3 > """) This is not three variables it is a single string value that coincidentally has the names of three of your variables inside it. But Python has no way to guess that. You need to be clear on the different between a variable: a name that references a value(or object if you prefer) and a string which is a type of value(a string object) In the first case you pass a name (line1) in the second you pass a value (the string literal) > I am beginning to feel paranoid! I simply can't see in what way > that differs > from yours. quote signs > I have, I hope, finally _fully_ taken in that many commands need (). Actually commands do not usually need (), it is functions and methods that need (). They are different. print is a command and it does not need () - in Python 2 at least! print 1,2,"some words" But file.write() is a method of the file object and must have parentheses. f.write("some words") The () are an instruction to execute the function. Without the () Python treats the function as an object in its own right: list_of_objects = [1,"a string",f.write] for obj in list_of_objects: print "Object is: ", obj > it is possible to get a new line just by giving a new line - without > the > explicit instruction. That is the unique selling point of triple quoted strings, you can embed newlines inside them. This makes them most useful for docstrings (which decribe what a function is for): def myFunc(): """"myFunc() -> None Does some useful background processing with no obvious impact on data. """ theAnswer = 7*6 HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From benderjacob44 at gmail.com Sat Jun 18 18:05:54 2011 From: benderjacob44 at gmail.com (Jacob Bender) Date: Sat, 18 Jun 2011 09:05:54 -0700 Subject: [Tutor] Communicating Between Programs Using Raw Inputs (con'd) Message-ID: Dear Tutors, Alright, I'm using linux (ubuntu) and I took all of your advice and I got something that works and doesn't work at the same time. Here's the source code for my two programs called Lock and Key: *Lock.py: * password = "a" psswd_try = raw_input("What's the password? ") if psswd_try == password: print "correct!!!" raw_input() else: print "wrong" raw_input() * Key.py*: import sys sys.stdout.write("a") In the linux terminal I ran this command(they were both in my home folder, so no directories were needed): python Key.py | python Lock.py And all went well except for an EOF error caused by the raw_input inside the "if" statement in my Lock program. However I did get it to print "correct", so I know sys.stdout.write() works for what I want it to, but I don't want the EOF error. Here's the output: Traceback (most recent call last): File "Lock.py", line 7, in raw_input() EOFError: EOF when reading a line Please help me get rid of it because I couldn't find a sys.stdout.close() command or any other std command that would help. Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From Warrior at programmer.net Sat Jun 18 22:02:34 2011 From: Warrior at programmer.net (Kaustubh Pratap chand) Date: Sat, 18 Jun 2011 20:02:34 +0000 Subject: [Tutor] BF Program hangs Message-ID: <20110618200235.42810@gmx.com> Hello i made this program which interprets brainf*** But i don't understand why it doesn't ends....and also it doesn't print anything import sys cell=[0] * 30000 code_pointer=0 cell_pointer=0 close_brace_pos=0 open_brace_pos=0 bf=raw_input("Input bf program:") while (code_pointer': cell_pointer+=1 code_pointer+=1 elif c=='<': cell_pointer-=1 code_pointer+=1 elif c=='+': cell[cell_pointer]+=1 code_pointer+=1 elif c=='-': cell[cell_pointer]-=1 code_pointer+=1 elif c=='[': if cell[cell_pointer]>0: code_pointer+=1 else: code_pointer=close_brace_pos+1 elif c==']': close_brace_pos=code_pointer code_pointer=open_brace_pos else: code_pointer+=1 For those of you who don't understand brainfuck its a very simple 8 instruction language http://en.wikipedia.org/wiki/Brainfuck -------------- next part -------------- An HTML attachment was scrubbed... URL: From wescpy at gmail.com Sat Jun 18 22:52:23 2011 From: wescpy at gmail.com (wesley chun) Date: Sat, 18 Jun 2011 22:52:23 +0200 Subject: [Tutor] BF Program hangs In-Reply-To: <20110618200235.42810@gmx.com> References: <20110618200235.42810@gmx.com> Message-ID: On Sat, Jun 18, 2011 at 10:02 PM, Kaustubh Pratap chand wrote: > Hello i made this program which interprets brainf*** > > But i don't understand why it doesn't ends....and also it doesn't print > anything can you tell us more about the code other than "it doesn't end" and "it doesn't print anything?" *why* doesn't it print anything? do you have a print statement or function in your code? no, you don't. also, why do you use sys.stdout instead of print? we just want to know your rationale because most people would use print instead. also, why don't you think your program ends? what is preventing "the end" from happening? the more you can describe your problem as well as the code you've written, the easier it will be for us to help you out. please also document your code so that other beginners can read it too... thanks! -- 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 Jun 19 01:55:26 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 19 Jun 2011 00:55:26 +0100 Subject: [Tutor] Communicating Between Programs Using Raw Inputs (con'd) References: Message-ID: "Jacob Bender" wrote > *Lock.py: * > > password = "a" > psswd_try = raw_input("What's the password? ") > > if psswd_try == password: > print "correct!!!" > raw_input() > else: > print "wrong" > raw_input() > * > Key.py*: > > import sys > sys.stdout.write("a") > > And all went well except for an EOF error caused > by the raw_input inside the "if" statement in my > Lock program. However I did get it to print "correct", You ask for two inputs but only provide one, so you get an error. The Key.py program closes stdout (which is Lock.py's stdin) before Lock.py gets any second input. Add another print(or sys.stdout.write() ) to Key.py and see how you get on. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From mehgcap at gmail.com Sun Jun 19 02:16:49 2011 From: mehgcap at gmail.com (Alex Hall) Date: Sat, 18 Jun 2011 20:16:49 -0400 Subject: [Tutor] using configobj package to output quoted strings Message-ID: Hello all, I am using the configobj package to handle a ridiculously simple ini file, which takes the form: [favorites] "search name" = "search terms", "search type" for any number of searches stored in the favorites section. I need the search type, term, and name to be read in as strings, but they will usually contain spaces, which is why I put them in quotes. Here is the question: when I try to add a search to the ini file, I cannot get the quotes to show up correctly. I just want my three strings enclosed in single or double quotes, but I cannot manage to do it. I either get no quotes, or, when I manually add them (such as "\""+searchTerms+"\"" and so on), I get strings surrounded by both double and single quotes. All documentation for configobj talks about using quotes so that keys and values will be read correctly, yet programmitically writing these quotes is proving very difficult. I am not sure if this is a python thing or a configobj thing, but it seems like it would be a relatively simple task. Is there a simple function I do not know about that will let me do this? Thanks. -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From nauty.me04 at gmail.com Sun Jun 19 03:55:47 2011 From: nauty.me04 at gmail.com (aditya) Date: Sun, 19 Jun 2011 07:25:47 +0530 Subject: [Tutor] Communicating Between Programs Using Raw Inputs (con'd) In-Reply-To: References: Message-ID: On Sat, Jun 18, 2011 at 9:35 PM, Jacob Bender wrote: > Dear Tutors, > > Alright, I'm using linux (ubuntu) and I took all of your advice and I got > something that works and doesn't work at the same time. Here's the source > code for my two programs called Lock and Key: > > *Lock.py: * > > password = "a" > > psswd_try = raw_input("What's the password? ") > > if psswd_try == password: > print "correct!!!" > raw_input() > else: > print "wrong" > raw_input() > * > * Why do you need to call raw_input() again? You are giving the input only once so remove raw_input() from both if and else , that should do the work > *Key.py*: > > import sys > > sys.stdout.write("a") > > In the linux terminal I ran this command(they were both in my home folder, > so no directories were needed): > > python Key.py | python Lock.py > > And all went well except for an EOF error caused by the raw_input inside > the "if" statement in my Lock program. However I did get it to print > "correct", so I know sys.stdout.write() works for what I want it to, but I > don't want the EOF error. Here's the output: > > Traceback (most recent call last): > File "Lock.py", line 7, in > raw_input() > EOFError: EOF when reading a line > > Please help me get rid of it because I couldn't find a sys.stdout.close() > command or any other std command that would help. > > Thanks! > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Regards Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sun Jun 19 04:29:08 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 19 Jun 2011 12:29:08 +1000 Subject: [Tutor] using configobj package to output quoted strings In-Reply-To: References: Message-ID: <4DFD5EF4.6060001@pearwood.info> Alex Hall wrote: > Hello all, > I am using the configobj package to handle a ridiculously simple ini What's configobj? >>> import configobj Traceback (most recent call last): File "", line 1, in ImportError: No module named configobj It's not in the 3.1 standard library. Is it a third-part package, or one you have written yourself, or something else? > file, which takes the form: > [favorites] > "search name" = "search terms", "search type" > > for any number of searches stored in the favorites section. I need the > search type, term, and name to be read in as strings, but they will > usually contain spaces, which is why I put them in quotes. You shouldn't need quotes. The standard library configparser module doesn't need them: >>> import configparser >>> ini = configparser.ConfigParser( ... {"key with spaces": "value with spaces, and a comma"}) >>> ini.defaults() OrderedDict([('key with spaces', 'value with spaces, and a comma')]) >>> >>> ini.get("DEFAULT", "key with spaces") 'value with spaces, and a comma' You can use quotes if you like, but why bother? >>> ini.set('DEFAULT', '"search name"', "some value") >>> ini.defaults() OrderedDict([('key with spaces', 'value with spaces, and a comma'), ('"search name"', 'some value')]) > Here is the > question: when I try to add a search to the ini file, I cannot get the > quotes to show up correctly. I just want my three strings enclosed in > single or double quotes, but I cannot manage to do it. I either get no What do you mean by "show up"? What are you using to do the showing? Remember, that when Python displays strings, the outer-most set of quotes are not part of the string. They're just the syntax to tell Python you are typing a string, and not part of the string, in the same way that the [ ] surrounding a list are not actually part of the list. So if I do this: >>> s = "hello world" >>> s 'hello world' The string is made up of characters h e l l o etc. and *not* the quotes. You can see the string without the delimiters by using print: >>> print(s) hello world but if you print an object containing a string, you still get the quotes (for obvious reasons): >>> print([1, 2, s]) [1, 2, 'hello world'] So, the question is, are you mistaking the string syntax for the contents of the string? If so, you will hardly be the first one! > quotes, or, when I manually add them (such as "\""+searchTerms+"\"" > and so on), I get strings surrounded by both double and single quotes. Sounds like you are mistaking them. If you do this: >>> searchTerms = "hello world" >>> "\"" + searchTerms + "\"" '"hello world"' The single quotes are just delimiters. The double quotes are part of the string, exactly as you wanted. Also, there is never any need to write something as ugly as "\"". This is why Python gives you a choice of two different string delimiters, single and double quotes. That is better written as: '"' with no need to escape the inner quote. The only good reason to escape a quotation mark is if you need *both* quote marks in a single string: "John Cleese said, \"'e's not dead, 'e's just pining for the fjords!\"" -- Steven From mehgcap at gmail.com Sun Jun 19 04:44:28 2011 From: mehgcap at gmail.com (Alex Hall) Date: Sat, 18 Jun 2011 22:44:28 -0400 Subject: [Tutor] using configobj package to output quoted strings In-Reply-To: <4DFD5EF4.6060001@pearwood.info> References: <4DFD5EF4.6060001@pearwood.info> Message-ID: On 6/18/11, Steven D'Aprano wrote: > Alex Hall wrote: >> Hello all, >> I am using the configobj package to handle a ridiculously simple ini > > What's configobj? > > >>> import configobj > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named configobj > > It's not in the 3.1 standard library. Is it a third-part package, or one > you have written yourself, or something else? Right, sorry. http://www.voidspace.org.uk/python/configobj.html > > >> file, which takes the form: >> [favorites] >> "search name" = "search terms", "search type" >> >> for any number of searches stored in the favorites section. I need the >> search type, term, and name to be read in as strings, but they will >> usually contain spaces, which is why I put them in quotes. > > You shouldn't need quotes. The standard library configparser module > doesn't need them: I'll have a look at it, but I liked configobj's dictionary approach to everything. > > >>> import configparser > >>> ini = configparser.ConfigParser( > ... {"key with spaces": "value with spaces, and a comma"}) > >>> ini.defaults() > OrderedDict([('key with spaces', 'value with spaces, and a comma')]) > >>> > >>> ini.get("DEFAULT", "key with spaces") > 'value with spaces, and a comma' The value is supposed to be a list; in python, you might write a search like this: searches={ "my first search":["the search terms", "the search type"] } > > > You can use quotes if you like, but why bother? > > > >>> ini.set('DEFAULT', '"search name"', "some value") > >>> ini.defaults() > OrderedDict([('key with spaces', 'value with spaces, and a comma'), > ('"search name"', 'some value')]) > > > >> Here is the >> question: when I try to add a search to the ini file, I cannot get the >> quotes to show up correctly. I just want my three strings enclosed in >> single or double quotes, but I cannot manage to do it. I either get no > > What do you mean by "show up"? What are you using to do the showing? > > Remember, that when Python displays strings, the outer-most set of > quotes are not part of the string. They're just the syntax to tell > Python you are typing a string, and not part of the string, in the same > way that the [ ] surrounding a list are not actually part of the list. I know, that is why I was using backslashes to escape quotes, trying to force the quotes to be outputted to the file when I call configobj's write() method, which takes the entire configuration and puts it in a .ini file. > > So if I do this: > > >>> s = "hello world" > >>> s > 'hello world' > > The string is made up of characters h e l l o etc. and *not* the quotes. > You can see the string without the delimiters by using print: > > >>> print(s) > hello world > > but if you print an object containing a string, you still get the quotes > (for obvious reasons): > > >>> print([1, 2, s]) > [1, 2, 'hello world'] > > > So, the question is, are you mistaking the string syntax for the > contents of the string? If so, you will hardly be the first one! No, the configobj will not see the multiple words of the string as a single value unless there are quotes in the config file. > > > >> quotes, or, when I manually add them (such as "\""+searchTerms+"\"" >> and so on), I get strings surrounded by both double and single quotes. > > Sounds like you are mistaking them. > > If you do this: > > >>> searchTerms = "hello world" > >>> "\"" + searchTerms + "\"" > '"hello world"' > > The single quotes are just delimiters. The double quotes are part of the > string, exactly as you wanted. > > Also, there is never any need to write something as ugly as "\"". This > is why Python gives you a choice of two different string delimiters, > single and double quotes. That is better written as: > > '"' > > with no need to escape the inner quote. The only good reason to escape a > quotation mark is if you need *both* quote marks in a single string: > > "John Cleese said, \"'e's not dead, 'e's just pining for the fjords!\"" Good point. Still, it is odd (well, to me at least) that when I write the string to the file with no quotes, I get no quotes, but using double quotes in the string's value gives me both single and double quotes. > > > > -- > Steven > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From steve at pearwood.info Sun Jun 19 04:48:50 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 19 Jun 2011 12:48:50 +1000 Subject: [Tutor] using configobj package to output quoted strings In-Reply-To: References: <4DFD5EF4.6060001@pearwood.info> Message-ID: <4DFD6392.7070701@pearwood.info> Alex Hall wrote: > Still, it is odd (well, to me at least) that when I write > the string to the file with no quotes, I get no quotes, but using > double quotes in the string's value gives me both single and double > quotes. Sounds to me like bad design on the part of configobj, but perhaps I'm misunderstanding something. -- Steven From lisi.reisz at gmail.com Sun Jun 19 08:47:34 2011 From: lisi.reisz at gmail.com (Lisi) Date: Sun, 19 Jun 2011 07:47:34 +0100 Subject: [Tutor] Closing triple quotation marks. In-Reply-To: References: <201106181252.13897.lisi.reisz@gmail.com> <201106181450.29729.lisi.reisz@gmail.com> Message-ID: <201106190747.34339.lisi.reisz@gmail.com> On Saturday 18 June 2011 15:58:23 Alan Gauld wrote: > "Lisi" wrote > > > But I still can't write to the file. > > > > If I do: > > target.write(line1) > > > > The value of the variable line1 is written to the file. > > That will work provided line1 is a string. > > > But if I put the three variables into the write command, > > what gets printed is the name of the variables, not their values. > > > > At the moment it is: > > target.write(""" > > line1 > > line2 > > line3 > > """) > > This is not three variables it is a single string value that > coincidentally has the names of three of your variables > inside it. But Python has no way to guess that. > > You need to be clear on the different between a variable: > a name that references a value(or object if you prefer) > and a string which is a type of value(a string object) > > In the first case you pass a name (line1) in the second > you pass a value (the string literal) > > > I am beginning to feel paranoid! I simply can't see in what way > > that differs > > from yours. > > quote signs > > > I have, I hope, finally _fully_ taken in that many commands need (). > > Actually commands do not usually need (), it is functions and methods > that need (). They are different. > > print is a command and it does not need () - in Python 2 at least! > > print 1,2,"some words" > > But file.write() is a method of the file object and must have > parentheses. > > f.write("some words") > > The () are an instruction to execute the function. Without > the () Python treats the function as an object in its own right: > > list_of_objects = [1,"a string",f.write] > > for obj in list_of_objects: > print "Object is: ", obj > > > it is possible to get a new line just by giving a new line - without > > the > > explicit instruction. > > That is the unique selling point of triple quoted strings, > you can embed newlines inside them. This makes them > most useful for docstrings (which decribe what a function > is for): > > def myFunc(): > """"myFunc() -> None > > Does some useful background processing with no obvious impact on > data. > """ > theAnswer = 7*6 > > > HTH, It does indeed. Thank you, both of you. I have clearly not got the terms command, method, function (and feature?) clearly sorted out in my mind, so that is obviously where I need to go. I am supposed to be researching import, but I have not yet succeeded in seeing why it is a problem. So I'll switch to looking up method, function etc. Lisi From alan.gauld at btinternet.com Sun Jun 19 09:39:43 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 19 Jun 2011 08:39:43 +0100 Subject: [Tutor] Closing triple quotation marks. References: <201106181252.13897.lisi.reisz@gmail.com><201106181450.29729.lisi.reisz@gmail.com> <201106190747.34339.lisi.reisz@gmail.com> Message-ID: "Lisi" wrote > It does indeed. Thank you, both of you. I have clearly not got the > terms > command, method, function (and feature?) clearly sorted out in my > mind, so > that is obviously where I need to go. I am supposed to be > researching > import, but I have not yet succeeded in seeing why it is a problem. > So I'll > switch to looking up method, function etc. Add "callable" to your list of search terms. Python has the concept of "callable objects" and you can call a callable by using parentheses. You can also test whether an object is callable or not: for obj in list_of_objects: if callable(obj): print obj() # call obj first else: print obj # just use the obj value HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From lisi.reisz at gmail.com Sun Jun 19 09:46:02 2011 From: lisi.reisz at gmail.com (Lisi) Date: Sun, 19 Jun 2011 08:46:02 +0100 Subject: [Tutor] Closing triple quotation marks. In-Reply-To: References: <201106181252.13897.lisi.reisz@gmail.com> <201106190747.34339.lisi.reisz@gmail.com> Message-ID: <201106190846.03109.lisi.reisz@gmail.com> On Sunday 19 June 2011 08:39:43 Alan Gauld wrote: > "Lisi" wrote > > > It does indeed. Thank you, both of you. I have clearly not got the > > terms > > command, method, function (and feature?) clearly sorted out in my > > mind, so > > that is obviously where I need to go. I am supposed to be > > researching > > import, but I have not yet succeeded in seeing why it is a problem. > > So I'll > > switch to looking up method, function etc. > > Add "callable" to your list of search terms. > Python has the concept of "callable objects" and > you can call a callable by using parentheses. > You can also test whether an object is callable > or not: > > for obj in list_of_objects: > if callable(obj): > print obj() # call obj first > else: > print obj # just use the obj value > > HTH, Thank you! Lisi From alan.gauld at btinternet.com Sun Jun 19 09:49:28 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 19 Jun 2011 08:49:28 +0100 Subject: [Tutor] using configobj package to output quoted strings References: <4DFD5EF4.6060001@pearwood.info> Message-ID: "Steven D'Aprano" wrote > ...The only good reason to escape a quotation mark is if you need > *both* quote marks in a single string: > > "John Cleese said, \"'e's not dead, 'e's just pining for the > fjords!\"" And even here you can use outer triple quotes if you prefer: '''John Cleese said, "'e's not dead, 'e's just pining for the fjords!"''' HTH, Alan G. From gerhardus.geldenhuis at gmail.com Sun Jun 19 13:25:07 2011 From: gerhardus.geldenhuis at gmail.com (Gerhardus Geldenhuis) Date: Sun, 19 Jun 2011 12:25:07 +0100 Subject: [Tutor] regex woes in finding an ip and GET string Message-ID: Hi I am trying to write a small program that will scan my access.conf file and update iptables to block anyone looking for stuff that they are not supposed to. The code: #!/usr/bin/python import sys import re def extractoffendingip(filename): f = open(filename,'r') filecontents = f.read() #193.6.135.21 - - [11/Jun/2011:13:58:01 +0000] "GET /admin/pma/scripts/setup.php HTTP/1.1" 404 304 "-" "Mozilla/4.0 (compatible; MSIE 6.0; Windows 98)" tuples = re.findall(r'^(\d+\.\d+\.\d+\.\d+).*\"GET(.*)HTTP', filecontents) iplist = [] for items in tuples: (ip, getstring) = items print ip,getstring #print item if ip not in iplist: iplist.append(ip) for item in iplist: print item #ipmatch = re.search(r'', filecontents) def main(): extractoffendingip('access_log.1') if __name__ == '__main__': main() logfile=http://pastebin.com/F3RXDYBW I could probably have used ranges to be more correct about finding ip's but I thought that apache should take care of that. I am assuming a level or integrity in the log file with regards to data... The first problem I ran into was that I added a ^ to my search string: re.findall(r'^(\d+\.\d+\.\d+\.\d+).*\"GET(.*)HTTP', filecontents) but that finds only two results a lot less than I am expecting. I am a little bit confused, first I thought that it might be because the string I am searching is now only one line because of the method of loading and the ^ should only find one instance but instead it finds two? So removing the ^ works much better but now I get mostly correct results but I also get a number of ip's with an empty get string, only thought there should be only one in the log file. I would really appreciate any pointers as to what is going on here. Regards -- Gerhardus Geldenhuis -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Sun Jun 19 13:33:55 2011 From: davea at ieee.org (Dave Angel) Date: Sun, 19 Jun 2011 07:33:55 -0400 Subject: [Tutor] using configobj package to output quoted strings In-Reply-To: References: <4DFD5EF4.6060001@pearwood.info> Message-ID: <4DFDDEA3.2020203@ieee.org> On 01/-10/-28163 02:59 PM, Alex Hall wrote: > On 6/18/11, Steven D'Aprano wrote: >> Alex Hall wrote: >>> Hello all, >>> I am using the configobj package to handle a ridiculously simple ini >> >> What's configobj? >> >> >>> import configobj >> Traceback (most recent call last): >> File "", line 1, in >> ImportError: No module named configobj >> >> It's not in the 3.1 standard library. Is it a third-part package, or one >> you have written yourself, or something else? > Right, sorry. http://www.voidspace.org.uk/python/configobj.html >> >> >>> file, which takes the form: >>> [favorites] >>> "search name" = "search terms", "search type" >>> >>> for any number of searches stored in the favorites section. I need the >>> search type, term, and name to be read in as strings, but they will >>> usually contain spaces, which is why I put them in quotes. >> >> You shouldn't need quotes. The standard library configparser module >> doesn't need them: > I'll have a look at it, but I liked configobj's dictionary approach to > everything. >> >> >>> import configparser >> >>> ini = configparser.ConfigParser( >> ... {"key with spaces": "value with spaces, and a comma"}) >> >>> ini.defaults() >> OrderedDict([('key with spaces', 'value with spaces, and a comma')]) >> >>> >> >>> ini.get("DEFAULT", "key with spaces") >> 'value with spaces, and a comma' > The value is supposed to be a list; in python, you might write a > search like this: > searches={ > "my first search":["the search terms", "the search type"] > } >> >> >> You can use quotes if you like, but why bother? >> >> >> >>> ini.set('DEFAULT', '"search name"', "some value") >> >>> ini.defaults() >> OrderedDict([('key with spaces', 'value with spaces, and a comma'), >> ('"search name"', 'some value')]) >> >> >> >>> Here is the >>> question: when I try to add a search to the ini file, I cannot get the >>> quotes to show up correctly. I just want my three strings enclosed in >>> single or double quotes, but I cannot manage to do it. I either get no >> >> What do you mean by "show up"? What are you using to do the showing? >> >> Remember, that when Python displays strings, the outer-most set of >> quotes are not part of the string. They're just the syntax to tell >> Python you are typing a string, and not part of the string, in the same >> way that the [ ] surrounding a list are not actually part of the list. > I know, that is why I was using backslashes to escape quotes, trying > to force the quotes to be outputted to the file when I call > configobj's write() method, which takes the entire configuration and > puts it in a .ini file. >> >> So if I do this: >> >> >>> s = "hello world" >> >>> s >> 'hello world' >> >> The string is made up of characters h e l l o etc. and *not* the quotes. >> You can see the string without the delimiters by using print: >> >> >>> print(s) >> hello world >> >> but if you print an object containing a string, you still get the quotes >> (for obvious reasons): >> >> >>> print([1, 2, s]) >> [1, 2, 'hello world'] >> >> >> So, the question is, are you mistaking the string syntax for the >> contents of the string? If so, you will hardly be the first one! > No, the configobj will not see the multiple words of the string as a > single value unless there are quotes in the config file. >> >> >> >>> quotes, or, when I manually add them (such as "\""+searchTerms+"\"" >>> and so on), I get strings surrounded by both double and single quotes. >> >> Sounds like you are mistaking them. >> >> If you do this: >> >> >>> searchTerms = "hello world" >> >>> "\"" + searchTerms + "\"" >> '"hello world"' >> >> The single quotes are just delimiters. The double quotes are part of the >> string, exactly as you wanted. >> >> Also, there is never any need to write something as ugly as "\"". This >> is why Python gives you a choice of two different string delimiters, >> single and double quotes. That is better written as: >> >> '"' >> >> with no need to escape the inner quote. The only good reason to escape a >> quotation mark is if you need *both* quote marks in a single string: >> >> "John Cleese said, \"'e's not dead, 'e's just pining for the fjords!\"" > Good point. Still, it is odd (well, to me at least) that when I write > the string to the file with no quotes, I get no quotes, but using > double quotes in the string's value gives me both single and double > quotes. >> >> When a string is interpreted with repr(), if it has any embedded quotes in it, it will be displayed with the others around the outside. But if it has no funny characters, it will still put quotes around it. str(), on the other hand, doesn't add either one. Without any context, we've been guessing wildly. it's good that you now include a link to the package. But you still aren't showing what calls you use to write to the file, nor what calls you're using to read the file. By now, you should be able to write a trivial program to demonstrate the problem. Show the code, and show the console output when you run that code. Plus show the content of the .ini file. I figure there are two ways you could be writing the file, one from within this configobj package, and the other with a text editor. And there's two ways you could be reading the file, with a text editor and with this configobj package. Be explicit, especially because apparently none of us are familiar with the package. DaveA From lists at solderintheveins.co.uk Sun Jun 19 13:36:06 2011 From: lists at solderintheveins.co.uk (Peter Lavelle) Date: Sun, 19 Jun 2011 12:36:06 +0100 Subject: [Tutor] regex woes in finding an ip and GET string In-Reply-To: References: Message-ID: <4DFDDF26.1060307@solderintheveins.co.uk> Looking at the regex you have to match an IP address, I think you would need to put a range limit on each of the four octets you are searching for (as each one would be between 1 and 3 digits long.) For example: r = re.match(r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b",line) has worked for me. I am no expert on regex (it scares me!) I got the example above from: http://www.regular-expressions.info/examples.html Hope my semi-coherent ramblings have been of some help Regards Peter On 19/06/11 12:25, Gerhardus Geldenhuis wrote: > Hi > I am trying to write a small program that will scan my access.conf > file and update iptables to block anyone looking for stuff that they > are not supposed to. > > The code: > #!/usr/bin/python > import sys > import re > > def extractoffendingip(filename): > f = open(filename,'r') > filecontents = f.read() > #193.6.135.21 - - [11/Jun/2011:13:58:01 +0000] "GET > /admin/pma/scripts/setup.php HTTP/1.1" 404 304 "-" "Mozilla/4.0 > (compatible; MSIE 6.0; Windows 98)" > tuples = re.findall(r'^(\d+\.\d+\.\d+\.\d+).*\"GET(.*)HTTP', > filecontents) > iplist = [] > for items in tuples: > (ip, getstring) = items > print ip,getstring > #print item > if ip not in iplist: > iplist.append(ip) > for item in iplist: > print item > #ipmatch = re.search(r'', filecontents) > > def main(): > extractoffendingip('access_log.1') > > if __name__ == '__main__': > main() > > logfile=http://pastebin.com/F3RXDYBW > > > I could probably have used ranges to be more correct about finding > ip's but I thought that apache should take care of that. I am assuming > a level or integrity in the log file with regards to data... > > The first problem I ran into was that I added a ^ to my search string: > re.findall(r'^(\d+\.\d+\.\d+\.\d+).*\"GET(.*)HTTP', filecontents) > > but that finds only two results a lot less than I am expecting. I am a > little bit confused, first I thought that it might be because the > string I am searching is now only one line because of the method of > loading and the ^ should only find one instance but instead it finds two? > > So removing the ^ works much better but now I get mostly correct > results but I also get a number of ip's with an empty get string, only > thought there should be only one in the log file. I would really > appreciate any pointers as to what is going on here. > > Regards > > -- > Gerhardus Geldenhuis > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- LinkedIn Profile: http://linkedin.com/in/pmjlavelle Twitter: http://twitter.com/pmjlavelle -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Sun Jun 19 14:13:32 2011 From: davea at ieee.org (Dave Angel) Date: Sun, 19 Jun 2011 08:13:32 -0400 Subject: [Tutor] BF Program hangs In-Reply-To: <20110618200235.42810@gmx.com> References: <20110618200235.42810@gmx.com> Message-ID: <4DFDE7EC.9040508@ieee.org> On 01/-10/-28163 02:59 PM, Kaustubh Pratap chand wrote: > Hello i made this program which interprets brainf*** > > But i don't understand why it doesn't ends....and also it doesn't print anything > > import sys > > cell=[0] * 30000 > code_pointer=0 > cell_pointer=0 > close_brace_pos=0 > open_brace_pos=0 > > bf=raw_input("Input bf program:") > > while (code_pointer > c=bf[code_pointer] Indentation error. Presumably a flaw in your email program. Try using text mode. > > if c=='.': > sys.stdout.write(cell[cell_pointer]) > code_pointer+=1 write() doesn't take an integer parameter, but only character strings. If you want to be true to the original language, you'll need a chr() function there. But if I were you, I'd be debugging this by making it print something more verbose, in case the problem is invisible characters. > > elif c==',': > cell[cell_pointer]=sys.stdin.read(1); > code_pointer+=1 This one's a bit tougher, since I don't know any portable way to get a single character of input from a user. In any case, you'll be wanting to use ord() to convert (one of) user's character to an integer. > > elif c=='>': > cell_pointer+=1 > code_pointer+=1 > In any case, I'd make two other changes till you get it working: 1) make the input explicit, so people can know what you're testing this with. After all, if someone were to run it and just press enter, then of course it would print nothing. 2) add a print statement of some sort to the loop, so you can see how the pointers are doing. DaveA From ajarncolin at gmail.com Sun Jun 19 15:23:25 2011 From: ajarncolin at gmail.com (col speed) Date: Sun, 19 Jun 2011 20:23:25 +0700 Subject: [Tutor] Closing triple quotation marks. In-Reply-To: <201106190846.03109.lisi.reisz@gmail.com> References: <201106181252.13897.lisi.reisz@gmail.com> <201106190747.34339.lisi.reisz@gmail.com> <201106190846.03109.lisi.reisz@gmail.com> Message-ID: On 19 June 2011 14:46, Lisi wrote: > On Sunday 19 June 2011 08:39:43 Alan Gauld wrote: > > "Lisi" wrote > > > > > It does indeed. Thank you, both of you. I have clearly not got the > > > terms > > > command, method, function (and feature?) clearly sorted out in my > > > mind, so > > > that is obviously where I need to go. I am supposed to be > > > researching > > > import, but I have not yet succeeded in seeing why it is a problem. > > > So I'll > > > switch to looking up method, function etc. > > > > Add "callable" to your list of search terms. > > Python has the concept of "callable objects" and > > you can call a callable by using parentheses. > > You can also test whether an object is callable > > or not: > > > > for obj in list_of_objects: > > if callable(obj): > > print obj() # call obj first > > else: > > print obj # just use the obj value > > > > HTH, > > Thank you! > > Lisi > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > A good way to learn is making mistakes(in language it's the *only* way). I don't think I will mistake variable_name with "variable_name" in the near future! I downloaded a text file of prime numbers - lots of them. Being clever(!), I knew they were strs and I had to convert them to ints, so: 1. I put them all in memory - first mistake, but not fatal 2. I, very cleverly(I thought) used a list comprehension to convert them to ints - OK 3. I did something like: for prime in tooManyPrimes: f.write("prime") I did this with about 6 files! -- -------------- next part -------------- An HTML attachment was scrubbed... URL: From lisi.reisz at gmail.com Sun Jun 19 15:31:44 2011 From: lisi.reisz at gmail.com (Lisi) Date: Sun, 19 Jun 2011 14:31:44 +0100 Subject: [Tutor] Closing triple quotation marks. In-Reply-To: References: <201106181252.13897.lisi.reisz@gmail.com> <201106190846.03109.lisi.reisz@gmail.com> Message-ID: <201106191431.44422.lisi.reisz@gmail.com> On Sunday 19 June 2011 14:23:25 col speed wrote: > On 19 June 2011 14:46, Lisi wrote: > > On Sunday 19 June 2011 08:39:43 Alan Gauld wrote: > > > "Lisi" wrote > > > > > > > It does indeed. Thank you, both of you. I have clearly not got the > > > > terms > > > > command, method, function (and feature?) clearly sorted out in my > > > > mind, so > > > > that is obviously where I need to go. I am supposed to be > > > > researching > > > > import, but I have not yet succeeded in seeing why it is a problem. > > > > So I'll > > > > switch to looking up method, function etc. > > > > > > Add "callable" to your list of search terms. > > > Python has the concept of "callable objects" and > > > you can call a callable by using parentheses. > > > You can also test whether an object is callable > > > or not: > > > > > > for obj in list_of_objects: > > > if callable(obj): > > > print obj() # call obj first > > > else: > > > print obj # just use the obj value > > > > > > HTH, > > > > Thank you! > > > > Lisi > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > A good way to learn is making mistakes(in language it's the *only* way). I > don't think I will mistake variable_name with "variable_name" in the near > future! > I downloaded a text file of prime numbers - lots of them. Being clever(!), > I knew they were strs and I had to convert them to ints, so: > 1. I put them all in memory - first mistake, but not fatal > 2. I, very cleverly(I thought) used a list comprehension to convert them to > ints - OK > 3. I did something like: > for prime in tooManyPrimes: > f.write("prime") > > I did this with about 6 files! !! ;-) Thank you for the marvellous mental image! Prime numbers will never be the same again. Lisi From sulinet at postafiok.hu Sun Jun 19 15:43:40 2011 From: sulinet at postafiok.hu (=?ISO-8859-1?Q?V=E1las_P=E9ter?=) Date: Sun, 19 Jun 2011 15:43:40 +0200 Subject: [Tutor] regex woes in finding an ip and GET string In-Reply-To: References: Message-ID: 2011/6/19 Gerhardus Geldenhuis > f = open(filename,'r') > filecontents = f.read() > Try f.read().splitlines() instead. > tuples = re.findall(r'^(\d+\.\d+\.\d+\.\d+).*\"GET(.*)HTTP', > filecontents) > This searches the beginning of the lines, but you downloaded the whole page as one string. Another hint is to open it in an editor and investigate it by your eyes, where are the strings you look for. :-) P?ter -------------- next part -------------- An HTML attachment was scrubbed... URL: From sulinet at postafiok.hu Sun Jun 19 16:10:51 2011 From: sulinet at postafiok.hu (=?ISO-8859-1?Q?V=E1las_P=E9ter?=) Date: Sun, 19 Jun 2011 16:10:51 +0200 Subject: [Tutor] nitinchandra rubbish on list Message-ID: Each time I send a message to this list, I get an autoreply like this. No, I won't add myself to any stupid guestlists to use a public list. Could a list moderator please show this user the exit? ---------- Tov?bb?tott lev?l ---------- Felad?: D?tum: 2011. j?nius 19. 15:45 T?rgy: Re: Re: [Tutor] regex woes in finding an ip and GET string (Action Required)Hello =?ISO-8859-1?Q?V=E1las_P=E9ter?=, Your message about "Re: [Tutor] regex woes in finding an ip and GET string" was waitlisted. Please add yourself to my Guest List so your messages will be delivered to my Inbox. Use the link below. Click here to deliver your message Thank you, nitinchandra1 at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sun Jun 19 17:26:42 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 20 Jun 2011 01:26:42 +1000 Subject: [Tutor] nitinchandra rubbish on list In-Reply-To: References: Message-ID: <4DFE1532.5050904@pearwood.info> V?las P?ter wrote: > Each time I send a message to this list, I get an autoreply like this. No, I > won't add myself to any stupid guestlists to use a public list. Could a list > moderator please show this user the exit? I've been sending many lists to this list, and haven't received any such autoreplies. I suspect that you are getting them because you are replying directly to the sender, and CC'ing the list. Stop replying to the sender, and the problem will probably go away. -- Steven From alexandre.conrad at gmail.com Sun Jun 19 17:33:27 2011 From: alexandre.conrad at gmail.com (Alexandre Conrad) Date: Sun, 19 Jun 2011 08:33:27 -0700 Subject: [Tutor] nitinchandra rubbish on list In-Reply-To: <4DFE1532.5050904@pearwood.info> References: <4DFE1532.5050904@pearwood.info> Message-ID: 2011/6/19 Steven D'Aprano : > I've been sending many lists to this list, and haven't received any such > autoreplies. I suspect that you are getting them because you are replying > directly to the sender, and CC'ing the list. > > Stop replying to the sender, and the problem will probably go away. I always "reply to all", which replies to the sender and CC the list (just like this email) and I can't recall of such behavior. All works fine with me. -- Alex | twitter.com/alexconrad From swiftone at swiftone.org Sun Jun 19 17:44:10 2011 From: swiftone at swiftone.org (Brett Ritter) Date: Sun, 19 Jun 2011 11:44:10 -0400 Subject: [Tutor] nitinchandra rubbish on list In-Reply-To: References: <4DFE1532.5050904@pearwood.info> Message-ID: On Sun, Jun 19, 2011 at 11:33 AM, Alexandre Conrad wrote: > 2011/6/19 Steven D'Aprano : >> Stop replying to the sender, and the problem will probably go away. > I always "reply to all", which replies to the sender and CC the list > (just like this email) and I can't recall of such behavior. All works > fine with me. I've had this as well, and as Steven says, it only occurs with a partiuclar recipient. If you send to the list only (or in fact anyone other than that person), you'll not receive this. -- Brett Ritter / SwiftOne swiftone at swiftone.org From ajarncolin at gmail.com Sun Jun 19 17:18:53 2011 From: ajarncolin at gmail.com (col speed) Date: Sun, 19 Jun 2011 22:18:53 +0700 Subject: [Tutor] nitinchandra rubbish on list In-Reply-To: References: Message-ID: 2011/6/19 V?las P?ter > Each time I send a message to this list, I get an autoreply like this. No, > I won't add myself to any stupid guestlists to use a public list. Could a > list moderator please show this user the exit? > > ---------- Tov?bb?tott lev?l ---------- > Felad?: > D?tum: 2011. j?nius 19. 15:45 > T?rgy: Re: Re: [Tutor] regex woes in finding an ip and GET string (Action > Required)Hello =?ISO-8859-1?Q?V=E1las_P=E9ter?=, > > Your message about "Re: [Tutor] regex woes in finding an ip and GET string" > was waitlisted. > > Please add yourself to my Guest List so your messages will be delivered to > my Inbox. Use the link below. > > Click here to deliver your message > > > Thank you, > nitinchandra1 at gmail.com > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Some people have "waitlists", some don't. The same thing happened to me, > and I decided to click. Click and your message gets sent, don't click and it > doesn't. I've heard of repetetetetetetive something syndrome, but I don't > think 1 click will disable you for life. -- -------------- next part -------------- An HTML attachment was scrubbed... URL: From lisi.reisz at gmail.com Sun Jun 19 18:01:26 2011 From: lisi.reisz at gmail.com (Lisi) Date: Sun, 19 Jun 2011 17:01:26 +0100 Subject: [Tutor] nitinchandra rubbish on list In-Reply-To: References: Message-ID: <201106191701.26602.lisi.reisz@gmail.com> On Sunday 19 June 2011 15:10:51 V?las P?ter wrote: > Each time I send a message to this list, I get an autoreply like this. No, > I won't add myself to any stupid guestlists to use a public list. Could a > list moderator please show this user the exit? The solution is simple. Never reply to emails from this particular person. (I can quite understand your not wanting to add yourself to any list.) Lisi From alexandre.conrad at gmail.com Sun Jun 19 18:01:14 2011 From: alexandre.conrad at gmail.com (Alexandre Conrad) Date: Sun, 19 Jun 2011 09:01:14 -0700 Subject: [Tutor] nitinchandra rubbish on list In-Reply-To: References: <4DFE1532.5050904@pearwood.info> Message-ID: 2011/6/19 Alexandre Conrad : > 2011/6/19 Steven D'Aprano : >> I've been sending many lists to this list, and haven't received any such >> autoreplies. I suspect that you are getting them because you are replying >> directly to the sender, and CC'ing the list. >> >> Stop replying to the sender, and the problem will probably go away. > > I always "reply to all", which replies to the sender and CC the list > (just like this email) and I can't recall of such behavior. All works > fine with me. Ok, I just received the email after sending this one, haha. I guess I haven't posted on this list for about 2 or 3 weeks, I am surprised this is happening now. (setting the tutor list as the main recipient now) -- Alex | twitter.com/alexconrad From alan.gauld at btinternet.com Sun Jun 19 18:03:27 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 19 Jun 2011 17:03:27 +0100 Subject: [Tutor] nitinchandra rubbish on list References: Message-ID: "V?las P?ter" wrote > Each time I send a message to this list, I get an autoreply like > this. > No, I won't add myself to any stupid guestlists to use a public > list. > Could a list moderator please show this user the exit? The exit instructions are on the end of every email. But this is not coming frrom the Python tutor list but from boxbe.com - whoever they are? You need to address your concerns to them. Alan G. ---------- Tov?bb?tott lev?l ---------- Felad?: D?tum: 2011. j?nius 19. 15:45 T?rgy: Re: Re: [Tutor] regex woes in finding an ip and GET string (Action Required)Hello =?ISO-8859-1?Q?V=E1las_P=E9ter?=, Your message about "Re: [Tutor] regex woes in finding an ip and GET string" was waitlisted. Please add yourself to my Guest List so your messages will be delivered to my Inbox. Use the link below. Click here to deliver your message Thank you, nitinchandra1 at gmail.com -------------------------------------------------------------------------------- > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From sulinet at postafiok.hu Sun Jun 19 18:55:46 2011 From: sulinet at postafiok.hu (=?ISO-8859-1?Q?V=E1las_P=E9ter?=) Date: Sun, 19 Jun 2011 18:55:46 +0200 Subject: [Tutor] nitinchandra rubbish on list In-Reply-To: References: Message-ID: No, this does not happen if I write to a particular person; this very mail in the beginning of the thread was sent to the tutor list only, and I got the same answer. I am going to get it now again. 2011/6/19 Alan Gauld > > But this is not coming frrom the Python tutor list > but from boxbe.com - whoever they are? > You need to address your concerns to them. > This comes from a subscriber of this list, who may redirect their letters from gmail to boxbe or whatever. I got these letters in connection with using this list. However, I marked them as spam, and if this will not be enough, and you don't concern forcing some basic and widely accepted rules on the list, I will set the list to nomail instead of making further dull complaints, and set it back only if I have questions myself (which would unfortunately prevent me of helping others, what I would be sorry for, because questions are sometimes interesting). P. -------------- next part -------------- An HTML attachment was scrubbed... URL: From delegbede at dudupay.com Sun Jun 19 20:18:52 2011 From: delegbede at dudupay.com (delegbede at dudupay.com) Date: Sun, 19 Jun 2011 18:18:52 +0000 Subject: [Tutor] nitinchandra rubbish on list In-Reply-To: References: Message-ID: <1544134312-1308507534-cardhu_decombobulator_blackberry.rim.net-1740664552-@b28.c12.bise7.blackberry> The problem with boxbe is a nightmare for everybody. It is a mail application by a company that gets into the ways of people ones the receiver of your mail has boxbe running on his system. Sadly my yahoomail has boxbe but that's not my mail on this list. The most annoying part is that you can't even unsubscribe. While I understand how annoying that is, may I appeal you don't withdraw your contributions to this list as a result of that. Thank you. Sent from my BlackBerry wireless device from MTN -----Original Message----- From: V?las P?ter Sender: tutor-bounces+delegbede=dudupay.com at python.org Date: Sun, 19 Jun 2011 18:55:46 To: Python Tutors Subject: Re: [Tutor] nitinchandra rubbish on list _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From nitinchandra1 at gmail.com Sun Jun 19 20:22:07 2011 From: nitinchandra1 at gmail.com (nitin chandra) Date: Sun, 19 Jun 2011 23:52:07 +0530 Subject: [Tutor] nitinchandra rubbish on list Message-ID: Hello All, MY Sincerest APOLOGIES.... i had joined a a mail box management services... But unfortunately It started interfering with my Gmail mail box. But i was completely unaware that It was also effecting the others on the list. Most embarrassing moment when I found out how it was effecting others on the list. I have now ... as of this moment / mail ...rectified the issue. Please do let me know if it still persists. IT Should not ...though. Sorry once again the list. Reg Nitin Chandra From nitinchandra1 at gmail.com Sun Jun 19 20:23:24 2011 From: nitinchandra1 at gmail.com (nitin chandra) Date: Sun, 19 Jun 2011 23:53:24 +0530 Subject: [Tutor] SORRY - nitinchandra rubbish on list Message-ID: On Sun, Jun 19, 2011 at 11:52 PM, nitin chandra wrote: > Hello All, > > MY Sincerest APOLOGIES.... i had joined a a mail box management services... > But unfortunately It started interfering with my Gmail mail box. > > But i was completely unaware that It was also effecting the others on the list. > > Most embarrassing moment when I found out how it was effecting others > on the list. > > I have now ... as of this moment / mail ...rectified the issue. > > Please do let me know if it still persists. IT Should not ?...though. > > Sorry once again the list. > > Reg > > Nitin Chandra > From cbc at unc.edu Sun Jun 19 19:47:48 2011 From: cbc at unc.edu (Chris Calloway) Date: Sun, 19 Jun 2011 13:47:48 -0400 Subject: [Tutor] Seattle PyCamp 2011 In-Reply-To: References: <4DFBE769.7000701@unc.edu> <4DFBFC26.3030104@pearwood.info> Message-ID: <4DFE3644.7010101@unc.edu> On 6/17/2011 11:03 PM, Noah Hall wrote: > On Sat, Jun 18, 2011 at 2:15 AM, Steven D'Aprano wrote: >> Noah Hall wrote: >> >>> Just a note, but are these questions jokes? >>> >>>> Know how to use a text editor (not a word processor, but a text editor)? >>>> Know how to use a browser to download a file? >>>> Know how to run a program installer? >>> >>> If not, then I'd consider removing them. This isn't 1984. >> >> I think the questions are fine. It indicates the level of technical >> knowledge required -- not much, but more than just the ability to sign in to >> AOL. >> >> In 1984 the newbies didn't know anything about computers *and knew they >> didn't know*, but now you have people who think that because they can write >> a letter in Microsoft Office and save as HTML, they're expert at >> programming. >> >> I wish I were joking but I've had to work for some of them. > > That's true, I suppose, but in that case the rest of the questions are > out of place. > > I believe that someone who knows what environmental variables are and > how to change them is a huge step up from someone who knows how to > *download things*. > Mr. Hall, I've taught Python to over a thousand students. And these questions, which are on the PyCamp site and not in the previous email to this list, are not only not the slightest bit out of place or jokes, but rather necessary. We didn't start out asking these questions of prospective students. They were developed from experience. As far as 1984, plenty of people in 1984 knew what environment variables were and how to change them without knowing how to use a browser to download anything. :) What is a "step up" is a matter of perspective. We get not a lot but plenty enough people coming to PyCamp whose last experience with using a computer was 1984. It's simple courtesy to warn those people of what to expect. Thank you for your concern. -- 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 enalicho at gmail.com Sun Jun 19 21:40:59 2011 From: enalicho at gmail.com (Noah Hall) Date: Sun, 19 Jun 2011 20:40:59 +0100 Subject: [Tutor] Seattle PyCamp 2011 In-Reply-To: <4DFE3644.7010101@unc.edu> References: <4DFBE769.7000701@unc.edu> <4DFBFC26.3030104@pearwood.info> <4DFE3644.7010101@unc.edu> Message-ID: On Sun, Jun 19, 2011 at 6:47 PM, Chris Calloway wrote: > On 6/17/2011 11:03 PM, Noah Hall wrote: >> >> On Sat, Jun 18, 2011 at 2:15 AM, Steven D'Aprano >> ?wrote: >>> >>> Noah Hall wrote: >>> >>>> Just a note, but are these questions jokes? >>>> >>>>> Know how to use a text editor (not a word processor, but a text >>>>> editor)? >>>>> Know how to use a browser to download a file? >>>>> Know how to run a program installer? >>>> >>>> If not, then I'd consider removing them. This isn't 1984. >>> >>> I think the questions are fine. It indicates the level of technical >>> knowledge required -- not much, but more than just the ability to sign in >>> to >>> AOL. >>> >>> In 1984 the newbies didn't know anything about computers *and knew they >>> didn't know*, but now you have people who think that because they can >>> write >>> a letter in Microsoft Office and save as HTML, they're expert at >>> programming. >>> >>> I wish I were joking but I've had to work for some of them. >> >> That's true, I suppose, but in that case the rest of the questions are >> out of place. >> >> I believe that someone who knows what environmental variables are and >> how to change them is a huge step up from someone who knows how to >> *download things*. >> > > Mr. Hall, > > I've taught Python to over a thousand students. And these questions, which > are on the PyCamp site and not in the previous email to this list, are not > only not the slightest bit out of place or jokes, but rather necessary. We > didn't start out asking these questions of prospective students. They were > developed from experience. > > As far as 1984, plenty of people in 1984 knew what environment variables > were and how to change them without knowing how to use a browser to download > anything. :) What is a "step up" is a matter of perspective. We get not a > lot but plenty enough people coming to PyCamp whose last experience with > using a computer was 1984. It's simple courtesy to warn those people of what > to expect. > > Thank you for your concern. 1984 was not to be taken literally, of course. ;) Well, if you decide that in this day and age that asking whether someone knows how to use a browser to download files, or if someone knows how to install a program, then that's entirely up to you. I am merely in disbelief that you could find someone these days interested enough in computers to learn Python, and yet not know how to download a file. Had they been in jest, I would have understood, you know, something along the lines of "Want to learn Python? Well, there's only one thing you need to know - how to read!". But when taking it in seriousness, I must congratulate you on somehow finding these people; I had no idea they still existed. ;) Regards, Noah. From sulinet at postafiok.hu Sun Jun 19 21:49:24 2011 From: sulinet at postafiok.hu (=?ISO-8859-1?Q?V=E1las_P=E9ter?=) Date: Sun, 19 Jun 2011 21:49:24 +0200 Subject: [Tutor] nitinchandra rubbish on list In-Reply-To: References: Message-ID: 2011/6/19 nitin chandra > > MY Sincerest APOLOGIES.... All right, I accept, and let's see what happens now. :-) P. -------------- next part -------------- An HTML attachment was scrubbed... URL: From enalicho at gmail.com Sun Jun 19 21:53:47 2011 From: enalicho at gmail.com (Noah Hall) Date: Sun, 19 Jun 2011 20:53:47 +0100 Subject: [Tutor] Seattle PyCamp 2011 In-Reply-To: References: <4DFBE769.7000701@unc.edu> <4DFBFC26.3030104@pearwood.info> <4DFE3644.7010101@unc.edu> Message-ID: > 1984 was not to be taken literally, of course. ;) > > > Well, if you decide that in this day and age that asking whether > someone knows how to use a browser to download files, or if someone > knows how to install a program, then that's entirely up to you. I am > merely in disbelief that you could find someone these days interested > enough in computers to learn Python, and yet not know how to download > a file. Had they been in jest, I would have understood, you know, > something along the lines of "Want to learn Python? Well, there's only > one thing you need to know - how to read!". But when taking it in > seriousness, I must congratulate you on somehow finding these people; > I had no idea they still existed. ;) > > Regards, > Noah. I also realised how aggressive my first reply was, for which I'm sorry, I was merely trying to point out that perhaps they were out of date questions. From lisi.reisz at gmail.com Sun Jun 19 23:10:39 2011 From: lisi.reisz at gmail.com (Lisi) Date: Sun, 19 Jun 2011 22:10:39 +0100 Subject: [Tutor] line continuation characters Message-ID: <201106192210.40006.lisi.reisz@gmail.com> I am having problems with line continuation characters. Error message: SyntaxError: unexpected character after line continuation character I have succeeded in moving the position of the complaint, but am currently well and truly stuck. I have read up about it and now (I hope!) know what to do about it in general, but at one particular point everywhere seems to be wrong. Is there any way I can make these wretched continuation characters visible, so that I know where and what I am up against? Lisi From sulinet at postafiok.hu Sun Jun 19 23:34:45 2011 From: sulinet at postafiok.hu (=?ISO-8859-1?Q?V=E1las_P=E9ter?=) Date: Sun, 19 Jun 2011 23:34:45 +0200 Subject: [Tutor] line continuation characters In-Reply-To: <201106192210.40006.lisi.reisz@gmail.com> References: <201106192210.40006.lisi.reisz@gmail.com> Message-ID: 2011/6/19 Lisi > I am having problems with line continuation characters. Error message: > > SyntaxError: unexpected character after line continuation character > You should write here the line where the problem is. Likely that you have written something after \. If you place a \ at the end of line to continue it on the next line, there must not be anything after it, neither a comment. P?ter -------------- next part -------------- An HTML attachment was scrubbed... URL: From cbc at unc.edu Mon Jun 20 00:26:45 2011 From: cbc at unc.edu (Chris Calloway) Date: Sun, 19 Jun 2011 18:26:45 -0400 Subject: [Tutor] Seattle PyCamp 2011 In-Reply-To: References: <4DFBE769.7000701@unc.edu> <4DFBFC26.3030104@pearwood.info> <4DFE3644.7010101@unc.edu> Message-ID: <4DFE77A5.5040404@unc.edu> On 6/19/2011 3:53 PM, Noah Hall wrote: >> 1984 was not to be taken literally, of course. ;) >> >> >> Well, if you decide that in this day and age that asking whether >> someone knows how to use a browser to download files, or if someone >> knows how to install a program, then that's entirely up to you. I am >> merely in disbelief that you could find someone these days interested >> enough in computers to learn Python, and yet not know how to download >> a file. Had they been in jest, I would have understood, you know, >> something along the lines of "Want to learn Python? Well, there's only >> one thing you need to know - how to read!". But when taking it in >> seriousness, I must congratulate you on somehow finding these people; >> I had no idea they still existed. ;) >> >> Regards, >> Noah. > > I also realised how aggressive my first reply was, for which I'm > sorry, I was merely trying to point out that perhaps they were out of > date questions. Mr. Hall, It's not really entirely up to me, no. There are many people in several user groups behind these questions. And the questions have evolved over time to be perfectly up to date, yes. The first few PyCamps attempted to qualify participants by simply stating the syllabus. The casual observer might think that would be enough. But no, that is not the case in reality when you get experience from teaching many classes of any kind. From those first few camps there were outlier participants who either thought PyCamp was too easy or too hard and who demanded more information be placed on the PyCamp page about what qualifications are required. With each successive PyCamp, those qualifications were adjusted according to participant feedback until the suggested prerequisites are what they are now. I'm sure they will continue to evolve even more in the future. No, it isn't enough to only need to know how to read to come to PyCamp. There are many ways to learn Python which might entail only knowing how to read or learning to use a computer at the same time. But PyCamp is one week and we don't teach people how to use a computer during that week. Whatever your disbelief, I can assure you in this day and age if it is not explicitly stated up front that you need to know how to download a file and run a program installer before coming to PyCamp, then there will be people who will be upset when lack of those skills hinders them in class and when class doesn't pause to teach them those skills. And I can assure you those people are common enough to find, no congratulations necessary, especially when offering a week long training at the low PyCamp price point. You may not mean 1984. But PyCamp and any computer-based open training for that matter has to account for people from 1984. Python doesn't appeal only to computer nerds. Python has many domain-specific uses from geography to biology. When you have large numbers of people coming from such disparate backgrounds, you find that computer illiteracy is quite high in the general population, even among the educated, even among people who Facebook, or even among people from 2011. :) I accept your apology and yes, I was taken aback by the hostility of your replies in a public forum. However, in the interest of providing information about PyCamp and in the interest of what it takes to tutor Python, I hope this explains some things. -- 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 alan.gauld at btinternet.com Mon Jun 20 00:50:50 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 19 Jun 2011 23:50:50 +0100 Subject: [Tutor] Seattle PyCamp 2011 References: <4DFBE769.7000701@unc.edu><4DFBFC26.3030104@pearwood.info><4DFE3644.7010101@unc.edu> Message-ID: "Noah Hall" wrote > Well, if you decide that in this day and age that asking whether > someone knows how to use a browser to download files, > or if someone knows how to install a program, This is not out of place. I have experienced it myself with users of my web tutorial. I have had several - not a lot, maybe a dozen out of the half million visitors - but a few, who could not follow the instructions to download python and install it. I have had to walk them through the process step by step by email. In at least one case it was the first time they had ever installed anything from tyhe web, they had always used install CDs up till then. > in disbelief that you could find someone these days > interested enough in computers to learn Python, and > yet not know how to download a file. Nope, it happens, I can promise you. The last such case I had was late last year. I have also had users who didn't know how to use the File->SaveAs menu in Notepad to change a filename from foo.txt (the default) to foo.py... As my old boss used to say: "Its impossible to underestimate your users abilities" -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Mon Jun 20 01:03:47 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 20 Jun 2011 09:03:47 +1000 Subject: [Tutor] line continuation characters In-Reply-To: <201106192210.40006.lisi.reisz@gmail.com> References: <201106192210.40006.lisi.reisz@gmail.com> Message-ID: <4DFE8053.2090907@pearwood.info> Lisi wrote: > I am having problems with line continuation characters. Error message: > > SyntaxError: unexpected character after line continuation character Then delete it ;) Seriously. You have your editor open, right? Go to the line where the error is reported. It will look something like this: blah blah blah \ Press the End key. Your editor's blinking insertion point or cursor will go to the end of the line: blah blah blah \ | Backspace until the cursor is *immediately* next to the backslash, with no other characters INCLUDING SPACES after it. Which editor are you using? If it is kwrite or kate, it has a setting to control whether spaces are left at the end of lines, e.g. in kwrite: Settings > Configure Editor > Editing > Remove trailing spaces > I have succeeded in moving the position of the complaint, but am currently > well and truly stuck. > > I have read up about it and now (I hope!) know what to do about it in general, > but at one particular point everywhere seems to be wrong. Is there any way I > can make these wretched continuation characters visible, so that I know where > and what I am up against? Continuation characters are visible. It is a backslash at the very end of the line. It must not be followed by *anything* -- no comments, no spaces, nothing. >>> x = 23 + \ File "", line 1 x = 23 + \ ^ SyntaxError: unexpected character after line continuation character If this error message is not clear, would you like to suggest an improvement? -- Steven From steve at pearwood.info Mon Jun 20 01:47:08 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 20 Jun 2011 09:47:08 +1000 Subject: [Tutor] nitinchandra rubbish on list In-Reply-To: References: Message-ID: <4DFE8A7C.2090400@pearwood.info> nitin chandra wrote: > Hello All, > > MY Sincerest APOLOGIES.... i had joined a a mail box management services... > But unfortunately It started interfering with my Gmail mail box. Thanks for fixing this! -- Steven From nitinchandra1 at gmail.com Mon Jun 20 08:31:10 2011 From: nitinchandra1 at gmail.com (nitin chandra) Date: Mon, 20 Jun 2011 12:01:10 +0530 Subject: [Tutor] nitinchandra rubbish on list In-Reply-To: <4DFE8A7C.2090400@pearwood.info> References: <4DFE8A7C.2090400@pearwood.info> Message-ID: Thank you. Nitin On Mon, Jun 20, 2011 at 5:17 AM, Steven D'Aprano wrote: > nitin chandra wrote: >> >> Hello All, >> >> MY Sincerest APOLOGIES.... i had joined a a mail box management >> services... >> But unfortunately It started interfering with my Gmail mail box. > > Thanks for fixing this! > > > > -- > Steven > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From lisi.reisz at gmail.com Mon Jun 20 09:19:07 2011 From: lisi.reisz at gmail.com (Lisi) Date: Mon, 20 Jun 2011 08:19:07 +0100 Subject: [Tutor] line continuation characters In-Reply-To: <4DFE8053.2090907@pearwood.info> References: <201106192210.40006.lisi.reisz@gmail.com> <4DFE8053.2090907@pearwood.info> Message-ID: <201106200819.07317.lisi.reisz@gmail.com> On Monday 20 June 2011 00:03:47 Steven D'Aprano wrote: > Lisi wrote: > > I am having problems with line continuation characters. Error message: > > > > SyntaxError: unexpected character after line continuation character > > Then delete it ;) > > Seriously. You have your editor open, right? Go to the line where the > error is reported. It will look something like this: > > blah blah blah \ > > Press the End key. Your editor's blinking insertion point or cursor will > go to the end of the line: > > blah blah blah \ | > > Backspace until the cursor is *immediately* next to the backslash, with > no other characters INCLUDING SPACES after it. > > Which editor are you using? If it is kwrite or kate, it has a setting to > control whether spaces are left at the end of lines, e.g. in kwrite: > > Settings > Configure Editor > Editing > Remove trailing spaces > > > I have succeeded in moving the position of the complaint, but am > > currently well and truly stuck. > > > > I have read up about it and now (I hope!) know what to do about it in > > general, but at one particular point everywhere seems to be wrong. Is > > there any way I can make these wretched continuation characters visible, > > so that I know where and what I am up against? > > Continuation characters are visible. It is a backslash at the very end > of the line. It must not be followed by *anything* -- no comments, no > spaces, nothing. > > >>> x = 23 + \ > > File "", line 1 > x = 23 + \ > ^ > SyntaxError: unexpected character after line continuation character > > > If this error message is not clear, would you like to suggest an > improvement? It is not the error message that is unclear, it was the state of my knowledge. I did not know that \ was a line continuation character, and simply wrote a long line which wrapped. I know how to remove spaces - I just had not got a clue what the message was on about. I found quite a few references to line continuation characters, but nothing that told me what a line continuation character looked like, nor that it must be at the very end of the line. The back-slashes in the script all had other purposes, and I had not realised that where they fell was significant. Thanks for the help. Now to tackle my script. Lisi Lisi From __peter__ at web.de Mon Jun 20 09:58:13 2011 From: __peter__ at web.de (Peter Otten) Date: Mon, 20 Jun 2011 09:58:13 +0200 Subject: [Tutor] regex woes in finding an ip and GET string References: Message-ID: Gerhardus Geldenhuis wrote: > I am trying to write a small program that will scan my access.conf file > and update iptables to block anyone looking for stuff that they are not > supposed to. > > The code: > #!/usr/bin/python > import sys > import re > > def extractoffendingip(filename): > f = open(filename,'r') > filecontents = f.read() > #193.6.135.21 - - [11/Jun/2011:13:58:01 +0000] "GET > /admin/pma/scripts/setup.php HTTP/1.1" 404 304 "-" "Mozilla/4.0 > (compatible; MSIE 6.0; Windows 98)" > tuples = re.findall(r'^(\d+\.\d+\.\d+\.\d+).*\"GET(.*)HTTP', > filecontents) If you want to process the whole file at once you have to use the re.MULTILINE flag for the regex to match the start of a line instead of the start of the whole text: tuples = re.compile(r'...', re.MULTILINE).findall(filecontents) But I think it's better to process the file one line at a time. > iplist = [] [snip] > if ip not in iplist: > iplist.append(ip) So you want every unique ip appear only once in iplist. Python offers an efficient data structure for that, the set. With these changes your funtion becomes something like (untested) def extractoffendingips(filename): match = re.compile(r'^(\d+\.\d+\.\d+\.\d+).*\"GET(.*)HTTP').match ipset = set() with open(filename) as f: for line in f: m = match(line) if m is not None: ip, getstring = m.groups() ipset.add(ip) for item in ipset: print item From alan.gauld at btinternet.com Mon Jun 20 10:06:15 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 20 Jun 2011 09:06:15 +0100 Subject: [Tutor] line continuation characters References: <201106192210.40006.lisi.reisz@gmail.com><4DFE8053.2090907@pearwood.info> <201106200819.07317.lisi.reisz@gmail.com> Message-ID: "Lisi" wrote > It is not the error message that is unclear, it was the state of my > knowledge. > I did not know that \ was a line continuation character, I sympathise. I had been programming for about 5 years before I came across line continuation characters. For me it was while reviewing someone's code, and they used them extensively. > I found quite a few references to line continuation characters, Wikipedia is usually your friend for looking up things like this. In this case it would have told you that the characters used depend on the language and specifically: Backslash as last character of line a.. C and C++ preprocessor b.. Python c.. Ruby > The back-slashes in the script all had other purposes, Which is one reason I try not to use them, because backslashes already have another purpose, they can be confusing. You can usually avoid using them by incorporating parentheses or brackets in the line and breaking before the closing bracket. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From g.nius.ck at gmail.com Mon Jun 20 16:02:28 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Mon, 20 Jun 2011 10:02:28 -0400 Subject: [Tutor] Communicating Between Programs Using Raw Inputs (con'd) In-Reply-To: References: Message-ID: Well, that's a trick me and jake learned in a book to stop the program from changing. On Saturday, June 18, 2011, aditya wrote: > > > On Sat, Jun 18, 2011 at 9:35 PM, Jacob Bender wrote: > > Dear Tutors, > > Alright, I'm using linux (ubuntu) and I took all of your advice and I got something that works and doesn't work at the same time. Here's the source code for my two programs called Lock and Key: > > Lock.py: > > password = "a" > > > psswd_try = raw_input("What's the password? ") > > > if psswd_try == password: > > ??? print "correct!!!" > > ??? raw_input() > > else: > > ??? print "wrong" > > ??? raw_input() > > Why do you need to call raw_input() again? ?You are giving the input only once so remove raw_input() from both if and else , that should do the work > > ?Key.py: > > import sys > > > sys.stdout.write("a") > > In the linux terminal I ran this command(they were both in my home folder, so no directories were needed): > > python Key.py | python Lock.py > > And all went well except for an EOF error caused by the raw_input inside the "if" statement in my Lock program. However I did get it to print "correct", so I know sys.stdout.write() works for what I want it to, but I don't want the EOF error. Here's the output: > > Traceback (most recent call last): > ? File "Lock.py", line 7, in > ??? raw_input() > EOFError: EOF when reading a line > > Please help me get rid of it because I couldn't find a sys.stdout.close() command or any other std command that would help. > > Thanks! > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > > -- > RegardsAditya > From g.nius.ck at gmail.com Mon Jun 20 17:26:36 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Mon, 20 Jun 2011 11:26:36 -0400 Subject: [Tutor] Main Function In-Reply-To: <31873480.post@talk.nabble.com> References: <31873480.post@talk.nabble.com> Message-ID: Looks all good except for this: while guess == the_number: Since you break out at the end, an if statement would be a more logical choice. and also: if tries == 4: print("\nYou fail!") input("\n\nPress the enter key to exit.") break you don't need to break because the condition already requires the tries to be under 4, so you don't need both the break statement and the tries < 4. Something else you could do is instead of # start the program main() input("\n\nPress the enter key to quit.") you could do if __name__ == __main__: # start the program main() input("\n\nPress the enter key to quit.") which means that if its used as a module (say, you want the number chooser thing) it won't run the game also, I liked the print("\nYou fail!") very nice On Fri, Jun 17, 2011 at 11:21 PM, Vincent Balmori wrote: > > I answered another question that says "Modify the guess_number program so > that the program's code is in a function called main(). Don't forget to > call > main() so you can play the game." It seems to be working fine, but I would > like to have a second opinion if there was a better way to put it together. > > # Guess My Number > # > # The computer picks a random number between 1 and 10 > # The player tries to guess it and the computer lets > # the player know if the guess is too high, too low > # or right on the money > > import random > > def display_instruct(): > print("\tWelcome to 'Guess My Number'!") > print("\nI'm thinking of a number between 1 and 10.") > print("Try to guess it in as few attempts as possible.\n") > > # set ask_number function > def ask_number(question, low, high, step = 1): > """Ask for a number within a range.""" > response = None > while response not in range(low, high, step): > response = int(input(question)) > return response > > # guessing loop > def num(): > # set the initial values > the_number = random.randint(1, 10) > tries = 0 > guess = None > while guess != the_number and tries < 4: > guess = ask_number("Take a guess:", 1, 10) > if guess > the_number: > print("Lower...") > else: > print("Higher...") > tries += 1 > > if tries == 4: > print("\nYou fail!") > input("\n\nPress the enter key to exit.") > break > > while guess == the_number: > print("\nYou guessed it! The number was", the_number) > print("And it only took you", tries, "tries!\n") > input("\n\nPress the enter key to exit.") > break > > def main(): > display_instruct() > num() > > # start the program > main() > input("\n\nPress the enter key to quit.") > -- > View this message in context: > http://old.nabble.com/Main-Function-tp31873480p31873480.html > Sent from the Python - tutor mailing list archive at Nabble.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 arunkumar413 at gmail.com Mon Jun 20 17:34:16 2011 From: arunkumar413 at gmail.com (arun kumar) Date: Mon, 20 Jun 2011 21:04:16 +0530 Subject: [Tutor] html files to pdf document Message-ID: HI, i have a some 100 plus html individual files.I want to convert them to a single pdf document programatically. How to convert them in python. Are there any functions,modules or libraries for python to achieve this. -- Thank you Arun Kumar http://clicknscroll.blogspot.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From g.nius.ck at gmail.com Mon Jun 20 18:02:05 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Mon, 20 Jun 2011 12:02:05 -0400 Subject: [Tutor] nitinchandra rubbish on list In-Reply-To: References: <4DFE8A7C.2090400@pearwood.info> Message-ID: wait a minute, I clicked the link but didn't submit my info, does that mean my email will start corrupting the list now? On Mon, Jun 20, 2011 at 2:31 AM, nitin chandra wrote: > Thank you. > > Nitin > > On Mon, Jun 20, 2011 at 5:17 AM, Steven D'Aprano > wrote: > > nitin chandra wrote: > >> > >> Hello All, > >> > >> MY Sincerest APOLOGIES.... i had joined a a mail box management > >> services... > >> But unfortunately It started interfering with my Gmail mail box. > > > > Thanks for fixing this! > > > > > > > > -- > > 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 > -------------- next part -------------- An HTML attachment was scrubbed... URL: From g.nius.ck at gmail.com Mon Jun 20 18:31:32 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Mon, 20 Jun 2011 12:31:32 -0400 Subject: [Tutor] Communicating Between Programs Using Raw Inputs (con'd) In-Reply-To: References: Message-ID: Also, we tried removing the raw input, but it wouldn't print correct On Sat, Jun 18, 2011 at 9:55 PM, aditya wrote: > > > On Sat, Jun 18, 2011 at 9:35 PM, Jacob Bender wrote: > >> Dear Tutors, >> >> Alright, I'm using linux (ubuntu) and I took all of your advice and I got >> something that works and doesn't work at the same time. Here's the source >> code for my two programs called Lock and Key: >> >> *Lock.py: * >> >> password = "a" >> >> psswd_try = raw_input("What's the password? ") >> >> if psswd_try == password: >> print "correct!!!" >> raw_input() >> else: >> print "wrong" >> raw_input() >> * >> * > > Why do you need to call raw_input() again? You are giving the input only > once so remove raw_input() from both if and else , that should do the work > > > >> *Key.py*: >> >> import sys >> >> sys.stdout.write("a") >> >> In the linux terminal I ran this command(they were both in my home folder, >> so no directories were needed): >> >> python Key.py | python Lock.py >> >> And all went well except for an EOF error caused by the raw_input inside >> the "if" statement in my Lock program. However I did get it to print >> "correct", so I know sys.stdout.write() works for what I want it to, but I >> don't want the EOF error. Here's the output: >> >> Traceback (most recent call last): >> File "Lock.py", line 7, in >> raw_input() >> EOFError: EOF when reading a line >> >> Please help me get rid of it because I couldn't find a sys.stdout.close() >> command or any other std command that would help. >> >> Thanks! >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > > > -- > Regards > Aditya > > > _______________________________________________ > 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 timomlists at gmail.com Mon Jun 20 18:58:56 2011 From: timomlists at gmail.com (Timo) Date: Mon, 20 Jun 2011 18:58:56 +0200 Subject: [Tutor] html files to pdf document In-Reply-To: References: Message-ID: <4DFF7C50.3000405@gmail.com> On 20-06-11 17:34, arun kumar wrote: > HI, i have a some 100 plus html individual files.I want to convert > them to a single pdf document programatically. How to convert them in > python. Are there any functions,modules or libraries for python to > achieve this. Just a question, but did you use Google before asking here? Because the first hit when searching for "python html to pdf" looks like it should do what you want. Cheers, Timo > > -- > Thank you > > Arun Kumar > http://clicknscroll.blogspot.com > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From motoom at xs4all.nl Mon Jun 20 19:11:13 2011 From: motoom at xs4all.nl (Michiel Overtoom) Date: Mon, 20 Jun 2011 19:11:13 +0200 Subject: [Tutor] html files to pdf document In-Reply-To: <4DFF7C50.3000405@gmail.com> References: <4DFF7C50.3000405@gmail.com> Message-ID: <00E86B69-6D07-46ED-B4CA-4F740509BB0B@xs4all.nl> On Jun 20, 2011, at 18:58, Timo wrote: > On 20-06-11 17:34, arun kumar wrote: >> HI, i have a some 100 plus html individual files.I want to convert them to a single pdf document programatically. How to convert them in python. Are there any functions,modules or libraries for python to achieve this. > Just a question, but did you use Google before asking here? Because the first hit when searching for "python html to pdf" looks like it should do what you want. Maybe for you, but not for the OP. Google will give different search results depending on your location, nationality, IP address and previous searches from that address. Please post the URL of the first hit you got? Greetings, -- "Freedom: To ask nothing. To expect nothing. To depend on nothing." - Ayn Rand From wprins at gmail.com Tue Jun 21 00:19:52 2011 From: wprins at gmail.com (Walter Prins) Date: Mon, 20 Jun 2011 23:19:52 +0100 Subject: [Tutor] html files to pdf document In-Reply-To: <00E86B69-6D07-46ED-B4CA-4F740509BB0B@xs4all.nl> References: <4DFF7C50.3000405@gmail.com> <00E86B69-6D07-46ED-B4CA-4F740509BB0B@xs4all.nl> Message-ID: Hello, On 20 June 2011 18:11, Michiel Overtoom wrote: > > On Jun 20, 2011, at 18:58, Timo wrote: > > > On 20-06-11 17:34, arun kumar wrote: > >> HI, i have a some 100 plus html individual files.I want to convert them > to a single pdf document programatically. How to convert them in python. > Are there any functions,modules or libraries for python to achieve this. > > > Just a question, but did you use Google before asking here? Because the > first hit when searching for "python html to pdf" looks like it should do > what you want. > > Maybe for you, but not for the OP. Google will give different search > results depending on your location, nationality, IP address and previous > searches from that address. > At the risk of belaboring the point, I think what Timo was gentlying trying to point out to the OP was that Google would've likely yielded many relevant results, including in all likelihood the top hit, notwithstanding Google's tailoring based on location and other factors. (You're not seriously trying to suggest that Google would've yielded *no* useful results, or that the top link wouldn't have been at all relevant to his question, are you?) For reference, for me the top hit is http://www.xhtml2pdf.com/ which does indeed look like it might do the job (and is a pure python solution.) Another possibly quite relevant link is this one (about 20 lines of code): http://www.linux.com/learn/docs/ldp/284676-converting-html-to-pdf-using-python-and-qt Cheers Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From motoom at xs4all.nl Tue Jun 21 00:29:27 2011 From: motoom at xs4all.nl (Michiel Overtoom) Date: Tue, 21 Jun 2011 00:29:27 +0200 Subject: [Tutor] html files to pdf document In-Reply-To: References: <4DFF7C50.3000405@gmail.com> <00E86B69-6D07-46ED-B4CA-4F740509BB0B@xs4all.nl> Message-ID: <994B3638-CD1E-449D-86AE-29A2AF0418A2@xs4all.nl> On Jun 21, 2011, at 00:19, Walter Prins wrote: > For reference, for me the top hit is http://www.xhtml2pdf.com/ which does indeed look like it might do the job (and is a pure python solution.) I get five SERP pages with tons of Stackoverflow hits, but not one for www.xhtml2pdf.com! I think this is what is known as an Internet Search Bubble. > Another possibly quite relevant link is this one (about 20 lines of code): http://www.linux.com/learn/docs/ldp/284676-converting-html-to-pdf-using-python-and-qt Thank you for posting the links. Greetings, -- "If you don't know, the thing to do is not to get scared, but to learn." - Ayn Rand From nauty.me04 at gmail.com Tue Jun 21 07:41:51 2011 From: nauty.me04 at gmail.com (aditya) Date: Tue, 21 Jun 2011 11:11:51 +0530 Subject: [Tutor] Socket Programming issue Message-ID: This is a small client-server program in which i am using a Vbscript program to check for connectivity of 2 machines and write the output to a text file whether it connectes or not , for example the contents of the file *output.txt* are 192.168.1.2 is connected 192.168.1.10 is not connected Now i am trying to send the contents of this file from a client through a socket to a server which is running on my main server .This is basically created to automate the checking of connectivity of the machines. The issue is that although the Vbscript writes the output to the file correctly but when the client sends the contents of the file to the server via socket , it sometimes prints all the lines of the file on the server and sometimes it doesnt , i dont know whether the issue is with the client or the server , Please Help.. CLIENT.PY import socket import os import sys os.system("C:\Python26\ping.vbs") host = "localhost" port= 23333 size = 1024 s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host,port)) f=open('output.txt','r') while 1: data = f.readline() if data: s.send(data) else: break f.close() s.close() SERVER.PY import socket host = "" port = 23333 size = 1024 backlog=5 s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host,port)) s.listen(backlog) while 1: client, addr =s.accept() data=client.recv(size) if data: print data else: print "client exit" s.close() -- Regards Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Jun 21 09:15:55 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 21 Jun 2011 08:15:55 +0100 Subject: [Tutor] Socket Programming issue References: Message-ID: "aditya" wrote > is that although the Vbscript writes the output to the file > correctly but > when the client sends the contents of the file to the server via > socket , it > sometimes prints all the lines of the file on the server and > sometimes it > doesnt , i dont know whether the issue is with the client or the > server , Use the return values from functions. > CLIENT.PY > > import socket > import os > import sys > os.system("C:\Python26\ping.vbs") > host = "localhost" > port= 23333 > size = 1024 > > s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) > s.connect((host,port)) > > f=open('output.txt','r') > while 1: > data = f.readline() You could print the data here to check that you got something meaningful from the file.... > if data: s.send(data) The socket documentation specifically says: --------------------------------- socket.send(string[, flags]) Send data to the socket. The socket must be connected to a remote socket. The optional flags argument has the same meaning as for recv() above. Returns the number of bytes sent. Applications are responsible for checking that all data has been sent; if only some of the data was transmitted, the application needs to attempt delivery of the remaining data. ------------------------------------------ Notice that it tells you how many bytes have been sent, and it is your responsibility to check and retry if necessary. I see no check nor any attempt to retry.... That should tell you if the data is leaving the client at least. > SERVER.PY > import socket > > host = "" > port = 23333 > size = 1024 > backlog=5 > s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > s.bind((host,port)) > s.listen(backlog) > > while 1: > client, addr =s.accept() > data=client.recv(size) > if data: > print data > else: > print "client exit" This implies you should always get something printed, do you? When you say it sometimes prints the lines and sometimes not, does it print the exit message instead? > s.close() I'm not clear where this line sits since the mail has lost its indentation. Is it inside the else or at the while level? Just some things to c0onsider, HTH -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From nauty.me04 at gmail.com Tue Jun 21 09:37:28 2011 From: nauty.me04 at gmail.com (aditya) Date: Tue, 21 Jun 2011 13:07:28 +0530 Subject: [Tutor] Socket Programming issue In-Reply-To: References: Message-ID: On Tue, Jun 21, 2011 at 12:45 PM, Alan Gauld wrote: > > "aditya" wrote > > > is that although the Vbscript writes the output to the file correctly but >> when the client sends the contents of the file to the server via socket , >> it >> sometimes prints all the lines of the file on the server and sometimes it >> doesnt , i dont know whether the issue is with the client or the server , >> > > Use the return values from functions. > > > CLIENT.PY >> >> import socket >> import os >> import sys >> os.system("C:\Python26\ping.**vbs") >> host = "localhost" >> port= 23333 >> size = 1024 >> >> s=socket.socket(socket.AF_**INET, socket.SOCK_STREAM) >> s.connect((host,port)) >> >> f=open('output.txt','r') >> while 1: >> data = f.readline() >> > > You could print the data here to check that you got something > meaningful from the file.... > > > if data: s.send(data) >> > > The socket documentation specifically says: > ------------------------------**--- > socket.send(string[, flags]) > Send data to the socket. The socket must be connected to a remote socket. > The optional flags argument has the same meaning as for recv() above. > Returns the number of bytes sent. Applications are responsible for checking > that all data has been sent; if only some of the data was transmitted, the > application needs to attempt delivery of the remaining data. > > >Thanks Alan i will put in some conditional checks to check and reattempt to send the data if it has not been sent or not. besides i am sending you the client,server, and the output file to just go though it once . You can run the script for yourself and see what happens.It actually prints only one line of the ouput file and some times all the lines at the server end. Besides can you help me with the checks which you insist me to put in socket.send() ? > ------------------------------**------------ > Notice that it tells you how many bytes have been sent, and it > is your responsibility to check and retry if necessary. > I see no check nor any attempt to retry.... > > That should tell you if the data is leaving the client at least. > > > > SERVER.PY >> import socket >> >> host = "" >> port = 23333 >> size = 1024 >> backlog=5 >> s=socket.socket(socket.AF_**INET, socket.SOCK_STREAM) >> >> s.bind((host,port)) >> s.listen(backlog) >> >> while 1: >> client, addr =s.accept() >> data=client.recv(size) >> if data: >> print data >> else: >> print "client exit" >> > > This implies you should always get something printed, do you? > When you say it sometimes prints the lines and sometimes > not, does it print the exit message instead? > > s.close() >> > > I'm not clear where this line sits since the mail has lost > its indentation. Is it inside the else or at the while level? > > Just some things to c0onsider, > > 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 > -- Regards Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- reply from 192.168.100.1 reply from 192.168.100.7 -------------- next part -------------- A non-text attachment was scrubbed... Name: client.py Type: application/octet-stream Size: 346 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: server.py Type: application/octet-stream Size: 304 bytes Desc: not available URL: From arunkumar413 at gmail.com Tue Jun 21 09:56:54 2011 From: arunkumar413 at gmail.com (arun kumar) Date: Tue, 21 Jun 2011 13:26:54 +0530 Subject: [Tutor] Tutor Digest, Vol 88, Issue 83 In-Reply-To: References: Message-ID: On Tue, Jun 21, 2011 at 12:46 PM, 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: html files to pdf document (Timo) > 2. Re: html files to pdf document (Michiel Overtoom) > 3. Re: html files to pdf document (Walter Prins) > 4. Re: html files to pdf document (Michiel Overtoom) > 5. Socket Programming issue (aditya) > 6. Re: Socket Programming issue (Alan Gauld) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Mon, 20 Jun 2011 18:58:56 +0200 > From: Timo > To: tutor at python.org > Subject: Re: [Tutor] html files to pdf document > Message-ID: <4DFF7C50.3000405 at gmail.com> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 20-06-11 17:34, arun kumar wrote: > > HI, i have a some 100 plus html individual files.I want to convert > > them to a single pdf document programatically. How to convert them in > > python. Are there any functions,modules or libraries for python to > > achieve this. > Just a question, but did you use Google before asking here? Because the > first hit when searching for "python html to pdf" looks like it should > do what you want. > Cheers, > Timo > > > > > -- > > Thank you > > > > Arun Kumar > > http://clicknscroll.blogspot.com > > > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > > yes i did a Google search but did find anything useful. The xhtml2pdf is > buggy in i'm unable to install it. Also mailed the community of xhtml2pdf > but didn't receive any reply from them. > Thanks Arun Kumar > ------------------------------ > > Message: 2 > Date: Mon, 20 Jun 2011 19:11:13 +0200 > From: Michiel Overtoom > To: tutor at python.org > Subject: Re: [Tutor] html files to pdf document > Message-ID: <00E86B69-6D07-46ED-B4CA-4F740509BB0B at xs4all.nl> > Content-Type: text/plain; charset=us-ascii > > > On Jun 20, 2011, at 18:58, Timo wrote: > > > On 20-06-11 17:34, arun kumar wrote: > >> HI, i have a some 100 plus html individual files.I want to convert them > to a single pdf document programatically. How to convert them in python. > Are there any functions,modules or libraries for python to achieve this. > > > Just a question, but did you use Google before asking here? Because the > first hit when searching for "python html to pdf" looks like it should do > what you want. > > Maybe for you, but not for the OP. Google will give different search > results depending on your location, nationality, IP address and previous > searches from that address. > > Please post the URL of the first hit you got? > > Greetings, > > -- > "Freedom: To ask nothing. To expect nothing. To depend on nothing." - Ayn > Rand > > > > ------------------------------ > > Message: 3 > Date: Mon, 20 Jun 2011 23:19:52 +0100 > From: Walter Prins > To: tutor at python.org > Subject: Re: [Tutor] html files to pdf document > Message-ID: > Content-Type: text/plain; charset="iso-8859-1" > > Hello, > > On 20 June 2011 18:11, Michiel Overtoom wrote: > > > > > On Jun 20, 2011, at 18:58, Timo wrote: > > > > > On 20-06-11 17:34, arun kumar wrote: > > >> HI, i have a some 100 plus html individual files.I want to convert > them > > to a single pdf document programatically. How to convert them in python. > > Are there any functions,modules or libraries for python to achieve this. > > > > > Just a question, but did you use Google before asking here? Because the > > first hit when searching for "python html to pdf" looks like it should do > > what you want. > > > > Maybe for you, but not for the OP. Google will give different search > > results depending on your location, nationality, IP address and previous > > searches from that address. > > > > At the risk of belaboring the point, I think what Timo was gentlying trying > to point out to the OP was that Google would've likely yielded many > relevant > results, including in all likelihood the top hit, notwithstanding Google's > tailoring based on location and other factors. (You're not seriously > trying > to suggest that Google would've yielded *no* useful results, or that the > top > link wouldn't have been at all relevant to his question, are you?) > > For reference, for me the top hit is http://www.xhtml2pdf.com/ which does > indeed look like it might do the job (and is a pure python solution.) > > Another possibly quite relevant link is this one (about 20 lines of code): > > http://www.linux.com/learn/docs/ldp/284676-converting-html-to-pdf-using-python-and-qt > > Cheers > > Walter > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20110620/3aa076cd/attachment-0001.html > > > > ------------------------------ > > Message: 4 > Date: Tue, 21 Jun 2011 00:29:27 +0200 > From: Michiel Overtoom > To: tutor at python.org > Subject: Re: [Tutor] html files to pdf document > Message-ID: <994B3638-CD1E-449D-86AE-29A2AF0418A2 at xs4all.nl> > Content-Type: text/plain; charset=us-ascii > > > On Jun 21, 2011, at 00:19, Walter Prins wrote: > > > For reference, for me the top hit is http://www.xhtml2pdf.com/ which > does indeed look like it might do the job (and is a pure python solution.) > > I get five SERP pages with tons of Stackoverflow hits, but not one for > www.xhtml2pdf.com! I think this is what is known as an Internet Search > Bubble. > > > > Another possibly quite relevant link is this one (about 20 lines of > code): > http://www.linux.com/learn/docs/ldp/284676-converting-html-to-pdf-using-python-and-qt > > Thank you for posting the links. > > Greetings, > > -- > "If you don't know, the thing to do is not to get scared, but to learn." - > Ayn Rand > > Hi Micheal, > Thanks for the suggestion but my desktop environment is not qt. Its gnome. And i'm looking for some pure python way. www.xhtml2pdf is buggy and i had problems installing that library Thanks Arun Kumar > > > > ------------------------------ > > Message: 5 > Date: Tue, 21 Jun 2011 11:11:51 +0530 > From: aditya > To: tutor at python.org > Subject: [Tutor] Socket Programming issue > Message-ID: > Content-Type: text/plain; charset="iso-8859-1" > > This is a small client-server program in which i am using a Vbscript > program > to check for connectivity of 2 machines and write the output to a text file > whether it connectes or not , > > > for example the contents of the file *output.txt* are > > 192.168.1.2 is connected > 192.168.1.10 is not connected > > > Now i am trying to send the contents of this file from a client through a > socket to a server which is running on my main server .This is basically > created to automate the checking of connectivity of the machines. The issue > is that although the Vbscript writes the output to the file correctly but > when the client sends the contents of the file to the server via socket , > it > sometimes prints all the lines of the file on the server and sometimes it > doesnt , i dont know whether the issue is with the client or the server , > Please Help.. > > > CLIENT.PY > > import socket > import os > import sys > os.system("C:\Python26\ping.vbs") > host = "localhost" > port= 23333 > size = 1024 > > s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) > s.connect((host,port)) > > > > > f=open('output.txt','r') > while 1: > data = f.readline() > if data: s.send(data) > else: break > > > > f.close() > > s.close() > > > > SERVER.PY > > > import socket > > host = "" > port = 23333 > size = 1024 > backlog=5 > s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > s.bind((host,port)) > s.listen(backlog) > > while 1: > client, addr =s.accept() > data=client.recv(size) > if data: > print data > > else: > print "client exit" > > s.close() > > > > > > > > > > -- > Regards > Aditya > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20110621/b2cd975c/attachment-0001.html > > > > ------------------------------ > > Message: 6 > Date: Tue, 21 Jun 2011 08:15:55 +0100 > From: "Alan Gauld" > To: tutor at python.org > Subject: Re: [Tutor] Socket Programming issue > Message-ID: > Content-Type: text/plain; format=flowed; charset="iso-8859-1"; > reply-type=original > > > "aditya" wrote > > > is that although the Vbscript writes the output to the file > > correctly but > > when the client sends the contents of the file to the server via > > socket , it > > sometimes prints all the lines of the file on the server and > > sometimes it > > doesnt , i dont know whether the issue is with the client or the > > server , > > Use the return values from functions. > > > CLIENT.PY > > > > import socket > > import os > > import sys > > os.system("C:\Python26\ping.vbs") > > host = "localhost" > > port= 23333 > > size = 1024 > > > > s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > s.connect((host,port)) > > > > f=open('output.txt','r') > > while 1: > > data = f.readline() > > You could print the data here to check that you got something > meaningful from the file.... > > > if data: s.send(data) > > The socket documentation specifically says: > --------------------------------- > socket.send(string[, flags]) > Send data to the socket. The socket must be connected to a remote > socket. The optional flags argument has the same meaning as for recv() > above. Returns the number of bytes sent. Applications are responsible > for checking that all data has been sent; if only some of the data was > transmitted, the application needs to attempt delivery of the > remaining data. > > ------------------------------------------ > Notice that it tells you how many bytes have been sent, and it > is your responsibility to check and retry if necessary. > I see no check nor any attempt to retry.... > > That should tell you if the data is leaving the client at least. > > > > SERVER.PY > > import socket > > > > host = "" > > port = 23333 > > size = 1024 > > backlog=5 > > s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > > > s.bind((host,port)) > > s.listen(backlog) > > > > while 1: > > client, addr =s.accept() > > data=client.recv(size) > > if data: > > print data > > else: > > print "client exit" > > This implies you should always get something printed, do you? > When you say it sometimes prints the lines and sometimes > not, does it print the exit message instead? > > > s.close() > > I'm not clear where this line sits since the mail has lost > its indentation. Is it inside the else or at the while level? > > Just some things to c0onsider, > > 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 88, Issue 83 > ************************************* > -- Thank you Arun Kumar http://clicknscroll.blogspot.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From merrickdav at gmail.com Tue Jun 21 10:12:04 2011 From: merrickdav at gmail.com (David Merrick) Date: Tue, 21 Jun 2011 20:12:04 +1200 Subject: [Tutor] Using class methods Message-ID: I need help using Class methods in another class. I have a class called Critter and I want to create two critters in a farm Class Farm and use Class Critter's methods # A virtual pet to care for class Critter(object): """A virtual pet""" def __init__(self, name, hunger = 0, boredom = 0): self.name = name self.hunger = hunger self.boredom = boredom # __ denotes private method def __pass_time(self,farm): self.hunger += 1 self.boredom += 1 self.__str__() def __str__(self,farmlet): print("Hunger is",self.hunger, "Boredom is " ,self.boredom) print("Unhappines is ",self.hunger + self.boredom," and Mood is ",self.mood) @property def mood(self): unhappiness = self.hunger + self.boredom if unhappiness < 5: m = "happy" elif 5 <= unhappiness <= 10: m = "okay" elif 11 <= unhappiness <= 15: m = "frustrated" else: m = "mad" return m def talk(self): print("I'm", self.name, "and I feel", self.mood, "now.\n") self.__pass_time() def eat(self): food = int(input("Enter how much food you want to feed your critter: ")) print("Brruppp. Thank you.") self.hunger -= food # hunger = 0 at iniatition # self.hunger = self.boredom - food if self.hunger < 0: self.hunger = 0 self.__pass_time() def play(self): fun = int(input("Enter how much fun you want your critter to have: ")) print("Wheee!") self.boredom -= fun # boredom = 0 at iniatition # self.boredom = self.boredom - fun if self.boredom < 0: self.boredom = 0 self.__pass_time() class Farm(Critter,hunger = 0,boredom = 0): #A collection of Critters def __init__(farmlet, name): for critter in farmlet: critter.name = name critter.hunger = hunger critter.boredom = boredom def talk(self,farmlet): for critter in farmlet: print(self,farmlet) def __str__(farmlet): for critter in farmlet: print("Hunger is",critter.hunger, "Boredom is " ,critter.boredom) print("Unhappines is ",critter.hunger + critter.boredom," and Mood is ",critter.mood) def eat(farmlet): for critter in farmlet: food = int(input("Enter how much food you want to feed your critter: ")) print("Brruppp. Thank you.") farmlet.hunger -= food # hunger = 0 at iniatition # self.hunger = self.boredom - food if farmlet.hunger < 0: farmlet.hunger = 0 farmlet.__pass_time() def main(): ## crit_name = input("What do you want to name your critter?: ") ## crit = Critter(crit_name) crit1 = Critter("Sweetie") crit2 = Critter("Dave") farmlet = [crit1,crit2] farmlet.hunger = 0 farmlet.boredom = 0 farm = Farm.__str__(farmlet) choice = None while choice != "0": print \ (""" Critter Caretaker 0 - Quit 1 - Listen to your critter 2 - Feed your critter 3 - Play with your critter """) choice = input("Choice: ") print() # exit if choice == "0": print("Good-bye.") # listen to your critter elif choice == "1": farm = Farm.__str__(farmlet) # feed your critter elif choice == "2": farm = Farm.eat(farmlet) # play with your critter elif choice == "3": farm.play(farmlet) # some unknown choice else: print("\nSorry, but", choice, "isn't a valid choice.") main() ("\n\nPress the enter key to exit.") -- Dave Merrick merrickdav at gmail.com Ph 03 3423 121 Cell 027 3089 169 -------------- next part -------------- An HTML attachment was scrubbed... URL: From merrickdav at gmail.com Tue Jun 21 09:38:08 2011 From: merrickdav at gmail.com (David Merrick) Date: Tue, 21 Jun 2011 19:38:08 +1200 Subject: [Tutor] Using Class methods Message-ID: I need help using Class methods in another class. I have a class called Critter and I want to create two critters in a farm Class Farm and use Class Critter's methods -- Dave Merrick merrickdav at gmail.com Ph 03 3423 121 Cell 027 3089 169 -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: critter_farm2.py Type: application/octet-stream Size: 3980 bytes Desc: not available URL: From andreengels at gmail.com Tue Jun 21 12:32:48 2011 From: andreengels at gmail.com (Andre Engels) Date: Tue, 21 Jun 2011 12:32:48 +0200 Subject: [Tutor] Using class methods In-Reply-To: References: Message-ID: On Tue, Jun 21, 2011 at 10:12 AM, David Merrick wrote: > I need help using Class methods in another class. I have a class called > Critter and I want to create two critters in a farm? Class Farm and use > Class Critter's methods Could you please specify where your current code does not suffice - where does it something different than you want, or where do you want to do something (and why) that you don't know how to do? -- Andr? Engels, andreengels at gmail.com From ajarncolin at gmail.com Tue Jun 21 14:57:39 2011 From: ajarncolin at gmail.com (col speed) Date: Tue, 21 Jun 2011 19:57:39 +0700 Subject: [Tutor] Using Class methods In-Reply-To: References: Message-ID: and? On 21 June 2011 14:38, David Merrick wrote: > I need help using Class methods in another class. I have a class called > Critter and I want to create two critters in a farm Class Farm and use > Class Critter's methods > > -- > Dave Merrick > > merrickdav at gmail.com > > Ph 03 3423 121 > Cell 027 3089 169 > > _______________________________________________ > 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 g.nius.ck at gmail.com Tue Jun 21 16:03:10 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Tue, 21 Jun 2011 10:03:10 -0400 Subject: [Tutor] Using class methods In-Reply-To: References: Message-ID: Well it depends what you mean. If you have a critter object and want to invoke its method inside the farm, do somethinh like this. class Farm_class(object): def feed(self, critter): critter.eat(self.food) or if you want to use a method of the Critter class within the farm do class Farm_class(object): def count(self): print Critter_class.count() On Tuesday, June 21, 2011, Andre Engels wrote: > On Tue, Jun 21, 2011 at 10:12 AM, David Merrick wrote: >> I need help using Class methods in another class. I have a class called >> Critter and I want to create two critters in a farm? Class Farm and use >> Class Critter's methods > > Could you please specify where your current code does not suffice - > where does it something different than you want, or where do you want > to do something (and why) that you don't know how to do? > > -- > Andr? Engels, andreengels at gmail.com > _______________________________________________ > 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 Tue Jun 21 19:31:11 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 21 Jun 2011 18:31:11 +0100 Subject: [Tutor] Using Class methods References: Message-ID: "David Merrick" wrote >I need help using Class methods in another class. I have a class >called > Critter and I want to create two critters in a farm Class Farm and > use > Class Critter's methods Ok, You seem to be a bit confused by OOP, and your code is using all sorts of features you probably shouldn't be messing with yet. Let's start with your main() method: def main(): crit1 = Critter("Sweetie") crit2 = Critter("Dave") farmlet = [crit1,crit2] So far so good. farmlet.hunger = 0 farmlet.boredom = 0 But here you are trying to access hunger and boredom attributes of a list(farmlet) which doesn't have those attributes. They are supposed to be part of your Farm class. But you haven't got a Farm yet so you can't access its attributes. farm = Farm.__str__(farmlet) Now you assign the string representation of a Farm to farm, but again you have no Farm object. And its highly unusual to pass attributes to a __str__ method! In fact its likely to cause serious problems if you ever try to print the Farm! So what about those attributes? Now we come to the next problem, let's look at the class definition: class Farm(Critter,hunger = 0,boredom = 0): I have no idea where you got that syntax, but its wrong. The parentheses in a class definition contain the list of super classes from which you are inheriting. A Farm is not a type of Critter, it has a collection of them. And you cannot define attributes there, you need to do that in the class body (for class level atrtributes), or in the init method (for instance level attributes). of critters... def __init__(farmlet, name): A method needs to take the instance placeholder variable - usually called self - as its first attribute. If we add a self this implies that you need to create a Farm with: f = Farm(aFarmlet, aName) But you never actually creaate a Farm object in your code... for critter in farmlet: critter.name = name critter.hunger = hunger critter.boredom = boredom This bit would be OK except all the critters would have the same name, hunger and boredom, which seems unlikely? Especially since you gave them different names when you created them(see above). There are plenty other anomolies I could highlight but as I say, I think you need to go back to first principles and try again. This time forget about using properties, and don't create any __xxx__ methods yet, (except __init__!) - they just confuse things at this stage. I would suggest you strip it right back to just defining the two classes and their init methods to initialise the data, nothing else. Your basic logic is then to create some critters - which you do already. Then create a Farm, passing the list of critters into it. Then print out the farm's list to check they are in there. Once you have done that add the __str__ methods to aid printing. Once that works you can start to think about addig the game logic and supporting methods. But get the basics right first. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From wprins at gmail.com Tue Jun 21 19:32:58 2011 From: wprins at gmail.com (Walter Prins) Date: Tue, 21 Jun 2011 18:32:58 +0100 Subject: [Tutor] html files to pdf document In-Reply-To: <994B3638-CD1E-449D-86AE-29A2AF0418A2@xs4all.nl> References: <4DFF7C50.3000405@gmail.com> <00E86B69-6D07-46ED-B4CA-4F740509BB0B@xs4all.nl> <994B3638-CD1E-449D-86AE-29A2AF0418A2@xs4all.nl> Message-ID: On 20 June 2011 23:29, Michiel Overtoom wrote: > > On Jun 21, 2011, at 00:19, Walter Prins wrote: > > > For reference, for me the top hit is http://www.xhtml2pdf.com/ which > does indeed look like it might do the job (and is a pure python solution.) > > I get five SERP pages with tons of Stackoverflow hits, but not one for > www.xhtml2pdf.com! I think this is what is known as an Internet Search > Bubble. > I also get the SERP pages if I include the quotes in the search. Try the search without the quotes. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Tue Jun 21 19:35:19 2011 From: wprins at gmail.com (Walter Prins) Date: Tue, 21 Jun 2011 18:35:19 +0100 Subject: [Tutor] html files to pdf document In-Reply-To: <994B3638-CD1E-449D-86AE-29A2AF0418A2@xs4all.nl> References: <4DFF7C50.3000405@gmail.com> <00E86B69-6D07-46ED-B4CA-4F740509BB0B@xs4all.nl> <994B3638-CD1E-449D-86AE-29A2AF0418A2@xs4all.nl> Message-ID: On 20 June 2011 23:29, Michiel Overtoom wrote: > > On Jun 21, 2011, at 00:19, Walter Prins wrote: > > > For reference, for me the top hit is http://www.xhtml2pdf.com/ which > does indeed look like it might do the job (and is a pure python solution.) > > I get five SERP pages with tons of Stackoverflow hits, but not one for > www.xhtml2pdf.com! I think this is what is known as an Internet Search > Bubble. > > Sorry, I mean to say, I also get SERP pages with as you put it tons of Stackoverflow hits (and not www.xhtml2pdf.com) but this is because the phrase as quoted does not appear on www.xxhtml2pdf.com obviously. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Jun 21 19:35:56 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 21 Jun 2011 18:35:56 +0100 Subject: [Tutor] Using class methods References: Message-ID: "Christopher King" wrote > class Farm_class(object): ... > or if you want to use a method of the Critter class within the farm > do > > class Farm_class(object): But please do NOT add '_class' to the end of your class names! The fact that it has a capital letter at the front combined with context should be enough of a clue. Otherwise we'll all wind up doing things like: x_int = 2 y_int = 4 answer_string = str(x_int+y_int) Eek, please, no! :-) -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Jun 21 19:43:45 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 21 Jun 2011 18:43:45 +0100 Subject: [Tutor] Tutor Digest, Vol 88, Issue 83 References: Message-ID: PLEASE PAY ATTENTION TO THE INSTRUCTIONS: >> When replying, please edit your Subject line so it is more specific >> than "Re: Contents of Tutor digest..." AND please edit the contents so we don't need to scroll through the whole digest to find your comments! > Thanks for the suggestion but my desktop environment is not qt. > Its > gnome. And i'm looking for some pure python way. www.xhtml2pdf is > buggy and > i had problems installing that library Then you have some choices: 1) Fix the xhtml2pdf bugs for everyone's benefit 2) Use the code as a template for your own solution. 3) Spend more time on Google to find another solution. 4) Switch to qt or integrate qt with your desktop. 5) Figure out how to do it from scratch Once you have decided your best approach come back with any specific issues. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From wprins at gmail.com Tue Jun 21 20:59:38 2011 From: wprins at gmail.com (Walter Prins) Date: Tue, 21 Jun 2011 19:59:38 +0100 Subject: [Tutor] Tutor Digest, Vol 88, Issue 83 In-Reply-To: References: Message-ID: Hi Arun, On 21 June 2011 08:56, arun kumar wrote: > yes i did a Google search but did find anything useful. The xhtml2pdf is > buggy in i'm unable to install it. Also mailed the community of xhtml2pdf > but didn't receive any reply from them. > OK, firstly I'm no expect on xhtml2pdf, but not being able to install it does not neccesarily mean that it's buggy... It might (I suspect) be something to do with your environment or with what you're doing. Exactly what errors did you get? Out of curiosity, I just installed it on my Ubuntu box, by issuing: sudo pip install xhtml2pdf It apparently installed successfully. (You would only be able to follow this command if a) you're using Ubuntu, b) you have "pip" installed in your Python environment. If you don't know what "pip" is or why it's useful then either post back and ask, or better yet, first do your own research and then post if you still have questions and don't understand.) Thanks for the suggestion but my desktop environment is not qt. Its > gnome. > QT is not a desktop environment, it's a cross application framework, primary feature of which is its platform independent widget set. Therefore your desktop environment is actually irrelevant w.r.t. whether or not you use QT in your solution. In other words: You can install QT and run QT applications on your Gnome desktop. (Or on pretty much any other platform where QT is available.) On Debian based desktops using Gnome (like Ubuntu), the following command (untested) should pull in QT4 and all the dependencies, together with the Python wrappers, to allow you to try out the QT PDF suggestion. apt-get install python-qt4 As an aside, it (QT4) was already installed on my Ubuntu installation, I don't know if that's because at some point I installed an app that required it or whether it's because it was installed by default. Regards, Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Tue Jun 21 21:17:28 2011 From: wprins at gmail.com (Walter Prins) Date: Tue, 21 Jun 2011 20:17:28 +0100 Subject: [Tutor] Tutor Digest, Vol 88, Issue 83 In-Reply-To: References: Message-ID: Hi again Arun, On 21 June 2011 19:59, Walter Prins wrote: > It apparently installed successfully. (You would only be able to follow > this command if a) you're using Ubuntu, b) you have "pip" installed in your > Python environment. If you don't know what "pip" is or why it's useful then > either post back and ask, or better yet, first do your own research and then > post if you still have questions and don't understand.) > Out of curiosity I just did a quick followup experiment with xhtml2pdf after installing it: 1) I read the documentation page here: http://www.xhtml2pdf.com/doc/pisa-en.html 2) Then I saved the page to my desktop as "pisa Documentation.html" (the default filename) 3) Then I issued (as suggested in the documentation) the command: xhtml2pdf -s "pisa Documentation.html" 4) xhtml2pdf then spat out some messages and generated "pisa Documentation.pdf" The result is (I think) pretty good. I must note that I've not encountered any real problems so far either installing it or using it, so I must conclude that whatever installation issues you ran into was due to something specific to your current platform, or to something you've done, and not due to bugs in xhtml2pdf as you suggested. (In fact the results are so good that I'm planning on playing around with this in Python a bit more myself... might come in very handy for generating reports and suchlike at some point no doubt...) Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From merrickdav at gmail.com Tue Jun 21 22:44:47 2011 From: merrickdav at gmail.com (David Merrick) Date: Wed, 22 Jun 2011 08:44:47 +1200 Subject: [Tutor] Tutor Digest, Vol 88, Issue 86 In-Reply-To: References: Message-ID: I have created a Critter object and a Farm object which is two critters. I want to use Critters methods in the Farm object as it just 2 critters in a list crit1 = Critter("Sweetie") crit2 = Critter("Dave") farmlet = [crit1,crit2] # Critter Caretaker > # A virtual pet to care for > class Critter(object): > > """A virtual pet""" > def __init__(self, name, hunger = 0, boredom = 0): > self.name = name > self.hunger = hunger > self.boredom = boredom > > # __ denotes private method > def __pass_time(self,farm): > self.hunger += 1 > self.boredom += 1 > self.__str__() > > def __str__(self,farmlet): > print("Hunger is",self.hunger, "Boredom is " ,self.boredom) > print("Unhappines is ",self.hunger + self.boredom," and Mood is > ",self.mood) > > > > @property > def mood(self): > unhappiness = self.hunger + self.boredom > if unhappiness < 5: > m = "happy" > elif 5 <= unhappiness <= 10: > m = "okay" > elif 11 <= unhappiness <= 15: > m = "frustrated" > else: > m = "mad" > return m > > def talk(self): > print("I'm", self.name, "and I feel", self.mood, "now.\n") > self.__pass_time() > > > def eat(self): > food = int(input("Enter how much food you want to feed your > critter: ")) > print("Brruppp. Thank you.") > self.hunger -= food > # hunger = 0 at iniatition > # self.hunger = self.boredom - food > if self.hunger < 0: > self.hunger = 0 > self.__pass_time() > > > def play(self): > fun = int(input("Enter how much fun you want your critter to have: > ")) > print("Wheee!") > self.boredom -= fun > # boredom = 0 at iniatition > # self.boredom = self.boredom - fun > if self.boredom < 0: > self.boredom = 0 > self.__pass_time() > > class Farm(Critter,hunger = 0,boredom = 0): > #A collection of Critters > > def __init__(farmlet, name): > for critter in farmlet: > critter.name = name > critter.hunger = hunger > critter.boredom = boredom > > def talk(self,farmlet): > for critter in farmlet: > print(self,farmlet) > > def __str__(farmlet): > for critter in farmlet: > print("Hunger is",critter.hunger, "Boredom is " ,critter.boredom) > print("Unhappines is ",critter.hunger + critter.boredom," and > Mood is ",critter.mood) > > def eat(farmlet): > for critter in farmlet: > food = int(input("Enter how much food you want to feed your > critter: ")) > print("Brruppp. Thank you.") > farmlet.hunger -= food > # hunger = 0 at iniatition > # self.hunger = self.boredom - food > if farmlet.hunger < 0: > farmlet.hunger = 0 > farmlet.__pass_time() > > def main(): > ## crit_name = input("What do you want to name your critter?: ") > ## crit = Critter(crit_name) > crit1 = Critter("Sweetie") > crit2 = Critter("Dave") > farmlet = [crit1,crit2] > farmlet.hunger = 0 > farmlet.boredom = 0 > farm = Farm.__str__(farmlet) > > > choice = None > while choice != "0": > print \ > (""" > Critter Caretaker > > 0 - Quit > 1 - Listen to your critter > 2 - Feed your critter > 3 - Play with your critter > """) > > choice = input("Choice: ") > print() > > # exit > if choice == "0": > print("Good-bye.") > > # listen to your critter > elif choice == "1": > farm = Farm.__str__(farmlet) > > # feed your critter > elif choice == "2": > farm = Farm.eat(farmlet) > > # play with your critter > elif choice == "3": > farm.play(farmlet) > > # some unknown choice > else: > print("\nSorry, but", choice, "isn't a valid choice.") > > > > > > main() > ("\n\nPress the enter key to exit.") > > > > Well it depends what you mean. If you have a critter object and want > to invoke its method inside the farm, do somethinh like this. > class Farm_class(object): > def feed(self, critter): > critter.eat(self.food) > > or if you want to use a method of the Critter class within the farm do > > class Farm_class(object): > def count(self): > print Critter_class.count() > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Jun 22 01:43:05 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 22 Jun 2011 00:43:05 +0100 Subject: [Tutor] Tutor Digest, Vol 88, Issue 86 References: Message-ID: "David Merrick" wrote >I have created a Critter object and a Farm object which is two >critters. I > want to use Critters methods in the Farm object as it just 2 > critters in a > list > > crit1 = Critter("Sweetie") > crit2 = Critter("Dave") > farmlet = [crit1,crit2] > This creates two critters but it does not create a Farm object, it only creates a list of two critters. (That might be all you need! Maybe you don't need a Farm class) So to call the talk() method of crit1 via the farmlet list: farmlet[0].talk() Or for all the critters in the farmlet: for critter in farmlet: critter.talk() HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From metolone+gmane at gmail.com Wed Jun 22 04:41:24 2011 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Tue, 21 Jun 2011 19:41:24 -0700 Subject: [Tutor] Socket Programming issue References: Message-ID: "aditya" wrote in message news:BANLkTikS+gzm=89tHCZpbWKSd+wUfeC7mA at mail.gmail.com... > This is a small client-server program in which i am using a Vbscript > program > to check for connectivity of 2 machines and write the output to a text > file > whether it connectes or not , > > > for example the contents of the file *output.txt* are > > 192.168.1.2 is connected > 192.168.1.10 is not connected > > > Now i am trying to send the contents of this file from a client through a > socket to a server which is running on my main server .This is basically > created to automate the checking of connectivity of the machines. The > issue > is that although the Vbscript writes the output to the file correctly but > when the client sends the contents of the file to the server via socket , > it > sometimes prints all the lines of the file on the server and sometimes it > doesnt , i dont know whether the issue is with the client or the server , > Please Help.. > > > CLIENT.PY > > import socket > import os > import sys > os.system("C:\Python26\ping.vbs") > host = "localhost" > port= 23333 > size = 1024 > > s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) > s.connect((host,port)) > > > > > f=open('output.txt','r') > while 1: > data = f.readline() > if data: s.send(data) > else: break Use "s.sendall(data)" instead of send to correct the error Alan pointed out. > > > > f.close() > > s.close() > > > > SERVER.PY > > > import socket > > host = "" > port = 23333 > size = 1024 > backlog=5 > s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > s.bind((host,port)) > s.listen(backlog) > s.accept() should be before the while loop, then loop on recv until the client closes the connection. Since TCP is a streaming protocol, recv() could receive less than a line or more than one line at once, but with the accept inside the loop the script will pause waiting for a different client to connect, and won't continue reading the data from the original client. -Mark > while 1: > client, addr =s.accept() > data=client.recv(size) > if data: > print data > > else: > print "client exit" > > s.close() > > > > > > > > > > -- > Regards > Aditya > -------------------------------------------------------------------------------- > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From merrickdav at gmail.com Wed Jun 22 07:14:05 2011 From: merrickdav at gmail.com (David Merrick) Date: Wed, 22 Jun 2011 17:14:05 +1200 Subject: [Tutor] Class methods Message-ID: # Critter Caretaker # A virtual pet to care for class Critter(object): """A virtual pet""" def __init__(self, name, hunger = 0, boredom = 0): self.name = name self.hunger = hunger self.boredom = boredom # __ denotes private method def __pass_time(self): self.hunger += 1 self.boredom += 1 self.__str__() def __str__(self): print("Hunger is",self.hunger, "Boredom is " ,self.boredom) print("Unhappines is ",self.hunger + self.boredom," and Mood is ",self.mood) @property def mood(self): unhappiness = self.hunger + self.boredom if unhappiness < 5: m = "happy" elif 5 <= unhappiness <= 10: m = "okay" elif 11 <= unhappiness <= 15: m = "frustrated" else: m = "mad" return m def talk(self): print("I'm", self.name, "and I feel", self.mood, "now.\n") self.__pass_time() def eat(self): food = int(input("Enter how much food you want to feed your critter: ")) print("Brruppp. Thank you.") self.hunger -= food # hunger = 0 at iniatition # self.hunger = self.boredom - food if self.hunger < 0: self.hunger = 0 self.__pass_time() def play(self): fun = int(input("Enter how much fun you want your critter to have: ")) print("Wheee!") self.boredom -= fun # boredom = 0 at iniatition # self.boredom = self.boredom - fun if self.boredom < 0: self.boredom = 0 self.__pass_time() class Farm(Critter): def __init__(self,farmlet): Critter.__init__(self,farmlet) self.farmlet = farmlet def talk(self,farmlet): for critter in farmlet: print("Hello") Critter.talk(farmlet) def main(): crit1 = Critter("Sweetie") crit2 = Critter("Dave") farmlet = [crit1,crit2] f = Farm(farmlet) choice = None while choice != "0": print \ (""" Critter Caretaker 0 - Quit 1 - Listen to your critter 2 - Feed your critter 3 - Play with your critter """) choice = input("Choice: ") print() # exit if choice == "0": print("Good-bye.") # listen to your critter elif choice == "1": f.talk(farmlet) # feed your critter elif choice == "2": f.eat(farmlet) # play with your critter elif choice == "3": f.play(farmlet) # some unknown choice else: print("\nSorry, but", choice, "isn't a valid choice.") main() ("\n\nPress the enter key to exit.") *OUTPUT* Critter Caretaker 0 - Quit 1 - Listen to your critter 2 - Feed your critter 3 - Play with your critter Choice: 1 Hello Traceback (most recent call last): File "D:/David/Python/programs/critter_farm3.py", line 115, in main() File "D:/David/Python/programs/critter_farm3.py", line 101, in main f.talk(farmlet) File "D:/David/Python/programs/critter_farm3.py", line 72, in talk Critter.talk(farmlet) File "D:/David/Python/programs/critter_farm3.py", line 38, in talk print("I'm", self.name, "and I feel", self.mood, "now.\n") AttributeError: 'list' object has no attribute 'name' I am trying to access Crit1 and Crit2 namr in farmlet -- Dave Merrick merrickdav at gmail.com Ph 03 3423 121 Cell 027 3089 169 -------------- next part -------------- An HTML attachment was scrubbed... URL: From johan at accesstel.com.au Wed Jun 22 08:55:41 2011 From: johan at accesstel.com.au (Johan Geldenhuys) Date: Wed, 22 Jun 2011 16:55:41 +1000 Subject: [Tutor] sftp get single file In-Reply-To: References: <20090717150843.GA20678@chicago.blisses.org> Message-ID: <032401cc30a9$66e8c980$34ba5c80$@com.au> Hi all, This topic is old, but I have a similar issue and I know everybody will say I should use piramiko, but it is not that simple. The device I have to run my python scripts on is a simple, small, scaled down version of Suse linux and I can't install other packages like piramiko. All the files I need to use that is not part of Python 2.7 must be included in my package. With the above in mind, what can I use to open SFTP to a server and transfer a file? Thanks Johan -----Original Message----- From: tutor-bounces+johan=accesstel.com.au at python.org [mailto:tutor-bounces+johan=accesstel.com.au at python.org] On Behalf Of Sander Sweers Sent: Saturday, 18 July 2009 1:43 AM To: Matt Herzog Cc: Python List Subject: Re: [Tutor] sftp get single file 2009/7/17 Matt Herzog : > Hello All. > > I need to use paramiko to sftp get a single file from a remote server. > The remote file's base name will be today's date (%Y%m%d) dot tab. > I need help joining the today with the .tab extension. Do I need globbing? > > example: 20090716.tab > > #!/usr/bin/env python > import paramiko > import glob > import os > import time > hostname = 'sftp.booboo.com' > port = 22 > username = 'booboo' > password = '07N4219?' > # glob_pattern='*.tab' > today = time.strftime("%Y%m%d") > remotepath = today.tab > localpath = '/home/data/text' > > if __name__ == "__main__": > t = paramiko.Transport((hostname, port)) > t.connect(username=username, password=password) > sftp = paramiko.SFTPClient.from_transport(t) > sftp.get(remotepath, localpath) > t.close() > -- You don't need glob if you know in advance what the filename is. Print example below. --- import time today = time.localtime() datestr = time.strftime("%Y%m%d",today) ext = ".tab" print datestr + ext --- Greets Sander _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor Checked by AVG - www.avg.com Version: 8.5.387 / Virus Database: 270.13.17/2242 - Release Date: 07/16/09 18:00:00 From alan.gauld at btinternet.com Wed Jun 22 09:58:03 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 22 Jun 2011 08:58:03 +0100 Subject: [Tutor] Class methods References: Message-ID: "David Merrick" wrote > class Critter(object): > > def __init__(self, name, hunger = 0, boredom = 0): > def __pass_time(self): > def __str__(self): > @property > def mood(self): > def talk(self): > def eat(self): > def play(self): > > class Farm(Critter): I still don't think a Farm is a type of Critter... > def __init__(self,farmlet): > Critter.__init__(self,farmlet) This will set the name to farmlet, which I don't think you want. > def talk(self,farmlet): You don't need to pass farmlet in since the class has farmlet stored inside it. You can access farmlet with self.farmlet. > for critter in farmlet: > print("Hello") > Critter.talk(farmlet) You want the instance to talk not the class. So you need to use critter.talk() And the talk method does not take any arguments except self. What you are doing here is calling the class method with an instance value of farmlet. ie self in that method gets the value of farmlet. > def main(): > crit1 = Critter("Sweetie") > crit2 = Critter("Dave") > farmlet = [crit1,crit2] > f = Farm(farmlet) > > choice = None > while choice != "0": > print \ > (""" > Critter Caretaker > > 0 - Quit > 1 - Listen to your critter > 2 - Feed your critter > 3 - Play with your critter > """) > > choice = input("Choice: ") > print() > > # exit > if choice == "0": > print("Good-bye.") > > # listen to your critter > elif choice == "1": > f.talk(farmlet) > > # feed your critter > elif choice == "2": > f.eat(farmlet) Note that f.eat is a method you inherit from Critter. The Critter method does not take any arguments so this will fail. > # play with your critter > elif choice == "3": > f.play(farmlet) Same with f.play() > Traceback (most recent call last): > File "D:/David/Python/programs/critter_farm3.py", line 72, in talk > Critter.talk(farmlet) > File "D:/David/Python/programs/critter_farm3.py", line 38, in talk > print("I'm", self.name, "and I feel", self.mood, "now.\n") > AttributeError: 'list' object has no attribute 'name' This is because you are accessing the method via the class and passing farmlet as the instance value rather than sending the message to the innstance directly. Use critter.talk() # and no farmlet needed! HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From lists at solderintheveins.co.uk Wed Jun 22 11:07:53 2011 From: lists at solderintheveins.co.uk (Peter Lavelle) Date: Wed, 22 Jun 2011 10:07:53 +0100 Subject: [Tutor] sftp get single file In-Reply-To: <032401cc30a9$66e8c980$34ba5c80$@com.au> References: <20090717150843.GA20678@chicago.blisses.org> <032401cc30a9$66e8c980$34ba5c80$@com.au> Message-ID: <4E01B0E9.8000300@solderintheveins.co.uk> You could use the subprocess module to run the relevant system commands. More info on running sftp non-interactively (i.e from a script) can be found here: http://fixunix.com/ssh/238284-non-interactive-sftp-put.html Regards Peter Lavelle From merrickdav at gmail.com Thu Jun 23 00:29:34 2011 From: merrickdav at gmail.com (David Merrick) Date: Thu, 23 Jun 2011 10:29:34 +1200 Subject: [Tutor] Tutor Digest, Vol 88, Issue 89 In-Reply-To: References: Message-ID: Can someone show me how to code this correctly please On Wed, Jun 22, 2011 at 10:00 PM, 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: Class methods (Alan Gauld) > 2. Re: sftp get single file (Peter Lavelle) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Wed, 22 Jun 2011 08:58:03 +0100 > From: "Alan Gauld" > To: tutor at python.org > Subject: Re: [Tutor] Class methods > Message-ID: > Content-Type: text/plain; format=flowed; charset="UTF-8"; > reply-type=original > > "David Merrick" wrote > > > class Critter(object): > > > > def __init__(self, name, hunger = 0, boredom = 0): > > def __pass_time(self): > > def __str__(self): > > @property > > def mood(self): > > def talk(self): > > def eat(self): > > def play(self): > > > > class Farm(Critter): > > I still don't think a Farm is a type of Critter... > > > def __init__(self,farmlet): > > Critter.__init__(self,farmlet) > > This will set the name to farmlet, which I don't > think you want. > > > def talk(self,farmlet): > > You don't need to pass farmlet in since the > class has farmlet stored inside it. > You can access farmlet with self.farmlet. > > > for critter in farmlet: > > print("Hello") > > Critter.talk(farmlet) > > You want the instance to talk not the class. > So you need to use critter.talk() And the talk > method does not take any arguments except > self. What you are doing here is calling the > class method with an instance value of farmlet. > ie self in that method gets the value of farmlet. > > > def main(): > > crit1 = Critter("Sweetie") > > crit2 = Critter("Dave") > > farmlet = [crit1,crit2] > > f = Farm(farmlet) > > > > choice = None > > while choice != "0": > > print \ > > (""" > > Critter Caretaker > > > > 0 - Quit > > 1 - Listen to your critter > > 2 - Feed your critter > > 3 - Play with your critter > > """) > > > > choice = input("Choice: ") > > print() > > > > # exit > > if choice == "0": > > print("Good-bye.") > > > > # listen to your critter > > elif choice == "1": > > f.talk(farmlet) > > > > # feed your critter > > elif choice == "2": > > f.eat(farmlet) > > Note that f.eat is a method you inherit from Critter. > The Critter method does not take any arguments > so this will fail. > > > # play with your critter > > elif choice == "3": > > f.play(farmlet) > > Same with f.play() > > > Traceback (most recent call last): > > File "D:/David/Python/programs/critter_farm3.py", line 72, in talk > > Critter.talk(farmlet) > > File "D:/David/Python/programs/critter_farm3.py", line 38, in talk > > print("I'm", self.name, "and I feel", self.mood, "now.\n") > > AttributeError: 'list' object has no attribute 'name' > > This is because you are accessing the method via > the class and passing farmlet as the instance value > rather than sending the message to the innstance > directly. Use > > critter.talk() # and no farmlet needed! > > HTH, > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > > > ------------------------------ > > Message: 2 > Date: Wed, 22 Jun 2011 10:07:53 +0100 > From: Peter Lavelle > To: tutor at python.org > Subject: Re: [Tutor] sftp get single file > Message-ID: <4E01B0E9.8000300 at solderintheveins.co.uk> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > You could use the subprocess module to run the relevant system commands. > More info on running sftp non-interactively (i.e from a script) can be > found here: http://fixunix.com/ssh/238284-non-interactive-sftp-put.html > > Regards > > Peter Lavelle > > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 88, Issue 89 > ************************************* > -- Dave Merrick merrickdav at gmail.com Ph 03 3423 121 Cell 027 3089 169 -------------- next part -------------- An HTML attachment was scrubbed... URL: From merrickdav at gmail.com Thu Jun 23 00:31:08 2011 From: merrickdav at gmail.com (David Merrick) Date: Thu, 23 Jun 2011 10:31:08 +1200 Subject: [Tutor] Tutor Digest, Vol 88, Issue 89 In-Reply-To: References: Message-ID: > > Can someone show me how to code this correctly please > > > class Critter(object): > > > > def __init__(self, name, hunger = 0, boredom = 0): > > def __pass_time(self): > > def __str__(self): > > @property > > def mood(self): > > def talk(self): > > def eat(self): > > def play(self): > > > > class Farm(Critter): > > I still don't think a Farm is a type of Critter... > > > def __init__(self,farmlet): > > Critter.__init__(self,farmlet) > > This will set the name to farmlet, which I don't > think you want. > > > def talk(self,farmlet): > > You don't need to pass farmlet in since the > class has farmlet stored inside it. > You can access farmlet with self.farmlet. > > > for critter in farmlet: > > print("Hello") > > Critter.talk(farmlet) > > You want the instance to talk not the class. > So you need to use critter.talk() And the talk > method does not take any arguments except > self. What you are doing here is calling the > class method with an instance value of farmlet. > ie self in that method gets the value of farmlet. > > > def main(): > > crit1 = Critter("Sweetie") > > crit2 = Critter("Dave") > > farmlet = [crit1,crit2] > > f = Farm(farmlet) > > > > choice = None > > while choice != "0": > > print \ > > (""" > > Critter Caretaker > > > > 0 - Quit > > 1 - Listen to your critter > > 2 - Feed your critter > > 3 - Play with your critter > > """) > > > > choice = input("Choice: ") > > print() > > > > # exit > > if choice == "0": > > print("Good-bye.") > > > > # listen to your critter > > elif choice == "1": > > f.talk(farmlet) > > > > # feed your critter > > elif choice == "2": > > f.eat(farmlet) > > Note that f.eat is a method you inherit from Critter. > The Critter method does not take any arguments > so this will fail. > > > # play with your critter > > elif choice == "3": > > f.play(farmlet) > > Same with f.play() > > > Traceback (most recent call last): > > File "D:/David/Python/programs/critter_farm3.py", line 72, in talk > > Critter.talk(farmlet) > > File "D:/David/Python/programs/critter_farm3.py", line 38, in talk > > print("I'm", self.name, "and I feel", self.mood, "now.\n") > > AttributeError: 'list' object has no attribute 'name' > > This is because you are accessing the method via > the class and passing farmlet as the instance value > rather than sending the message to the innstance > directly. Use > > critter.talk() # and no farmlet needed! > > HTH, > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From merrickdav at gmail.com Thu Jun 23 00:38:11 2011 From: merrickdav at gmail.com (David Merrick) Date: Thu, 23 Jun 2011 10:38:11 +1200 Subject: [Tutor] Class methods Message-ID: Can someone show me how to code this correctly please? # Critter Caretaker # A virtual pet to care for class Critter(object): """A virtual pet""" def __init__(self, name, hunger = 0, boredom = 0): self.name = name self.hunger = hunger self.boredom = boredom # __ denotes private method def __pass_time(self): self.hunger += 1 self.boredom += 1 self.__str__() def __str__(self): print("Hunger is",self.hunger, "Boredom is " ,self.boredom) print("Unhappines is ",self.hunger + self.boredom," and Mood is ",self.mood) @property def mood(self): unhappiness = self.hunger + self.boredom if unhappiness < 5: m = "happy" elif 5 <= unhappiness <= 10: m = "okay" elif 11 <= unhappiness <= 15: m = "frustrated" else: m = "mad" return m def talk(self): for critter in farmlet: print("I'm", self.name, "and I feel", self.mood, "now.\n") self.__pass_time() def eat(self): food = int(input("Enter how much food you want to feed your critter: ")) print("Brruppp. Thank you.") self.hunger -= food # hunger = 0 at iniatition # self.hunger = self.boredom - food if self.hunger < 0: self.hunger = 0 self.__pass_time() def play(self): fun = int(input("Enter how much fun you want your critter to have: ")) print("Wheee!") self.boredom -= fun # boredom = 0 at iniatition # self.boredom = self.boredom - fun if self.boredom < 0: self.boredom = 0 self.__pass_time() ##class Farm(Critter): ## def __init__(self,farmlet): ## Critter.__init__(self,farmlet) ## self.farmlet = farmlet ## ## def talk(self,farmlet): ## for critter in farmlet: ## print("Hello") ## Critter.talk(farmlet) def main(): crit1 = Critter("Sweetie") crit2 = Critter("Dave") farmlet = [crit1,crit2] choice = None while choice != "0": print \ (""" Critter Caretaker 0 - Quit 1 - Listen to your critter 2 - Feed your critter 3 - Play with your critter """) choice = input("Choice: ") print() # exit if choice == "0": print("Good-bye.") # listen to your critter elif choice == "1": for critter in farmlet: farmlet.talk() # feed your critter elif choice == "2": farmlet.eat() # play with your critter elif choice == "3": f.play(farmlet) # some unknown choice else: print("\nSorry, but", choice, "isn't a valid choice.") main() ("\n\nPress the enter key to exit.") *Output* Critter Caretaker 0 - Quit 1 - Listen to your critter 2 - Feed your critter 3 - Play with your critter Choice: 1 Traceback (most recent call last): File "I:/Python/programs/critter_farm4.py", line 117, in main() File "I:/Python/programs/critter_farm4.py", line 103, in main farmlet.talk() AttributeError: 'list' object has no attribute 'talk' -- Dave Merrick merrickdav at gmail.com Ph 03 3423 121 Cell 027 3089 169 -------------- next part -------------- An HTML attachment was scrubbed... URL: From alexandre.conrad at gmail.com Thu Jun 23 00:48:42 2011 From: alexandre.conrad at gmail.com (Alexandre Conrad) Date: Wed, 22 Jun 2011 15:48:42 -0700 Subject: [Tutor] Class methods In-Reply-To: References: Message-ID: David, 2011/6/22 David Merrick : > ??????? # listen to your critter > ??????? elif choice == "1": > ??????????? for critter in farmlet: > ??????????????? farmlet.talk() You want to call .talk() on your "critter" instance which has the .talk() method, not on farmlet (which is a list as the error message states) > Traceback (most recent call last): > ? File "I:/Python/programs/critter_farm4.py", line 117, in > ??? main() > ? File "I:/Python/programs/critter_farm4.py", line 103, in main > ??? farmlet.talk() > AttributeError: 'list' object has no attribute 'talk' You will probably have a problem when calling talk() because it references to the "farmlet" variable which doesn't exist in the scope of your .talk() method. HTH, -- Alex | twitter.com/alexconrad From jigenbakuda at yahoo.com Thu Jun 23 02:10:24 2011 From: jigenbakuda at yahoo.com (michael scott) Date: Wed, 22 Jun 2011 17:10:24 -0700 (PDT) Subject: [Tutor] Class methods In-Reply-To: References: Message-ID: <1308787824.77859.YahooMailNeo@web130201.mail.mud.yahoo.com> Just to add a little to Alexandre's answer.? You can keep most of the code the same just add in ?? ??????????? farmlet[0].eat() ??????????? farmlet[1].eat() and it will be okay... kinda. Or you could rewrite it and? do it another way...? I'm guessing that you are using python 3 by your print statements, so I don't think you need the int() around your input, even in python.2x input() was safe for numbers I believe (the whole list will rip my throat out if I'm wrong anyways, lol), but in your while loop around line 82 you have all the conditions responding to a string, even thought you explicitly changed the input to an integer. if choice == "0" instead of if choice == 0: so I got a continual output of? ('\nSorry, but', 3, "isn't a valid choice.")? Now this does not get your program running the way you want it to, but it will start you off making the corrections you need. Just some things to think about, in line 113, when did you define class f? in line 102, what are you trying to do, and are you telling it the right thing? since you have 2 (or possibly more) critters you are taking care of, how does the player know which one he is feeding / talking to / playing with in your farmlet? Anyways best of luck in your program, sounds pretty cool... ? ---- What is it about you... that intrigues me so? ________________________________ From: Alexandre Conrad To: David Merrick Cc: tutor at python.org Sent: Wednesday, June 22, 2011 6:48 PM Subject: Re: [Tutor] Class methods David, 2011/6/22 David Merrick : > ??????? # listen to your critter > ??????? elif choice == "1": > ??????????? for critter in farmlet: > ??????????????? farmlet.talk() You want to call .talk() on your "critter" instance which has the .talk() method, not on farmlet (which is a list as the error message states) > Traceback (most recent call last): > ? File "I:/Python/programs/critter_farm4.py", line 117, in > ??? main() > ? File "I:/Python/programs/critter_farm4.py", line 103, in main > ??? farmlet.talk() > AttributeError: 'list' object has no attribute 'talk' You will probably have a problem when calling talk() because it references to the "farmlet" variable which doesn't exist in the scope of your .talk() method. HTH, -- Alex | twitter.com/alexconrad _______________________________________________ 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 Jun 23 03:16:20 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 23 Jun 2011 02:16:20 +0100 Subject: [Tutor] Class methods References: <1308787824.77859.YahooMailNeo@web130201.mail.mud.yahoo.com> Message-ID: "michael scott" wrote > you are using python 3 by your print statements, so I > don't think you need the int() around your input, Yes he does because in Python 3 input is the same as raw_input in Python 2 > even in python.2x input() was safe for numbers I believe > (the whole list will rip my throat out if I'm wrong anyways rip, rip, rip. :-) In Python 2 input could be used for numbers but it was not "safe", which is why input was effectively removed in Python 3 and raw_input renamed to input. In Python 2 input() evaluated whatever was typed as a Python expression which made it very unsafe. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Jun 23 03:38:29 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 23 Jun 2011 02:38:29 +0100 Subject: [Tutor] Class methods References: Message-ID: "David Merrick" wrote > Can someone show me how to code this correctly please? We've been doing that but you are still making some very basic mistakes which reflect a deep misunderastanding of what you are doing. You really should take several steps back and review the use of variables and functions and then reread the introductory material on classes and objects. Until you get the basics right you will struggle and even if somebody fixes all the issues in this code, the minute you try another program all the same problems will bite you. That having been said I'll make some comments: > class Critter(object): > > """A virtual pet""" > def __init__(self, name, hunger = 0, boredom = 0): > self.name = name > self.hunger = hunger > self.boredom = boredom This is OK. > # __ denotes private method > def __pass_time(self): > self.hunger += 1 > self.boredom += 1 > self.__str__() The last line does nothing useful. (It prints stuff just now but that's because of a conceptual fault in your str method. What you should really be saying here is: print (self) > def __str__(self): > print("Hunger is",self.hunger, "Boredom is " ,self.boredom) > print("Unhappines is ",self.hunger + self.boredom," and Mood > is > ",self.mood) __str__ methods are supposed to return a string which can be used (or printed) by other code. They should not print anything themselves. This should do something like: return """Hunger is %s, Boredom is %s Unhappines is %s and Mood is%s""" % ( self.hunger, self.boredom, self.hunger+self.boredom, self.mood) > @property > def mood(self): > unhappiness = self.hunger + self.boredom > if unhappiness < 5: > m = "happy" > elif 5 <= unhappiness <= 10: > m = "okay" > elif 11 <= unhappiness <= 15: > m = "frustrated" > else: > m = "mad" > return m OK > def talk(self): > for critter in farmlet: > print("I'm", self.name, "and I feel", self.mood, > "now.\n") > self.__pass_time() Problem: What is farmlet here? There is no farmlet in the method. There is no self.farmlet you can access. So now your class is tied to the external farmlet variable in the global scope, making your class pretty much useless in any other context. Also it will print the same message as many times as there are critters in farmlet - 2 in this case. But the message won't change because self still only applies to the current object. You are iterating over the critters in your main() function, you don't need to do it inside the critter itself. Each critter should only comment on its own state. I'd also prefer that this returned a string too because putting print statements inside methods limits the usefulness of the class. How would it work in a GUI version for example? Better to return a string and print that where you call it. > def eat(self): > food = int(input("Enter how much food you want to feed your > critter: > ")) > print("Brruppp. Thank you.") > self.hunger -= food > # hunger = 0 at iniatition > # self.hunger = self.boredom - food > if self.hunger < 0: > self.hunger = 0 > self.__pass_time() OK, I think > def play(self): > fun = int(input("Enter how much fun you want your critter to > have: > ")) > print("Wheee!") > self.boredom -= fun > # boredom = 0 at iniatition > # self.boredom = self.boredom - fun > if self.boredom < 0: > self.boredom = 0 > self.__pass_time() OK, I think > def main(): > crit1 = Critter("Sweetie") > crit2 = Critter("Dave") > farmlet = [crit1,crit2] OK so far, we have a list with two Critters > choice = None > while choice != "0": > print \ > (""" > Critter Caretaker > > 0 - Quit > 1 - Listen to your critter > 2 - Feed your critter > 3 - Play with your critter > """) > > choice = input("Choice: ") > print() Also OK we now have a choice and a loop. > if choice == "0": > print("Good-bye.") And we exit so the program eventually stops, which is good. > elif choice == "1": > for critter in farmlet: > farmlet.talk() But here we are asking the list to do stuiff which is not good. It is the critters that talk. So you need to send talk() to the critter not the list: for critter in farmlet: critter.talk() > # feed your critter > elif choice == "2": > farmlet.eat() Again lists can't eat, you need to feed weither an individual crittter - get the user to choose which? - or feed all your critters using the same code pattern as for talk above. > # play with your critter > elif choice == "3": > f.play(farmlet) You don't have an f and you don't now have a play method or function that takes a farmlet as an argument. Again you need the same pattern as above, call the play() method of each critter in farmlet, or choose a critter to play with. > # some unknown choice > else: > print("\nSorry, but", choice, "isn't a valid choice.") > Traceback (most recent call last): > File "I:/Python/programs/critter_farm4.py", line 117, in > main() > File "I:/Python/programs/critter_farm4.py", line 103, in main > farmlet.talk() > AttributeError: 'list' object has no attribute 'talk' See the comments above. You really need to think about the type of each variable you are using and what operations it supports. farmlet is a list. lists don't talk. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From ladymcse2000 at gmail.com Thu Jun 23 05:32:22 2011 From: ladymcse2000 at gmail.com (Becky Mcquilling) Date: Wed, 22 Jun 2011 20:32:22 -0700 Subject: [Tutor] Using os.path.walk Message-ID: I have a bunch of files I need to remove in dirs and subdirs when they are older than 7 days. I was looking at os.path.walk, to recurse the directories, but I'm having some difficulties with getting it to return the directory names or find examples of it's use for something like this. So far, I am trying to get it to just list the files in the directories and subdirs as such: def file_list(a, dir, files): print (dir): os.path.walk('/etc', dir_list, None) Ultimately, I want it to find to stat mtime and just list, then remove the files and directories, older than the seven days, but I can't seem to get past just returning a list of files correctly. Are there some clear examples that someone can point me to? Becky Here is a partial output of what I'm returning: /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/e /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/t /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/c / /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/m /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/a /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/i /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/l / /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/D /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/e /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/f /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/a /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/u /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/l /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/t /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/M /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/e /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/s /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/s /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/a /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/g /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/e /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/s /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/. /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/b /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/u /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/n /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/d /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/l /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/e / /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/C /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/o /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/n /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/t /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/e /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/n /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/t /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/s / /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/R /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/e /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/s /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/o /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/u /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/r /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/c /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/e /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/s / /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/F /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/r /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/e /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/n /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/c /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/h /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/. /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/l /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/p /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/r /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/o /etc/mail/DefaultMessages.bundle/Contents/Resources/French.lproj/j /etc/mail/DefaultMessages.bundle/Contents/Resources/German.lproj / /etc/mail/DefaultMessages.bundle/Contents/Resources/German.lproj/e /etc/mail/DefaultMessages.bundle/Contents/Resources/German.lproj/t /etc/mail/DefaultMessages.bundle/Contents/Resources/German.lproj/c / /etc/mail/DefaultMessages.bundle/Contents/Resources/German.lproj/m /etc/mail/DefaultMessages.bundle/Contents/Resources/German.lproj/a /etc/mail/DefaultMessages.bundle/Contents/Resources/German.lproj/i /etc/mail/DefaultMessages.bundle/Contents/Resources/German.lproj/l / /etc/mail/DefaultMessages.bundle/Contents/Resources/German.lproj/D /etc/mail/DefaultMessages.bundle/Contents/Resources/German.lproj/e -------------- next part -------------- An HTML attachment was scrubbed... URL: From kushal.kumaran+python at gmail.com Thu Jun 23 07:19:53 2011 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Thu, 23 Jun 2011 10:49:53 +0530 Subject: [Tutor] Using os.path.walk In-Reply-To: References: Message-ID: On Thu, Jun 23, 2011 at 9:02 AM, Becky Mcquilling wrote: > I have a bunch of files I need to remove in dirs and subdirs when they are > older than 7 days. > I was looking at os.path.walk, to recurse the directories, but I'm having > some difficulties with getting it to return the directory names or find > examples of it's use for something like this. > So far, I am trying to get it to just list the files in the directories and > subdirs as such: > def file_list(a, dir, files): > ? print (dir): > os.path.walk('/etc', dir_list, None) > Ultimately, I want it to find to stat mtime and just list, then remove the > files and directories, older than the seven days, but I can't seem to get > past just returning a list of files correctly. > Are there some clear examples that someone can point me to? > Becky os.path.walk is deprecated in favour of os.walk. There are a couple of examples[1] in the documentation. The second example shows how to remove everything under a directory. You should be able to modify it to remove files that satisfy your criteria. The os.path.getmtime function[2] gets the mtime of a file. [1] http://docs.python.org/library/os.html#os.walk [2] http://docs.python.org/library/os.path.html#os.path.getmtime -- regards, kushal From norman at khine.net Thu Jun 23 23:01:34 2011 From: norman at khine.net (Norman Khine) Date: Thu, 23 Jun 2011 23:01:34 +0200 Subject: [Tutor] set the BETWEEN range in the SQL query using the python datetime function Message-ID: hello, i have this code http://pastie.org/2112997 but i am not sure how to make the date range so that i get a list based on the daily totals not the results i am now getting: (2L, Decimal('173.958344'), Decimal('159.966349')) 2011-06-23 00:00:00 2011-06-23 23:59:59 (2L, Decimal('173.958344'), Decimal('159.966349')) 2011-06-22 00:00:00 2011-06-23 23:59:59 (6L, Decimal('786.816548'), Decimal('744.840562')) 2011-06-21 00:00:00 2011-06-23 23:59:59 (12L, Decimal('1410.674749'), Decimal('1326.722775')) 2011-06-20 00:00:00 2011-06-23 23:59:59 (14L, Decimal('1577.628295'), Decimal('1476.683527')) 2011-06-19 00:00:00 2011-06-23 23:59:59 (15L, Decimal('1634.608277'), Decimal('1526.667511')) 2011-06-18 00:00:00 2011-06-23 23:59:59 (18L, Decimal('2015.542555'), Decimal('1886.613796')) 2011-06-17 00:00:00 2011-06-23 23:59:59 (21L, Decimal('2306.470462'), Decimal('2156.553710')) 2011-06-16 00:00:00 2011-06-23 23:59:59 (25L, Decimal('2574.386376'), Decimal('2396.485633')) 2011-06-15 00:00:00 2011-06-23 23:59:59 (27L, Decimal('2878.338279'), Decimal('2686.445540')) 2011-06-14 00:00:00 2011-06-23 23:59:59 the problem is that i am unsure how best to set the BETWEEN range in the SQL query using the python datetime function. cheers norman -- ??? ?o? ?u???d ??,no? ?ou pu? ???o?? ? ?oo? ? ???? s? '?ln?????p s? ???? ?u?op ?p?sdn p,u?n? p??o? ??? ??s no? '?u???? s???? ??? pu? '?u??uo? ?q s,??? ??? %>>> "".join( [ {'*':'@','^':'.'}.get(c,None) or chr(97+(ord(c)-83)%26) for c in ",adym,*)&uzq^zqf" ] ) From sigzero at gmail.com Fri Jun 24 03:15:16 2011 From: sigzero at gmail.com (Robert) Date: Thu, 23 Jun 2011 21:15:16 -0400 Subject: [Tutor] decorators Message-ID: Is there a good tutorial out there somewhere about decorators? Google doesn't bring up much. -- Robert From steve at pearwood.info Fri Jun 24 05:05:23 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 24 Jun 2011 13:05:23 +1000 Subject: [Tutor] decorators In-Reply-To: References: Message-ID: <4E03FEF3.6050408@pearwood.info> Robert wrote: > Is there a good tutorial out there somewhere about decorators? Google > doesn't bring up much. > Define "good" :) I'm interested in what you think about this article: http://www.artima.com/weblogs/viewpost.jsp?thread=240808 Personally, I think it's filled with jargon that will be alien to most Python coders, but otherwise interesting. Here's my cheap introduction to decorators... Before you understand decorators, you have to understand two things about Python: (1) Functions are "first class objects"; (2) and therefore you can write "factory functions". Everything else is just a bonus. What I mean by "first class" is best explained by giving an example of the opposite, second class objects. In some languages, functions are "special", and by special I mean they are more restricted. You cannot (easily, or at all) pass a function as an argument to another function, or give it a new name. This makes a lot of code hard to write. For instance, you might want to create a Grapher application, that lets the user draw the graph of some function. The basic algorithm would be something like this: def grapher(function, low, high, step): for x in range(low, high, step): y = function(x) draw_pixel(x, y) # draw a pixel on the graph, somehow... This is easy in Python, but very hard in languages where functions are second class. Because they are second class, you cannot pass them as arguments: grapher(math.sin, 0, 100, 1) is not allowed in some languages, but is allowed in Python. One consequence of this is the idea of "factory functions" is allowed. You can write a function which builds new functions, and returns them: >>> def factory(x): ... def inner(arg): ... return arg + x ... return inner # return the function object itself ... >>> plusone = factory(1) >>> plustwo = factory(2) >>> >>> plusone(23) 24 Decorators are a special type of factory function. They take as their argument a function, and then modify, wrap, or replace the function to perform special processing. Because the decorator itself is a function, anything you can do in Python, you can do in a decorator. The only limitation is that it must take a single argument, expected to be a function. (Or a class, in newer versions of Python.) Everything else is up to you! "Decorator syntax" is the special syntax you often see: @decorator def spam(): pass is syntactic sugar for the longer version: def spam(): pass spam = decorator(spam) What are decorators good for? The most common use is to *wrap* the function so as to eliminate boilerplate code. Suppose you have a bunch of functions that look like this: def func(arg): if isinstance(arg, int) and arg > 0: arg = min(arg, 1000) do stuff else: raise ValueError('bad argument') def func2(arg): if isinstance(arg, int) and arg > 0: arg = min(arg, 1000) do different stuff else: raise ValueError('bad argument') def func3(arg): if isinstance(arg, int) and arg > 0: arg = min(arg, 1000) do something else else: raise ValueError('bad argument') All of the functions go through the same boilerplate at the beginning and end, testing for a valid argument, raising an error if not, adjusting the argument value... Only the "do stuff" parts are different. This is a lot of duplicated code. We can reduce the duplication, making it easier to maintain and test, by moving all the common code into one place: def test_argument(func): def inner(arg): if not (isinstance(arg, int) and arg > 0): raise ValueError('bad argument') arg = min(arg, 1000) return func(arg) return inner @test_argument def func(arg): do stuff @test_argument def func2(arg): do different stuff @test_argument def func3(arg): do something else again The common code (the boilerplate) is now inside the decorator. The decorator takes a function as an argument, wraps it with an inner function that calls the common boilerplate code, tests the argument, raises an error if needed, and returns the result of calling the unique "do stuff" part. -- Steven From vincentbalmori at yahoo.com Fri Jun 24 08:32:31 2011 From: vincentbalmori at yahoo.com (Vincent Balmori) Date: Thu, 23 Jun 2011 23:32:31 -0700 (PDT) Subject: [Tutor] Trivia Message-ID: <31917610.post@talk.nabble.com> I have to improve the trivia_challenge program so each question has a different point value. I added a point into the text file after each category line, so the next_block() can call it. Whenever the program calculates the 'score = point' in main() it comes up with "TypeError: unsupported operand type(s) for +=: 'int' and 'str' " The problem is I am having trouble changing "point = next_line(the_file)" in the next_block() to be an int type. http://old.nabble.com/file/p31917610/trivia_challenge2.py trivia_challenge2.py http://old.nabble.com/file/p31917610/trivia.txt trivia.txt -- View this message in context: http://old.nabble.com/Trivia-tp31917610p31917610.html Sent from the Python - tutor mailing list archive at Nabble.com. From vincentbalmori at yahoo.com Fri Jun 24 08:37:37 2011 From: vincentbalmori at yahoo.com (Vincent Balmori) Date: Thu, 23 Jun 2011 23:37:37 -0700 (PDT) Subject: [Tutor] Trivia In-Reply-To: <31917610.post@talk.nabble.com> References: <31917610.post@talk.nabble.com> Message-ID: <31917637.post@talk.nabble.com> ***ignore the "point = point" line in the next_block() function. -- View this message in context: http://old.nabble.com/Trivia-tp31917610p31917637.html Sent from the Python - tutor mailing list archive at Nabble.com. From vincentbalmori at yahoo.com Fri Jun 24 08:56:56 2011 From: vincentbalmori at yahoo.com (Vincent Balmori) Date: Thu, 23 Jun 2011 23:56:56 -0700 (PDT) Subject: [Tutor] Trivia In-Reply-To: <31917637.post@talk.nabble.com> References: <31917610.post@talk.nabble.com> <31917637.post@talk.nabble.com> Message-ID: <31917701.post@talk.nabble.com> <<>> It's working fine now with the scoring, but now at the end of the program for some reason I get this error message: Traceback (most recent call last): File "/Users/vincentbalmori/Desktop/Python/py3e_source/chapter07/trivia_challenge2.py", line 83, in main() File "/Users/vincentbalmori/Desktop/Python/py3e_source/chapter07/trivia_challenge2.py", line 76, in main category, point, question, answers, correct, explanation = next_block(trivia_file) File "/Users/vincentbalmori/Desktop/Python/py3e_source/chapter07/trivia_challenge2.py", line 27, in next_block point = int(next_line(the_file)) ValueError: invalid literal for int() with base 10: '' -- View this message in context: http://old.nabble.com/Trivia-tp31917610p31917701.html Sent from the Python - tutor mailing list archive at Nabble.com. From andreengels at gmail.com Fri Jun 24 09:13:02 2011 From: andreengels at gmail.com (Andre Engels) Date: Fri, 24 Jun 2011 09:13:02 +0200 Subject: [Tutor] Trivia In-Reply-To: <31917701.post@talk.nabble.com> References: <31917610.post@talk.nabble.com> <31917637.post@talk.nabble.com> <31917701.post@talk.nabble.com> Message-ID: On Fri, Jun 24, 2011 at 8:56 AM, Vincent Balmori wrote: > > << > point = int(next_line(the_file)) > > If x is a string that can be interpreted as an integer number, int(x) is > that integer number; if the string is not the representation of an integer, > this will lead to a ValueError. > > -- > Andr? Engels, andreengels at gmail.com>>> > > > It's working fine now with the scoring, but now at the end of the program > for some reason I get this error message: > > Traceback (most recent call last): > File > > "/Users/vincentbalmori/Desktop/Python/py3e_source/chapter07/trivia_challenge2.py", > line 83, in > main() > File > > "/Users/vincentbalmori/Desktop/Python/py3e_source/chapter07/trivia_challenge2.py", > line 76, in main > category, point, question, answers, correct, explanation = > next_block(trivia_file) > File > > "/Users/vincentbalmori/Desktop/Python/py3e_source/chapter07/trivia_challenge2.py", > line 27, in next_block > point = int(next_line(the_file)) > ValueError: invalid literal for int() with base 10: '' > > The important thing in such a case is reading the error message and the last line in the error trace. In this case the error message is: ValueError: invalid literal for int() with base 10: '' This means that the int() function is being called with something that is not an integer - it even says what that something is, namely '' - that is, the empty string. Apparently at some time you come to the line point = int(next_line(the_file)) when next_line(the_file) is the empty string. -- Andr? Engels, andreengels at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Jun 24 09:34:54 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 24 Jun 2011 08:34:54 +0100 Subject: [Tutor] Trivia References: <31917610.post@talk.nabble.com> <31917637.post@talk.nabble.com> <31917701.post@talk.nabble.com> Message-ID: "Vincent Balmori" wrote > It's working fine now with the scoring, but now at the end of the > program > for some reason I get this error message: > "/Users/vincentbalmori/Desktop/Python/py3e_source/chapter07/trivia_challenge2.py", > line 27, in next_block > point = int(next_line(the_file)) > ValueError: invalid literal for int() with base 10: '' Thats because after the last question you try to read another block and don't check anywhere whether you actually read anything. Your next_block code just assumes there will always be valid data there, but at the end of the file there won't be. You get away with category being blank because replace() doesn't complain. But int() does. Your whole approach is very fragile in this respect, it only takes one small mistake in the data to wreck your program,. Somethjing like a config file format would be much more robust (and readable) the config reader module would make sure you got what you expected back. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From vincentbalmori at yahoo.com Fri Jun 24 09:58:30 2011 From: vincentbalmori at yahoo.com (Vincent Balmori) Date: Fri, 24 Jun 2011 00:58:30 -0700 (PDT) Subject: [Tutor] Trivia In-Reply-To: References: <31917610.post@talk.nabble.com> <31917637.post@talk.nabble.com> <31917701.post@talk.nabble.com> Message-ID: <31917979.post@talk.nabble.com> "Your whole approach is very fragile in this respect, it only takes one small mistake in the data to wreck your program,. Somethjing like a config file format would be much more robust (and readable) the config reader module would make sure you got what you expected back. " Can you please explain more on what you mean by this? Alan Gauld wrote: > > > "Vincent Balmori" wrote > >> It's working fine now with the scoring, but now at the end of the >> program >> for some reason I get this error message: >> > "/Users/vincentbalmori/Desktop/Python/py3e_source/chapter07/trivia_challenge2.py", >> line 27, in next_block >> point = int(next_line(the_file)) >> ValueError: invalid literal for int() with base 10: '' > > Thats because after the last question you try to read another > block and don't check anywhere whether you actually read > anything. Your next_block code just assumes there will > always be valid data there, but at the end of the file there > won't be. You get away with category being blank > because replace() doesn't complain. But int() does. > > Your whole approach is very fragile in this respect, it only > takes one small mistake in the data to wreck your program,. > Somethjing like a config file format would be much more > robust (and readable) the config reader module would make > sure you got what you expected back. > > 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 > > -- View this message in context: http://old.nabble.com/Trivia-tp31917610p31917979.html Sent from the Python - tutor mailing list archive at Nabble.com. From alan.gauld at btinternet.com Fri Jun 24 12:07:31 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 24 Jun 2011 11:07:31 +0100 Subject: [Tutor] Trivia References: <31917610.post@talk.nabble.com> <31917637.post@talk.nabble.com><31917701.post@talk.nabble.com> <31917979.post@talk.nabble.com> Message-ID: "Vincent Balmori" wrote > Can you please explain more on what you mean by this? >> "Your whole approach is very fragile in this respect, it only >> takes one small mistake in the data to wreck your program,. Your program relies on your data being exactly right. It only takes one missed newline, or one extra newline or a blank line or an extra question (maybe a cut n paste error when editing) or whatever to completely mess your program. > > Somethjing like a config file format would be much more > > robust (and readable) the config reader module would make > > sure you got what you expected back. " Read the ConfigParser module documentation to see what I mean. It treats your data like a Windows INI file and you can retrieve values using section/tag values. So in your case You could do, in pseudo code: cp = ConfigParser(filename) for section in cp.getSections(): question = cp.get(section, "question") points = int( cp.getsection,"points") ) q1 = cp.get(section,"q1") q2 = cp.get(section,"q2") etc.... And you can catch exceptions raised to detect errors. That way, if a value doesn't exist you find out about it and the parser handles all the navigation of the file. You could also use an XML format (or JSON or....) but Config Parser would be adequate for your needs. The data file would also be easier to read because the tags would make it clear: [Section Title] tag=value Becomes, for example: [On the Run With a Mammal] points=1 question=Let's say you turn state's evidence and need to "get on the lamb." If you wait /too long, what will happen? q1=You'll end up on the sheep q2=You'll end up on the cow q3=You'll end up on the goat q4=You'll end up on the emu answer=1 explantion=A lamb is just a young sheep.[The Godfather Will Get Down With You Now]...HTH,-- Alan GauldAuthor of the Learn to Program web sitehttp://www.alan-g.me.uk/ From __peter__ at web.de Fri Jun 24 12:18:19 2011 From: __peter__ at web.de (Peter Otten) Date: Fri, 24 Jun 2011 12:18:19 +0200 Subject: [Tutor] set the BETWEEN range in the SQL query using the python datetime function References: Message-ID: Norman Khine wrote: > hello, i have this code http://pastie.org/2112997 > > but i am not sure how to make the date range so that i get a list > based on the daily totals not the results i am now getting: > > (2L, Decimal('173.958344'), Decimal('159.966349')) 2011-06-23 00:00:00 > 2011-06-23 23:59:59 > (2L, Decimal('173.958344'), Decimal('159.966349')) 2011-06-22 00:00:00 > 2011-06-23 23:59:59 What should the result look like? Can you give a simplified example with input and output data? > the problem is that i am unsure how best to set the BETWEEN range in > the SQL query using the python datetime function. My guess is that you can move more of the problem from Python into SQL if you add a GROUP BY clause. From norman at khine.net Fri Jun 24 13:19:39 2011 From: norman at khine.net (Norman Khine) Date: Fri, 24 Jun 2011 13:19:39 +0200 Subject: [Tutor] set the BETWEEN range in the SQL query using the python datetime function In-Reply-To: References: Message-ID: thank you, it was simpler than what i was trying to do, here is the revised version: http://pastie.org/2115586 one thing i am getting an error is on like 103, in that if, i change (http://pastie.org/2115615): -plt.legend(('Income - GBP', 'Discounts', 'Google AdWords - GBP', 'Commission - %s GBP' % (total_commission)), +plt.legend(('Income - GBP', 'Discounts', 'Google AdWords - %s GBP', 'Commission - %s GBP' % (total_adwords, total_commission)), 'upper right', shadow=True) i get the following traceback: Traceback (most recent call last): File "commission.py", line 119, in plt.legend(('Income - GBP', 'Discounts', 'Google AdWords - %s GBP', 'Commission - %s GBP' % (total_adwords, total_commission)), TypeError: not all arguments converted during string formatting what am i missing? thanks norman On Fri, Jun 24, 2011 at 12:18 PM, Peter Otten <__peter__ at web.de> wrote: > Norman Khine wrote: > >> hello, i have this code http://pastie.org/2112997 >> >> but i am not sure how to make the date range so that i get a list >> based on the daily totals not the results i am now getting: >> >> (2L, Decimal('173.958344'), Decimal('159.966349')) 2011-06-23 00:00:00 >> 2011-06-23 23:59:59 >> (2L, Decimal('173.958344'), Decimal('159.966349')) 2011-06-22 00:00:00 >> 2011-06-23 23:59:59 > > What should the result look like? Can you give a simplified example with > input and output data? > >> the problem is that i am unsure how best to set the BETWEEN range in >> the SQL query using the python datetime function. > > My guess is that you can move more of the problem from Python into SQL if > you add a GROUP BY clause. > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- ??? ?o? ?u???d ??,no? ?ou pu? ???o?? ? ?oo? ? ???? s? '?ln?????p s? ???? ?u?op ?p?sdn p,u?n? p??o? ??? ??s no? '?u???? s???? ??? pu? '?u??uo? ?q s,??? ??? %>>> "".join( [ {'*':'@','^':'.'}.get(c,None) or chr(97+(ord(c)-83)%26) for c in ",adym,*)&uzq^zqf" ] ) From __peter__ at web.de Fri Jun 24 13:35:12 2011 From: __peter__ at web.de (Peter Otten) Date: Fri, 24 Jun 2011 13:35:12 +0200 Subject: [Tutor] set the BETWEEN range in the SQL query using the python datetime function References: Message-ID: Norman Khine wrote: > thank you, it was simpler than what i was trying to do, here is the > revised version: > > http://pastie.org/2115586 > > one thing i am getting an error is on like 103, in that if, i change > (http://pastie.org/2115615): > > -plt.legend(('Income - GBP', 'Discounts', 'Google AdWords - GBP', > 'Commission - %s GBP' % (total_commission)), > +plt.legend(('Income - GBP', 'Discounts', 'Google AdWords - %s GBP', > 'Commission - %s GBP' % (total_adwords, total_commission)), > 'upper right', shadow=True) > > i get the following traceback: > > Traceback (most recent call last): > File "commission.py", line 119, in > plt.legend(('Income - GBP', 'Discounts', 'Google AdWords - %s > GBP', 'Commission - %s GBP' % (total_adwords, total_commission)), > TypeError: not all arguments converted during string formatting > > what am i missing? 'Commission - %s GBP' % (total_adwords, total_commission)) Two items in the tuple but only one '%s' in the format string. You probably wanted ... 'Google AdWords - %s GBP' % total_adwords, 'Commission - %s GBP' % total_commission ... From cwitts at compuscan.co.za Fri Jun 24 13:31:17 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Fri, 24 Jun 2011 13:31:17 +0200 Subject: [Tutor] set the BETWEEN range in the SQL query using the python datetime function In-Reply-To: References: Message-ID: <4E047585.2070106@compuscan.co.za> On 2011/06/24 01:19 PM, Norman Khine wrote: > thank you, it was simpler than what i was trying to do, here is the > revised version: > > http://pastie.org/2115586 > > one thing i am getting an error is on like 103, in that if, i change > (http://pastie.org/2115615): > > -plt.legend(('Income - GBP', 'Discounts', 'Google AdWords - GBP', > 'Commission - %s GBP' % (total_commission)), > +plt.legend(('Income - GBP', 'Discounts', 'Google AdWords - %s GBP', > 'Commission - %s GBP' % (total_adwords, total_commission)), > 'upper right', shadow=True) > > i get the following traceback: > > Traceback (most recent call last): > File "commission.py", line 119, in > plt.legend(('Income - GBP', 'Discounts', 'Google AdWords - %s > GBP', 'Commission - %s GBP' % (total_adwords, total_commission)), > TypeError: not all arguments converted during string formatting > > what am i missing? > > thanks > > norman You've got 'Google AdWords - %s GBP' with no arguments and 'Commission - %s GBP' with 2 arguments. -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From norman at khine.net Fri Jun 24 13:53:46 2011 From: norman at khine.net (Norman Khine) Date: Fri, 24 Jun 2011 13:53:46 +0200 Subject: [Tutor] set the BETWEEN range in the SQL query using the python datetime function In-Reply-To: <4E047585.2070106@compuscan.co.za> References: <4E047585.2070106@compuscan.co.za> Message-ID: On Fri, Jun 24, 2011 at 1:31 PM, Christian Witts wrote: > On 2011/06/24 01:19 PM, Norman Khine wrote: > > thank you, it was simpler than what i was trying to do, here is the > revised version: > > http://pastie.org/2115586 > > one thing i am getting an error is on like 103, in that if, i change > (http://pastie.org/2115615): > > -plt.legend(('Income - GBP', 'Discounts', 'Google AdWords - GBP', > 'Commission - %s GBP' % (total_commission)), > +plt.legend(('Income - GBP', 'Discounts', 'Google AdWords - %s GBP', > 'Commission - %s GBP' % (total_adwords, total_commission)), > 'upper right', shadow=True) > > i get the following traceback: > > Traceback (most recent call last): > File "commission.py", line 119, in > plt.legend(('Income - GBP', 'Discounts', 'Google AdWords - %s > GBP', 'Commission - %s GBP' % (total_adwords, total_commission)), > TypeError: not all arguments converted during string formatting > > what am i missing? > > thanks > > norman > > You've got 'Google AdWords - %s GBP' with no arguments and 'Commission - %s > GBP' with 2 arguments. thanks > > -- > > Christian Witts > Python Developer > > -- ??? ?o? ?u???d ??,no? ?ou pu? ???o?? ? ?oo? ? ???? s? '?ln?????p s? ???? ?u?op ?p?sdn p,u?n? p??o? ??? ??s no? '?u???? s???? ??? pu? '?u??uo? ?q s,??? ??? %>>> "".join( [ {'*':'@','^':'.'}.get(c,None) or chr(97+(ord(c)-83)%26) for c in ",adym,*)&uzq^zqf" ] ) From ramit.prasad at jpmchase.com Fri Jun 24 16:25:00 2011 From: ramit.prasad at jpmchase.com (Prasad, Ramit) Date: Fri, 24 Jun 2011 10:25:00 -0400 Subject: [Tutor] decorators In-Reply-To: <4E03FEF3.6050408@pearwood.info> References: <4E03FEF3.6050408@pearwood.info> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2E36A5E21D@EMARC112VS01.exchad.jpmchase.net> Excellent explanation Steven; I understood the mechanical basics but this has made the reason behind it a lot clearer. If test_argument is only being passed the function how does it have access to the arguments? Or is that more syntactic sugar / abbreviation for explanation? def test_argument(func): def inner(arg): if not (isinstance(arg, int) and arg > 0): raise ValueError('bad argument') arg = min(arg, 1000) return func(arg) return inner @test_argument def func(arg): do stuff 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 python at bdurham.com Fri Jun 24 18:17:22 2011 From: python at bdurham.com (python at bdurham.com) Date: Fri, 24 Jun 2011 12:17:22 -0400 Subject: [Tutor] decorators In-Reply-To: <4E03FEF3.6050408@pearwood.info> References: <4E03FEF3.6050408@pearwood.info> Message-ID: <1308932242.9690.1466874789@webmail.messagingengine.com> Steven, > Here's my cheap introduction to decorators... Beautifully explained! Thank you, Malcolm (not the OP) From steve at pearwood.info Fri Jun 24 18:18:50 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 25 Jun 2011 02:18:50 +1000 Subject: [Tutor] decorators In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2E36A5E21D@EMARC112VS01.exchad.jpmchase.net> References: <4E03FEF3.6050408@pearwood.info> <0604E20B5F6F2F4784C9C8C71C5DD4DD2E36A5E21D@EMARC112VS01.exchad.jpmchase.net> Message-ID: <4E04B8EA.7080000@pearwood.info> Prasad, Ramit wrote: > Excellent explanation Steven; I understood the mechanical basics but this has made the reason behind it a lot clearer. > > If test_argument is only being passed the function how does it have access to the arguments? It doesn't. There are three functions involved. The first is the decorator, test_argument. It only receives one argument, the function func. The second is func itself, the original function before it is wrapped. The third is the inner function of the decorator, which wraps func. Only the last two functions, func and the wrapped func, ever see the function arguments. An example may make it more clear: def decorator(f): # Wrap function f. print("decorator is called with argument %s" % f) print("creating inner function...") def inner(x): print("wrapper function called with argument %s" % x) return f(x+100) print("now returning the wrapped function") return inner @decorator def func(x): print("original function called with argument %s" % x) func(1) func(2) func(3) When I execute that code, I get this output printed: decorator is called with argument creating inner function... now returning the wrapped function wrapper function called with argument 1 original function called with argument 101 wrapper function called with argument 2 original function called with argument 102 wrapper function called with argument 3 original function called with argument 103 -- Steven From vincentbalmori at yahoo.com Sat Jun 25 10:18:37 2011 From: vincentbalmori at yahoo.com (Vincent Balmori) Date: Sat, 25 Jun 2011 01:18:37 -0700 (PDT) Subject: [Tutor] Television Message-ID: <31925053.post@talk.nabble.com> The question for this is to make a program that simulates a TV by creating it as an object. The user should be able to to enter a channel and or raise a volume. Make sure that the Channel Number and Volume stay within valid ranges. Before I can even start correcting my code this error shows up. I thought I had already created the "tv" instance. http://old.nabble.com/file/p31925053/Television Television Traceback (most recent call last): File "/Users/vincentbalmori/Desktop/Python/py3e_source/chapter08/Television", line 83, in main() File "/Users/vincentbalmori/Desktop/Python/py3e_source/chapter08/Television", line 46, in main print(Television(tv.display)) NameError: global name 'tv' is not defined -- View this message in context: http://old.nabble.com/Television-tp31925053p31925053.html Sent from the Python - tutor mailing list archive at Nabble.com. From enalicho at gmail.com Sat Jun 25 10:36:10 2011 From: enalicho at gmail.com (Noah Hall) Date: Sat, 25 Jun 2011 09:36:10 +0100 Subject: [Tutor] Television In-Reply-To: <31925053.post@talk.nabble.com> References: <31925053.post@talk.nabble.com> Message-ID: On Sat, Jun 25, 2011 at 9:18 AM, Vincent Balmori wrote: > > The question for this is to make a program that simulates a TV by creating it > as an object. The user should be able to to enter a channel and or raise a > volume. Make sure that the Channel Number and Volume stay within valid > ranges. Before I can even start correcting my code this error shows up. I > thought I had already created the "tv" instance. > http://old.nabble.com/file/p31925053/Television Television > > Traceback (most recent call last): > ?File > "/Users/vincentbalmori/Desktop/Python/py3e_source/chapter08/Television", > line 83, in > ? ?main() > ?File > "/Users/vincentbalmori/Desktop/Python/py3e_source/chapter08/Television", > line 46, in main > ? ?print(Television(tv.display)) > NameError: global name 'tv' is not defined The problem is exactly as stated. There is no tv instance - it doesn't exist. You can't call Television(tv.display) because there's simply nothing called tv, and therefore it will not have a display method. You're also calling the method incorrectly - if tv did exist, and it had the method display, what you've done there is refer to the method, and not call it. So, if you print it, you'd get something like >>> def a(): ... pass ... >>> something = a >>> print something >>> This isn't what you want, so remember to include brackets. Instead, try - tv = Television() tv.display() Note how there's no print on the tv.display()? That's because inside Television.display, you've already told it to print, and told it to return nothing (therefore None, by default), for example - >>> def b(): ... print 'This is something' ... >>> print b() This is something None See how None is printed? Also, you should use better method functions - if you had called "vold" "volume_down" instead, there would be no need for your comment to explain what it is, and will result in less random guessing. HTH. From alan.gauld at btinternet.com Sat Jun 25 10:55:52 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 25 Jun 2011 09:55:52 +0100 Subject: [Tutor] Television References: <31925053.post@talk.nabble.com> Message-ID: "Vincent Balmori" wrote > Before I can even start correcting my code this error shows up. You will find it much easier to write programns if you do not write out the whole program and then try to debug it! Just write a single method at a time and get that working before trying to debug a whole complex aopplication. This code is fuill of errors whicvh will continually prevent you from running the code. I'll highlight a few. But as I said in your previous thread, you really need to read some more about the basics because your errors reveal a deep gap in your understanding of variables, data types and their operations. Only once you undertsand that thoroughly will you be successful with classes and objects, because in OOP you are defining new data types and operations. If you can't use the standard types you have little hope of using newly defined ones! Some examples: class Television(object): def __init__(tv, channel = range(0,10), volume = range(0,10)): tv.channel = channel tv.volume = volume def cha(tv, level = 1): while 0 >= tv.channel <=10: Here you store two range objects as your channel and volume attributes in init (In Python v 2 these would be lists but in Python 3 they are range objects). Then in cha() you try to compare them to a number, that won't work, they are incompatible types. Later you try to increment channel which agaion won't work. (And why you only increment channel and never decrement is a puzzle - and you ignore the level value read from the user?) Similar applies in volu() except you have two methods, one up one down. But you are still trying to apply integer operations to range objects. In various places you do this: if level > 10: int(input("\n That's too much! Choose another number?: ")) The user input is read, converted to an int then thrown away. You need to store it in a variable. Finally we come to the error message, it is in main(): def main(): print(Television(tv.display)) choice = None Notice you do not create a tv instance. You try to print an instance but in creating it you try to passs tv.display to the constructor, but tv does not exist aty that point. And even if you did succeed the instance would be immediately destroyed again because you are not storing it in a variable. You need to go back to basic data types and understand that concept. There is clearly something missing at the moment since you jkeep making the same mistakes over and over again.> thought I had already created the "tv" instance.> http://old.nabble.com/file/p31925053/Television Television You defined a class. You tried to create an instance of the class inside the print statement, but it nevergot that far.Try reading my tutorial topic on data - The Raw Materials - and then the OOP topic. Then go back to whatever tutorial you are currently following and see if it helps.-- Alan GauldAuthor of the Learn to Program web sitehttp://www.alan-g.me.uk/ From naheedcse at gmail.com Sat Jun 25 14:34:17 2011 From: naheedcse at gmail.com (naheed arafat) Date: Sat, 25 Jun 2011 18:34:17 +0600 Subject: [Tutor] Efficiency Message-ID: 1) >>> zip('How are you?'.split(' ')[::-1],'i am fine.'.split(' ')) [('you?', 'i'), ('are', 'am'), ('How', 'fine.')] >>> map(lambda i,j:(i,j),'How are you?'.split(' ')[::-1],'i am fine.'.split(' ')) [('you?', 'i'), ('are', 'am'), ('How', 'fine.')] Which one has better efficiency? 2) Is there any way easier to do the following? input: 'How are you' 'I am fine' output: 'you I are am How fine' solution: >>> ' '.join(reduce(lambda x,y:x+y, zip('How are you'.split(' ')[::-1], 'I am fine'.split(' ')))) -------------- next part -------------- An HTML attachment was scrubbed... URL: From adamlcarr at yahoo.com Sat Jun 25 15:18:14 2011 From: adamlcarr at yahoo.com (Adam Carr) Date: Sat, 25 Jun 2011 06:18:14 -0700 (PDT) Subject: [Tutor] Conceptual Question About Use of Python for Employee Training Program Message-ID: <1309007894.48569.YahooMailRC@web35301.mail.mud.yahoo.com> Good Morning: I am very new to Python but I am enjoying the learning process. I have a question about the application of Python to a problem at the industrial business where I work. My two main questions are: 1. Can Python be used to achieve the goals of the possible project? 2. Where are the best places to look (books, blogs, websites, etc.) for programming examples or modules that would help me begin to assemble and test some code? We currently have a Windows-PC based safety training program that was put together in MS Access around 2001. Access has evolved through several versions since then, as has the Windows OS, and the original author of the database has left the company. Originally designed to be deployed on an employee's desktop, the database is now restricted to two older PCs in the facility that run a version of Access compatible with the original. In short, the program is quickly becoming obsolete. The safety training program is a monthly exercise for all thirty nine employees at our location. The training is mandated by OSHA, and the subject matter is chosen based on the relevance to our processes. The program consists of the following general steps. 1. The employee is prompted to enter his or her employee identity number. 2. A confirmation is generated showing the employee name and other minor details, accessed from a simple list, to be sure the identity number and the person are correctly matched. This requires employee acknowledgment. 3. The employee freely selects a training subject from a list. 4. Once a subject is selected, a PowerPoint (or could be the OpenOffice Presentation) is launched. The training information is in the presentation. The employee can navigate forward or backward through the presentation, or they can exit. 5. Once the presentation is complete, or the employee has started and used ESC to exit from the presentation, they are prompted to take a quiz or exit the training program. 6. The quiz is a simple true-false ten question process based on the material in the training presentation. 7. The employee clicks on their answers to questions, the quiz is completed and scored. The employee must get at least eight of the ten questions correct to pass the topic. 8. Right now the Access version of the program prints the quiz, the employee's answers and the correct answers to the quiz, and the hard copy is signed and left with their supervisor. The printer is the default location set for the machine on which the training and quiz are completed. I think that the only reason the quizzes are printed is because no topic and quiz verification process was written into the program. In other words, an employee can take the time to review a topic, take and pass the associated quiz but if the printed copy is lost there is no way to verify that the employee completed anything. I would like to see a program that can be deployed as originally intended, on?individual PCs,?that can be more easily maintained and modified than the behemoth Access program we now have. We are running a Windows network with most production floor PCs using the latest version of XP and most individual desktops and laptops using Windows 7. I have the blessing of our network gods to pursue an open source solution because the options for this kind of program, which is tailored to individual locations, are few. The best approach the network folks suggested was a Lotus Notes database, which would work great I'm sure but the development cost is very, very high and each of the company's many manufacturing locations would require a slightly different version of the database. Thanks in advance for taking the time to read my long note. I appreciate any help or direction that can be offered. Adam -------------- next part -------------- An HTML attachment was scrubbed... URL: From quasipedia at gmail.com Sat Jun 25 16:08:52 2011 From: quasipedia at gmail.com (Mac Ryan) Date: Sat, 25 Jun 2011 16:08:52 +0200 Subject: [Tutor] Conceptual Question About Use of Python for Employee Training Program In-Reply-To: <1309007894.48569.YahooMailRC@web35301.mail.mud.yahoo.com> References: <1309007894.48569.YahooMailRC@web35301.mail.mud.yahoo.com> Message-ID: <20110625160852.0476cb63@jabbar> On Sat, 25 Jun 2011 06:18:14 -0700 (PDT) Adam Carr wrote: > Good Morning: > > I am very new to Python but I am enjoying the learning process. I > have a question about the application of Python to a problem at the > industrial business where I work. My two main questions are: > > 1. Can Python be used to achieve the goals of the possible project? > 2. Where are the best places to look (books, blogs, websites, etc.) > for programming examples or modules that would help me begin to > assemble and test some code? > > We currently have a Windows-PC based safety training program that was > put together in MS Access around 2001.... > Thanks in advance for taking the time to read my long note. I > appreciate any help or direction that can be offered. Hi Adam, from the way you describe your problem, to me the obvious answer would be "web application". This way you will be able to: 1. Make sure all employees will use the latest up-to-date training material and software version. 2. Have a central DB able to track employees' activity (this opens up the possibility for extra functionalities like sending a "gentle reminder e-mail" to those who are not taking tests frequently enough, statistics on what topics employees struggle most with, etc...) 3. Be platform independent. 5. Save time on developing the GUI (which - done properly - is a very time consuming part of desktop projects). That said, python is a great tool for web apps too. I personally looked a bit into Django (www.djangoproject.com), which is one of the python web frameworks and I was impressed by the speed you can prototype a fully working application. As for presenting the training material, for iteration #1 I would simply make them available as a download link. But in following iteration of the project I would also integrate them with the web (so as to make the entire application truly portable. I once used S5 for a project. Here you can see a presentation of it that is - coherentely - done with the standard presented: http://meyerweb.com/eric/tools/s5/s5-intro.html#slide1 However an alternative I did not experiment with is XOXO, which I read has python code examples available (see http://microformats.org/wiki/xoxo-sample-code-python) HTH, Mac. From quasipedia at gmail.com Sat Jun 25 16:11:36 2011 From: quasipedia at gmail.com (Mac Ryan) Date: Sat, 25 Jun 2011 16:11:36 +0200 Subject: [Tutor] Conceptual Question About Use of Python for Employee Training Program In-Reply-To: <1309007894.48569.YahooMailRC@web35301.mail.mud.yahoo.com> References: <1309007894.48569.YahooMailRC@web35301.mail.mud.yahoo.com> Message-ID: <20110625161136.0d4ddba8@jabbar> Just thought to google for "S5 python", and google came out with a lot of interesting links! :o /mac > Good Morning: > > I am very new to Python but I am enjoying the learning process. I > have a question about the application of Python to a problem at the > industrial business where I work. My two main questions are: > > 1. Can Python be used to achieve the goals of the possible project? > 2. Where are the best places to look (books, blogs, websites, etc.) > for programming examples or modules that would help me begin to > assemble and test some code? > > We currently have a Windows-PC based safety training program that was > put together in MS Access around 2001. Access has evolved through > several versions since then, as has the Windows OS, and the original > author of the database has left the company. Originally designed to > be deployed on an employee's desktop, the database is now restricted > to two older PCs in the facility that run a version of Access > compatible with the original. In short, the program is quickly > becoming obsolete. > > The safety training program is a monthly exercise for all thirty nine > employees at our location. The training is mandated by OSHA, and the > subject matter is chosen based on the relevance to our processes. The > program consists of the following general steps. > > 1. The employee is prompted to enter his or her employee identity > number. > > 2. A confirmation is generated showing the employee name and other > minor details, accessed from a simple list, to be sure the identity > number and the person are correctly matched. This requires employee > acknowledgment. > > 3. The employee freely selects a training subject from a list. > > 4. Once a subject is selected, a PowerPoint (or could be the > OpenOffice Presentation) is launched. The training information is in > the presentation. The employee can navigate forward or backward > through the presentation, or they can exit. > > 5. Once the presentation is complete, or the employee has started and > used ESC to exit from the presentation, they are prompted to take a > quiz or exit the training program. > > 6. The quiz is a simple true-false ten question process based on the > material in the training presentation. > > 7. The employee clicks on their answers to questions, the quiz is > completed and scored. The employee must get at least eight of the ten > questions correct to pass the topic. > > > 8. Right now the Access version of the program prints the quiz, the > employee's answers and the correct answers to the quiz, and the hard > copy is signed and left with their supervisor. The printer is the > default location set for the machine on which the training and quiz > are completed. I think that the only reason the quizzes are printed > is because no topic and quiz verification process was written into > the program. In other words, an employee can take the time to review > a topic, take and pass the associated quiz but if the printed copy is > lost there is no way to verify that the employee completed anything. > > > I would like to see a program that can be deployed as originally > intended, on?individual PCs,?that can be more easily maintained and > modified than the behemoth Access program we now have. We are running > a Windows network with most production floor PCs using the latest > version of XP and most individual desktops and laptops using Windows > 7. I have the blessing of our network gods to pursue an open source > solution because the options for this kind of program, which is > tailored to individual locations, are few. The best approach the > network folks suggested was a Lotus Notes database, which would work > great I'm sure but the development cost is very, very high and each > of the company's many manufacturing locations would require a > slightly different version of the database. > > Thanks in advance for taking the time to read my long note. I > appreciate any help or direction that can be offered. > > Adam From johnf at jfcomputer.com Sat Jun 25 16:59:28 2011 From: johnf at jfcomputer.com (John Fabiani) Date: Sat, 25 Jun 2011 07:59:28 -0700 Subject: [Tutor] Conceptual Question About Use of Python for Employee Training Program In-Reply-To: <1309007894.48569.YahooMailRC@web35301.mail.mud.yahoo.com> References: <1309007894.48569.YahooMailRC@web35301.mail.mud.yahoo.com> Message-ID: <201106250759.28457.johnf@jfcomputer.com> On Saturday, June 25, 2011 06:18:14 am Adam Carr wrote: > Good Morning: > > I am very new to Python but I am enjoying the learning process. I have a > question about the application of Python to a problem at the industrial > business where I work. My two main questions are: > > 1. Can Python be used to achieve the goals of the possible project? > 2. Where are the best places to look (books, blogs, websites, etc.) for > programming examples or modules that would help me begin to assemble and > test some code? > > We currently have a Windows-PC based safety training program that was put > together in MS Access around 2001. Access has evolved through several > versions since then, as has the Windows OS, and the original author of the > database has left the company. Originally designed to be deployed on an > employee's desktop, the database is now restricted to two older PCs in the > facility that run a version of Access compatible with the original. In > short, the program is quickly becoming obsolete. > > The safety training program is a monthly exercise for all thirty nine > employees at our location. The training is mandated by OSHA, and the > subject matter is chosen based on the relevance to our processes. The > program consists of the following general steps. > > 1. The employee is prompted to enter his or her employee identity number. > > 2. A confirmation is generated showing the employee name and other minor > details, accessed from a simple list, to be sure the identity number and > the person are correctly matched. This requires employee acknowledgment. > > 3. The employee freely selects a training subject from a list. > > 4. Once a subject is selected, a PowerPoint (or could be the OpenOffice > Presentation) is launched. The training information is in the presentation. > The employee can navigate forward or backward through the presentation, or > they can exit. > > 5. Once the presentation is complete, or the employee has started and used > ESC to exit from the presentation, they are prompted to take a quiz or > exit the training program. > > 6. The quiz is a simple true-false ten question process based on the > material in the training presentation. > > 7. The employee clicks on their answers to questions, the quiz is completed > and scored. The employee must get at least eight of the ten questions > correct to pass the topic. > > > 8. Right now the Access version of the program prints the quiz, the > employee's answers and the correct answers to the quiz, and the hard copy > is signed and left with their supervisor. The printer is the default > location set for the machine on which the training and quiz are completed. > I think that the only reason the quizzes are printed is because no topic > and quiz verification process was written into the program. In other > words, an employee can take the time to review a topic, take and pass the > associated quiz but if the printed copy is lost there is no way to verify > that the employee completed anything. > > > I would like to see a program that can be deployed as originally intended, > on individual PCs, that can be more easily maintained and modified than the > behemoth Access program we now have. We are running a Windows network with > most production floor PCs using the latest version of XP and most > individual desktops and laptops using Windows 7. I have the blessing of > our network gods to pursue an open source solution because the options for > this kind of program, which is tailored to individual locations, are few. > The best approach the network folks suggested was a Lotus Notes database, > which would work great I'm sure but the development cost is very, very > high and each of the company's many manufacturing locations would require > a slightly different version of the database. > > Thanks in advance for taking the time to read my long note. I appreciate > any help or direction that can be offered. > > Adam You might want to check out Dabo (www.dabodev.com). It was designed to replace Visual Fox Pro, Access, and Visual Basic desktop programs. Dabo does a very good job with dealing with the GUI and data. That of course assumes you want a desktop app. You could also use Django to create a web app. But if this is your first python project I think I'd go with a desktop app rather than deal with HTML, JavaSript, CSS, and python for the first project. Johnf From steve at pearwood.info Sat Jun 25 17:31:59 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 26 Jun 2011 01:31:59 +1000 Subject: [Tutor] Conceptual Question About Use of Python for Employee Training Program In-Reply-To: <1309007894.48569.YahooMailRC@web35301.mail.mud.yahoo.com> References: <1309007894.48569.YahooMailRC@web35301.mail.mud.yahoo.com> Message-ID: <4E05FF6F.5040200@pearwood.info> Adam Carr wrote: > Good Morning: > > I am very new to Python but I am enjoying the learning process. I have a > question about the application of Python to a problem at the industrial business > where I work. My two main questions are: > > 1. Can Python be used to achieve the goals of the possible project? Yes. > 2. Where are the best places to look (books, blogs, websites, etc.) for > programming examples or modules that would help me begin to assemble and test > some code? Do you know Python? If not, start with a tutorial or three. Google is your friend: google for "python tutorial" or "learn Python". Don't just read them, do them. Don't start with code. Start with a list of Functional Requirements. FRs should be technology independent, and preferably written for non-tech people. In other words: BAD: The training notes are opened in Powerpoint using a remote procedure call. GOOD: The training notes are shown to the user by the system. You already have the skeleton of an FR, your text below. Don't think the FR needs to be a huge, technical, ISO-standard document. A single page may be enough. You're just trying to identify the target you are aiming for, so you can tell whether or not you've hit it. Requirements includes things like: - How scalable does this need to be? Do we have 10 users, or 10 million? - Do we have to service remote users over the Internet? - What sort of security is needed? Do you need fear staff cheating? Don't be afraid to postpone functionality for the next version. You don't need all the bells and whistles from day one. In fact, I recommend that you start with the simplest application you possibly can do, and add extra features afterwards. Release early, release often. Get the Powers That Be to approve the FRs. Make sure that everyone (especially you!) understands that no changes will be accepted to functionality without it being put in writing. Now you have a stable target, rather than a moving one. Now write a technical design document: this is where you choose the technologies used. This is the point you start thinking about: - Do we need a database? Which one? SQLite? Postgres? Oracle? - A web app or a desktop app? - Which web framework, or GUI toolkit? - Do you have a server that can run this web app? - Do you need a server-class machine, or can it run off a cheap PC? Again, this may be quite short, although probably a bit longer than the FR. Don't think that you *need* to answer every question up front, although it is best if you can. Especially for small projects, you can leave gaps to be filled in later. But the gaps will guide you, by showing you what you need to learn before you can even start writing code. E.g. if you decide you need a web application, but you have no idea which web framework to use, you now know that you need to spend some time investigating frameworks. CherryPy, Django, Zope, Pylons... http://wiki.python.org/moin/WebFrameworks Once you know what sort of code you need to write, then you can start writing code. More comments below: [...] > 2. A confirmation is generated showing the employee name and other minor > details, accessed from a simple list, to be sure the identity number and the > person are correctly matched. This requires employee acknowledgment. You state that the employee name and details are "accessed from a simple list"? That's a technical design choice, not a requirement of the program. Perhaps it would be better to come from a database, or a Python dict, or an INI file. Who knows? The requirement is that the employee must acknowledge that he or she is who the system thinks he or she is based on the ID number. Everything else is design. > 3. The employee freely selects a training subject from a list. I would put it as, "freely selects a training subject from a menu of available subjects". This could be implemented as a list box GUI widget, or a set of checkboxes, or a set of push buttons, or by typing the name of the subject... the user interface is a design choice, and should be kept separate from the requirement that the employee somehow choose a subject. You should see the pattern now... keep design *choices* separate from functional *requirements*. Nothing you have stated seems impossible for Python. Far from it, I would think that Python is a good choice for this project. [...] > I would like to see a program that can be deployed as originally intended, > on individual PCs, that can be more easily maintained and modified than the > behemoth Access program we now have. We are running a Windows network with most > production floor PCs using the latest version of XP and most individual desktops > and laptops using Windows 7. I have the blessing of our network gods to pursue > an open source solution because the options for this kind of program, which is > tailored to individual locations, are few. The best approach the network folks > suggested was a Lotus Notes database, which would work great I'm sure but the > development cost is very, very high and each of the company's many manufacturing > locations would require a slightly different version of the database. Do your staff have access to a web browser? Will your network sys admins allow you to put a PC on the intranet running a web server (possibly on a different port)? If the answers to this are both Yes, I would recommend you use a web-based solution, using CherryPy as a lightweight webserver, Sqlite as the database, and only OpenOffice and a browser on the desktops. But of course my recommendation is meaningless, because I don't have your functional requirements! I might as well guess that you need a distributed application spread over thirty countries, capable of servicing tens of millions of users at once, with nine-nines uptime... *wink* Good luck, and enjoy! -- Steven From alan.gauld at btinternet.com Sat Jun 25 17:38:59 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 25 Jun 2011 16:38:59 +0100 Subject: [Tutor] Efficiency References: Message-ID: "naheed arafat" wrote > 1) >>>> zip('How are you?'.split(' ')[::-1],'i am fine.'.split(' ')) > [('you?', 'i'), ('are', 'am'), ('How', 'fine.')] >>>> map(lambda i,j:(i,j),'How are you?'.split(' ')[::-1],'i am > fine.'.split(' ')) > [('you?', 'i'), ('are', 'am'), ('How', 'fine.')] > > Which one has better efficiency? Why not just measure it with timeit? > 2) > Is there any way easier to do the following? > input: > 'How are you' > 'I am fine' > output: > 'you I are am How fine' > > solution: >>>> ' '.join(reduce(lambda x,y:x+y, zip('How are you'.split(' >>>> ')[::-1], > 'I am fine'.split(' ')))) That depends on your efiition of easier There are clearer solutions but they will be more verbose. Do you measure "easiness" by readability, or by typing effort? Or something else? Alan G From rick at niof.net Sat Jun 25 17:10:28 2011 From: rick at niof.net (Rick Pasotto) Date: Sat, 25 Jun 2011 11:10:28 -0400 Subject: [Tutor] BadPickleGet error Message-ID: <20110625151028.GB17375@niof.net> Traceback (most recent call last): File "/usr/share/rss2email/rss2email.py", line 748, in else: run() File "/usr/share/rss2email/rss2email.py", line 488, in run feeds, feedfileObject = load() File "/usr/share/rss2email/rss2email.py", line 439, in load feeds = pickle.load(feedfileObject) cPickle.BadPickleGet: 2574'8 Could someone please explain what the number(s) after 'BadPickleGet' mean? I assume the data file is corrupt but the question is can I fix it with an editor using that info? -- "We pay the debts of the last generation by issuing bonds payable by the next generation." -- Lawerence J.Peter Rick Pasotto rick at niof.net http://www.niof.net From steve at pearwood.info Sat Jun 25 17:42:34 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 26 Jun 2011 01:42:34 +1000 Subject: [Tutor] Efficiency In-Reply-To: References: Message-ID: <4E0601EA.2010208@pearwood.info> naheed arafat wrote: > 1) >>>> zip('How are you?'.split(' ')[::-1],'i am fine.'.split(' ')) > [('you?', 'i'), ('are', 'am'), ('How', 'fine.')] >>>> map(lambda i,j:(i,j),'How are you?'.split(' ')[::-1],'i am > fine.'.split(' ')) > [('you?', 'i'), ('are', 'am'), ('How', 'fine.')] > > Which one has better efficiency? Define "efficiency". Do you mean: - most efficient for the programmer to write? - easiest to read? - fastest for the compiler to compile? - uses the smallest number of characters in source code? - takes up the least space on disk when compiled? - runs fastest? - uses least memory? - easiest to maintain when you need to make changes? - easiest to debug when you discover a bug? Before trying to optimize your code, you should consider whether you are wasting your time or not. Chances are good that you are. You should consider these famous quotes about optimization: "More computing sins are committed in the name of efficiency (without necessarily achieving it) than for any other single reason - including blind stupidity." - W.A. Wulf "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%. A good programmer will not be lulled into complacency by such reasoning, he will be wise to look carefully at the critical code; but only after that code has been identified." - Donald Knuth "Bottlenecks occur in surprising places, so don't try to second guess and put in a speed hack until you have proven that's where the bottleneck is." - Rob Pike "The First Rule of Program Optimization: Don't do it. The Second Rule of Program Optimization (for experts only!): Don't do it yet." - Michael A. Jackson I believe that the only efficiency you should care about initially is the efficiency of *reading* (and to a lesser extent, writing) good, readable, easily maintained code. So long as you avoid common-sense mistakes, who cares if you can speed up your script from 2.5 milliseconds to 1.5 ms? Who is going to notice? (On the other hand, if your script really is too slow, that's a different story!) > 2) > Is there any way easier to do the following? > input: > 'How are you' > 'I am fine' > output: > 'you I are am How fine' > > solution: >>>> ' '.join(reduce(lambda x,y:x+y, zip('How are you'.split(' ')[::-1], > 'I am fine'.split(' ')))) That will work well for small amounts of data, say, a few hundred words or so. But for large amounts of data, it will be slow and inefficient. It's best to avoid such one-liners when possible, they tend to be slow. I would solve it like this: import itertools a = reversed('How are you'.split(' ')) b = 'I am fine'.split(' ') words = itertools.chain(*zip(a, b)) ' '.join(words) -- Steven From alexandre.conrad at gmail.com Sat Jun 25 19:30:00 2011 From: alexandre.conrad at gmail.com (Alexandre Conrad) Date: Sat, 25 Jun 2011 10:30:00 -0700 Subject: [Tutor] Efficiency In-Reply-To: References: Message-ID: 2011/6/25 naheed arafat : > 1) >>>> zip('How are you?'.split(' ')[::-1],'i am fine.'.split(' ')) > [('you?', 'i'), ('are', 'am'), ('How', 'fine.')] >>>> map(lambda i,j:(i,j),'How are you?'.split(' ')[::-1],'i am >>>> fine.'.split(' ')) > [('you?', 'i'), ('are', 'am'), ('How', 'fine.')] > > Which one has better efficiency? Use timeit. $ python -m timeit -s "q = 'How are you?'.split(' ')[::-1]; a = 'i am fine.'.split(' ')" "zip(q, a)" 1000000 loops, best of 3: 0.558 usec per loop $ python -m timeit -s "q = 'How are you?'.split(' ')[::-1]; a = 'i am fine.'.split(' '); func = lambda i,j:(i,j)" "map(func, q, a)" 1000000 loops, best of 3: 1.24 usec per loop So apparently the first one is twice as fast. Note that function calls in Python are expensive. It's very likely that the lambda call kills the performance here. > 2) > Is there any way easier to do the following? > input: > 'How are you' > 'I am fine' > output: > 'you I are am How fine' > > solution: >>>> ' '.join(reduce(lambda x,y:x+y, zip('How are you'.split(' ')[::-1], > 'I am fine'.split(' ')))) Sorry, I'm too lazy right now to look at it. :) -- Alex | twitter.com/alexconrad From __peter__ at web.de Sat Jun 25 19:53:38 2011 From: __peter__ at web.de (Peter Otten) Date: Sat, 25 Jun 2011 19:53:38 +0200 Subject: [Tutor] BadPickleGet error References: <20110625151028.GB17375@niof.net> Message-ID: Rick Pasotto wrote: > Traceback (most recent call last): > File "/usr/share/rss2email/rss2email.py", line 748, in > else: run() > File "/usr/share/rss2email/rss2email.py", line 488, in run > feeds, feedfileObject = load() > File "/usr/share/rss2email/rss2email.py", line 439, in load > feeds = pickle.load(feedfileObject) > cPickle.BadPickleGet: 2574'8 > > Could someone please explain what the number(s) after 'BadPickleGet' > mean? It's a key into a dictionary with previously retrieved objects. When you save the same object in a pickle it is written once, and for the second occurence a reference to the previously stored object is written: >>> import cPickle >>> import pickletools >>> data = ("alpha", "alpha") >>> cPickle.dumps(data) "(S'alpha'\np1\ng1\ntp2\n." >>> dump = _ >>> pickletools.dis(dump) 0: ( MARK 1: S STRING 'alpha' 10: p PUT 1 13: g GET 1 16: t TUPLE (MARK at 0) 17: p PUT 2 20: . STOP highest protocol among opcodes = 0 Now let's break it: >>> broken = dump.replace("g1", "g2") >>> cPickle.loads(broken) Traceback (most recent call last): File "", line 1, in cPickle.BadPickleGet: 2 > I assume the data file is corrupt but the question is can I fix it with > an editor using that info? Probably not. You could run your file through pickletools.dis() to find the location of the bad key >>> pickletools.dis(broken) 0: ( MARK 1: S STRING 'alpha' 10: p PUT 1 13: g GET 2 Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.6/pickletools.py", line 2006, in dis raise ValueError(errormsg) ValueError: memo key 2 has never been stored into but if you replace it with a valid one your data will still be messed up. Also, there are probably other errors in the file. Another idea, patching the Unpickler implemented in Python to replace bad references with a dummy object: >>> import pickle >>> class U(pickle.Unpickler): ... def my_load_get(self): ... try: ... obj = self.load_get() ... except KeyError: ... obj = "" ... self.append(obj) ... dispatch = pickle.Unpickler.dispatch.copy() ... dispatch[pickle.GET] = my_load_get ... >>> from cStringIO import StringIO >>> U(StringIO(broken)).load() ('alpha', '') suffers from the same problems. From __peter__ at web.de Sat Jun 25 20:05:38 2011 From: __peter__ at web.de (Peter Otten) Date: Sat, 25 Jun 2011 20:05:38 +0200 Subject: [Tutor] Efficiency References: Message-ID: naheed arafat wrote: > Is there any way easier to do the following? > input: > 'How are you' > 'I am fine' > output: > 'you I are am How fine' > > solution: >>>> ' '.join(reduce(lambda x,y:x+y, zip('How are you'.split(' ')[::-1], > 'I am fine'.split(' ')))) reversed(items) instead of items[::-1] generates the items on the fly. Other building blocks may be sum() and itertools.chain: >>> z = zip([1,2,3], "abc") >>> wanted = reduce(lambda x, y: x + y, z) >>> sum(z, ()) == wanted True >>> from itertools import chain >>> tuple(chain.from_iterable(z)) == wanted True From vincentbalmori at yahoo.com Sun Jun 26 03:02:31 2011 From: vincentbalmori at yahoo.com (Vincent Balmori) Date: Sat, 25 Jun 2011 18:02:31 -0700 (PDT) Subject: [Tutor] Television In-Reply-To: References: <31925053.post@talk.nabble.com> Message-ID: <31928968.post@talk.nabble.com> It's working better now. The problem I have left is that I have to set the channel and volume values in a range (for both I intend for 0-10). I thought the range() would be the choice, but probably I'm not using it right. Another one is for the tv.channel to hold a new value instead of just adding/subtracting the value and the only way I can think how is to use a list and then have the function replace the value each time. I'm sure there is a better way though. http://old.nabble.com/file/p31928968/TV TV Alan Gauld wrote: > > > "Vincent Balmori" wrote > >> Before I can even start correcting my code this error shows up. > > You will find it much easier to write programns if you do > not write out the whole program and then try to debug it! > Just write a single method at a time and get that working > before trying to debug a whole complex aopplication. > > This code is fuill of errors whicvh will continually prevent > you from running the code. I'll highlight a few. But as I > said in your previous thread, you really need to read > some more about the basics because your errors reveal > a deep gap in your understanding of variables, data types > and their operations. Only once you undertsand that thoroughly > will you be successful with classes and objects, because > in OOP you are defining new data types and operations. > If you can't use the standard types you have little hope > of using newly defined ones! > > Some examples: > > class Television(object): > def __init__(tv, channel = range(0,10), volume = range(0,10)): > tv.channel = channel > tv.volume = volume > def cha(tv, level = 1): > while 0 >= tv.channel <=10: > > Here you store two range objects as your channel and > volume attributes in init (In Python v 2 these would be > lists but in Python 3 they are range objects). > Then in cha() you try to compare them to a number, > that won't work, they are incompatible types. > Later you try to increment channel which agaion won't > work. (And why you only increment channel and never > decrement is a puzzle - and you ignore the level value > read from the user?) > > Similar applies in volu() except you have two methods, > one up one down. But you are still trying to apply > integer operations to range objects. > > > In various places you do this: > > if level > 10: > int(input("\n That's too much! Choose another number?: ")) > > The user input is read, converted to an int then thrown away. > You need to store it in a variable. > > Finally we come to the error message, it is in main(): > > def main(): > print(Television(tv.display)) > choice = None Notice you do not create a tv instance. You try to > print an instance but in creating it you try to passs tv.display to > the constructor, but tv does not exist aty that point. And even if you > did succeed the instance would be immediately destroyed again because > you are not storing it in a variable. You need to go back to basic > data types and understand that concept. There is clearly something > missing at the moment since you jkeep making the same mistakes over > and over again.> thought I had already created the "tv" instance.> > http://old.nabble.com/file/p31925053/Television Television You defined > a class. You tried to create an instance of the class inside the print > statement, but it nevergot that far.Try reading my tutorial topic on > data - The Raw Materials - and then the OOP topic. Then go back to > whatever tutorial you are currently following and see if it helps.-- > Alan GauldAuthor of the Learn to Program web > sitehttp://www.alan-g.me.uk/ > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- View this message in context: http://old.nabble.com/Television-tp31925053p31928968.html Sent from the Python - tutor mailing list archive at Nabble.com. From naheedcse at gmail.com Sun Jun 26 04:41:06 2011 From: naheedcse at gmail.com (naheed arafat) Date: Sun, 26 Jun 2011 08:41:06 +0600 Subject: [Tutor] Efficiency In-Reply-To: References: Message-ID: On Sat, Jun 25, 2011 at 9:38 PM, Alan Gauld wrote: > > "naheed arafat" wrote > > 1) >> >>> zip('How are you?'.split(' ')[::-1],'i am fine.'.split(' ')) >>>>> >>>> [('you?', 'i'), ('are', 'am'), ('How', 'fine.')] >> >>> map(lambda i,j:(i,j),'How are you?'.split(' ')[::-1],'i am >>>>> >>>> fine.'.split(' ')) >> [('you?', 'i'), ('are', 'am'), ('How', 'fine.')] >> >> Which one has better efficiency? >> > > Why not just measure it with timeit? > > > > 2) >> Is there any way easier to do the following? >> input: >> 'How are you' >> 'I am fine' >> output: >> 'you I are am How fine' >> >> solution: >> >>> ' '.join(reduce(lambda x,y:x+y, zip('How are you'.split(' ')[::-1], >>>>> >>>> 'I am fine'.split(' ')))) >> > > That depends on your efiition of easier > There are clearer solutions but they will be more verbose. > Do you measure "easiness" by readability, or by typing effort? > Or something else? > > Alan G > > > Here I meant the term "easier" by conceptually easier.. I mean any Conceptually neater way other than the following steps: for the given input: 1. ['you', 'are', 'How'] 2. ['I', 'am', 'fine'] 3. [('you', 'I'), ('are', 'am'), ('How', 'fine')] 4. ('you', 'I', 'are', 'am', 'How', 'fine') i.e applying + operator cumulatively. sorry for my english. > ______________________________**_________________ > 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 naheedcse at gmail.com Sun Jun 26 05:46:54 2011 From: naheedcse at gmail.com (naheed arafat) Date: Sun, 26 Jun 2011 09:46:54 +0600 Subject: [Tutor] Efficiency In-Reply-To: <4E0601EA.2010208@pearwood.info> References: <4E0601EA.2010208@pearwood.info> Message-ID: On Sat, Jun 25, 2011 at 9:42 PM, Steven D'Aprano wrote: > naheed arafat wrote: > >> 1) >> >>> zip('How are you?'.split(' ')[::-1],'i am fine.'.split(' ')) >>>>> >>>> [('you?', 'i'), ('are', 'am'), ('How', 'fine.')] >> >>> map(lambda i,j:(i,j),'How are you?'.split(' ')[::-1],'i am >>>>> >>>> fine.'.split(' ')) >> [('you?', 'i'), ('are', 'am'), ('How', 'fine.')] >> >> Which one has better efficiency? >> > > Define "efficiency". > > Do you mean: > > - most efficient for the programmer to write? > - easiest to read? > - fastest for the compiler to compile? > - uses the smallest number of characters in source code? > - takes up the least space on disk when compiled? > - runs fastest? > - uses least memory? > - easiest to maintain when you need to make changes? > - easiest to debug when you discover a bug? > > I meant "runs fastest" . Before trying to optimize your code, you should consider whether you are > wasting your time or not. Chances are good that you are. You should consider > these famous quotes about optimization: > > > "More computing sins are committed in the name of efficiency (without > necessarily achieving it) than for any other single reason - including blind > stupidity." - W.A. Wulf > > I don't know what is meant by computing sins.. would you please clarify in which cases optimization would be a waste of time? > "We should forget about small efficiencies, say about 97% of the time: > premature optimization is the root of all evil. Yet we should not pass up > our opportunities in that critical 3%. A good programmer will not be lulled > into complacency by such reasoning, he will be wise to look carefully at the > critical code; but only after that code has been identified." - Donald Knuth > > > "Bottlenecks occur in surprising places, so don't try to second guess and > put in a speed hack until you have proven that's where the bottleneck is." - > Rob Pike > > what is meant by Bottleneck? > "The First Rule of Program Optimization: Don't do it. The Second Rule of > Program Optimization (for experts only!): Don't do it yet." - Michael A. > Jackson > > I believe that the only efficiency you should care about initially is the > efficiency of *reading* (and to a lesser extent, writing) good, readable, > easily maintained code. So long as you avoid common-sense mistakes, who > cares if you can speed up your script from 2.5 milliseconds to 1.5 ms? Who > is going to notice? > > (On the other hand, if your script really is too slow, that's a different > story!) > > > > > 2) >> Is there any way easier to do the following? >> input: >> 'How are you' >> 'I am fine' >> output: >> 'you I are am How fine' >> >> solution: >> >>> ' '.join(reduce(lambda x,y:x+y, zip('How are you'.split(' ')[::-1], >>>>> >>>> 'I am fine'.split(' ')))) >> > > That will work well for small amounts of data, say, a few hundred words or > so. But for large amounts of data, it will be slow and inefficient. It's > best to avoid such one-liners when possible, they tend to be slow. > > I was learning the use of lambda. And as assignment (may be) doesn't work inside lambda's i tried such one-liners..but didn't know such one-liners are slow for huge data..thank you for your suggestion. I would solve it like this: > > import itertools > a = reversed('How are you'.split(' ')) > b = 'I am fine'.split(' ') > words = itertools.chain(*zip(a, b)) > ' '.join(words) > > > > -- > Steven > > > zip() takes sequences as argument.Isn't variable a an iterable object? the code didn't work. > ______________________________**_________________ > 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 Sun Jun 26 08:25:03 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 26 Jun 2011 16:25:03 +1000 Subject: [Tutor] Efficiency In-Reply-To: References: <4E0601EA.2010208@pearwood.info> Message-ID: <4E06D0BF.2030205@pearwood.info> Hello Naheed, You seem to have messed up your quoting. Text starting with a > is a quote, but in your reply, you have written text starting with > as if it were written by me. I have fixed the quoting in this reply, but please try to watch that. See below for more comments. naheed arafat wrote: > On Sat, Jun 25, 2011 at 9:42 PM, Steven D'Aprano wrote: [...] >> Define "efficiency". >> >> Do you mean: >> >> - most efficient for the programmer to write? >> - easiest to read? >> - fastest for the compiler to compile? >> - uses the smallest number of characters in source code? >> - takes up the least space on disk when compiled? >> - runs fastest? >> - uses least memory? >> - easiest to maintain when you need to make changes? >> - easiest to debug when you discover a bug? >> > I meant "runs fastest" . Why? Is it a race? Do you win a prize if your code runs in 0.001 second instead of 0.002 second? Be careful that you have a good reason for caring about "fastest", not just "fast enough". Writing the fastest code usually means that it: - uses more memory - is harder to write - is harder to read - is harder to debug - is harder to maintain You should be sure that you don't waste your time trying to speed up code that is fast enough. >> Before trying to optimize your code, you should consider whether you are >> wasting your time or not. Chances are good that you are. You should consider >> these famous quotes about optimization: >> >> >> "More computing sins are committed in the name of efficiency (without >> necessarily achieving it) than for any other single reason - including blind >> stupidity." - W.A. Wulf >> >> > I don't know what is meant by computing sins.. would you please clarify in > which cases optimization would be a waste of time? Optimization is nearly always a waste of time. Not always, but nearly. By "computing sins", he means "doing something you should not do". Examples: - writing hard to maintain code - writing code that is fragile instead of robust when it receives unexpected input - writing buggy code (it is astonishing how many tens of thousands of hours has been wasted by programmers trying to make code that doesn't work correctly run fast) - spending an hour to try to save one minute - spending time trying to optimize trivial, unimportant parts of the program, while leaving important parts slow - writing code that is actually SLOWER but thinking that it must be faster (what I call a pessimation, not an optimization) These are computing sins. Don't do them. >> "Bottlenecks occur in surprising places, so don't try to second guess and >> put in a speed hack until you have proven that's where the bottleneck is." - >> Rob Pike >> >> > what is meant by Bottleneck? A bottleneck is a place where progress slows because your actions are restricted. Consider water in a bottle: the bottle might be 7cm wide at the bottom, but where the water comes out, through the neck, it is only 1.5cm wide: ]+---------------------+ ]| \ ]| +---------+ ]| +---------+ ]| / ]+---------------------+ The speed at which you can pour water from the bottle depends on the width of the neck, not the width of the bottle. Making the bottle wider at the bottom won't speed up how fast you can pour water. [...] >> I would solve it like this: >> import itertools >> a = reversed('How are you'.split(' ')) >> b = 'I am fine'.split(' ') >> words = itertools.chain(*zip(a, b)) >> ' '.join(words) > > zip() takes sequences as argument.Isn't variable a an iterable object? the > code didn't work. zip takes any iterable as argument, not just sequences. It works for me in every version of Python between 2.4 and 3.2. Perhaps you should copy and paste the exact code you are running, and the error message you get, or the result you get. -- Steven From lisi.reisz at gmail.com Sun Jun 26 13:05:01 2011 From: lisi.reisz at gmail.com (Lisi) Date: Sun, 26 Jun 2011 12:05:01 +0100 Subject: [Tutor] Defining a "format string" Message-ID: <201106261205.01820.lisi.reisz@gmail.com> In the following excerpt from a program in the book I am following: print "If I add %d, %d, and %d I get %d." % ( my_age, my_height, my_weight, my_age + my_height + my_weight) is % ( my_age, my_height, my_weight, my_age + my_height + my_weight) the/a format string? If not, then I still haven't "got" it, and I would be very grateful if someone could define "format string" for me - preferably in words of one syllable, because I seem to be being a bit thick about this. :-( Lisi From enalicho at gmail.com Sun Jun 26 13:18:31 2011 From: enalicho at gmail.com (Noah Hall) Date: Sun, 26 Jun 2011 12:18:31 +0100 Subject: [Tutor] Defining a "format string" In-Reply-To: <201106261205.01820.lisi.reisz@gmail.com> References: <201106261205.01820.lisi.reisz@gmail.com> Message-ID: On Sun, Jun 26, 2011 at 12:05 PM, Lisi wrote: > In the following excerpt from a program in the book I am following: > > ? print "If I add %d, %d, and %d I get %d." % ( > ? ? ?my_age, my_height, my_weight, my_age + my_height + my_weight) > > is > > % ( > ? ? ?my_age, my_height, my_weight, my_age + my_height + my_weight) > > the/a format string? No. (my_age, my_height, my_weight, my_age + my_height + my_weight) are the values (variables in this case, but it could be direct values too) "If I add %d, %d, and %d I get %d." is the formatted string (what you want to see outputted as a string) So, say we had - my_age = 65 my_height = 185 my_weight = 11 Then what'd happen is - print "If I add %d, %d, and %d I get %d." % (65, 185, 11, 65 + 185 + 11) Notice how the values are actual values? The other text part is the format for the values to take inside a string, so you get - print "If I add 65, 185 and 11 I get 261" HTH From steve at pearwood.info Sun Jun 26 13:24:12 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 26 Jun 2011 21:24:12 +1000 Subject: [Tutor] Defining a "format string" In-Reply-To: <201106261205.01820.lisi.reisz@gmail.com> References: <201106261205.01820.lisi.reisz@gmail.com> Message-ID: <4E0716DC.5050400@pearwood.info> Lisi wrote: > In the following excerpt from a program in the book I am following: > > print "If I add %d, %d, and %d I get %d." % ( > my_age, my_height, my_weight, my_age + my_height + my_weight) > > is > > % ( > my_age, my_height, my_weight, my_age + my_height + my_weight) > > the/a format string? No. The format string is a string with the % codes. In this case, they are all %d codes: "If I add %d, %d, and %d I get %d." but there are other codes possible. The % symbol on its own is an operator, like + or * or / The part inside the brackets () is a tuple of values to insert into the format string. Putting the three together: target = "Hello %s." value = "Lisi" print target % value => prints "Hello Lisi." -- Steven From lisi.reisz at gmail.com Sun Jun 26 15:42:22 2011 From: lisi.reisz at gmail.com (Lisi) Date: Sun, 26 Jun 2011 14:42:22 +0100 Subject: [Tutor] Defining a "format string" In-Reply-To: <4E0716DC.5050400@pearwood.info> References: <201106261205.01820.lisi.reisz@gmail.com> <4E0716DC.5050400@pearwood.info> Message-ID: <201106261442.22784.lisi.reisz@gmail.com> Thanks, Noah and Steven. :-) On Sunday 26 June 2011 12:24:12 Steven D'Aprano wrote: > Lisi wrote: > > In the following excerpt from a program in the book I am following: > > > > print "If I add %d, %d, and %d I get %d." % ( > > my_age, my_height, my_weight, my_age + my_height + my_weight) > > > > is > > > > % ( > > my_age, my_height, my_weight, my_age + my_height + my_weight) > > > > the/a format string? > > No. The format string is a string with the % codes. In this case, they > are all %d codes: > > "If I add %d, %d, and %d I get %d." > > but there are other codes possible. > > The % symbol on its own is an operator, like + or * or / > > The part inside the brackets () is a tuple of values to insert into the > format string. Putting the three together: > > > target = "Hello %s." > value = "Lisi" > print target % value > > => prints "Hello Lisi." At least I had managed to pick up correctly that the format string needed a % symbol! So, if I have now understood correctly, a format string is a string containing at least one variable, and the variable(s) is/are preceded by the % symbol. Yes??? Lisi From enalicho at gmail.com Sun Jun 26 15:53:47 2011 From: enalicho at gmail.com (Noah Hall) Date: Sun, 26 Jun 2011 14:53:47 +0100 Subject: [Tutor] Defining a "format string" In-Reply-To: <201106261442.22784.lisi.reisz@gmail.com> References: <201106261205.01820.lisi.reisz@gmail.com> <4E0716DC.5050400@pearwood.info> <201106261442.22784.lisi.reisz@gmail.com> Message-ID: On Sun, Jun 26, 2011 at 2:42 PM, Lisi wrote: > Thanks, Noah and Steven. ?:-) > > On Sunday 26 June 2011 12:24:12 Steven D'Aprano wrote: >> Lisi wrote: >> > In the following excerpt from a program in the book I am following: >> > >> > ? ?print "If I add %d, %d, and %d I get %d." % ( >> > ? ? ? my_age, my_height, my_weight, my_age + my_height + my_weight) >> > >> > is >> > >> > % ( >> > ? ? ? my_age, my_height, my_weight, my_age + my_height + my_weight) >> > >> > the/a format string? >> >> No. The format string is a string with the % codes. In this case, they >> are all %d codes: >> >> "If I add %d, %d, and %d I get %d." >> >> but there are other codes possible. >> >> The % symbol on its own is an operator, like + or * or / >> >> The part inside the brackets () is a tuple of values to insert into the >> format string. Putting the three together: >> >> >> target = "Hello %s." >> value = "Lisi" >> print target % value >> >> => prints "Hello Lisi." > > At least I had managed to pick up correctly that the format string needed a % > symbol! > > So, if I have now understood correctly, a format string is a string containing > at least one variable, and the variable(s) is/are preceded by the % symbol. Well, sort of. Leaning more to the "no" side, but sort of. A format string is a string containing specifiers (placeholders, if you will) for values, including variables, but not the values themselves. The % symbol is a specifier. So, for example, %d specifies that something should be of type d which, in Python, is an int. The actual variables/values are the bit after the format string, and after the %. HTH. From enalicho at gmail.com Sun Jun 26 16:51:27 2011 From: enalicho at gmail.com (Noah Hall) Date: Sun, 26 Jun 2011 15:51:27 +0100 Subject: [Tutor] Television In-Reply-To: <31928968.post@talk.nabble.com> References: <31925053.post@talk.nabble.com> <31928968.post@talk.nabble.com> Message-ID: On Sun, Jun 26, 2011 at 2:02 AM, Vincent Balmori wrote: > > It's working better now. The problem I have left is that I have to set the > channel and volume values in a range (for both I intend for 0-10). I thought > the range() would be the choice, but probably I'm not using it right. I think the best way to do this is probably to set two properties - tv.channel_boundary and tv.volume_boundary, this is presuming that you don't want to allow the lower boundary to be changed. If you do, create an upper and lower boundary variable for each. >def channel_remote(tv, level = 1): > if tv.channel in range(0,10): Here, it'd be better if you used if tv.channel < 10: That way you're not wasting a whole list and a list search just to test if something is less than ten. Using the boundaries, that would be if tv.channel < tv.channel_boundary: There's also no need for this, not here, anyway. You should be testing in __init__, where the channel can be set incorrectly. > level = int(input("\n Which channel do you want to go up to: ")) Why have this when you allow level as an argument? It's a waste. > if 0 > level > 10: > int(input("\n That's not valid! Choose another channel: ")) > else: > tv.channel += level This is your second problem you've found, I guess? Well, how about this tv.channel = level Easy, right? :) > print("\n The channel is now:", tv.channel) > Another one is for the tv.channel to hold a new value instead of just > adding/subtracting the value and the only way I can think how is to use a > list and then have the function replace the value each time. I'm sure there > is a better way though. > http://old.nabble.com/file/p31928968/TV TV HTH From alan.gauld at btinternet.com Sun Jun 26 18:15:14 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 26 Jun 2011 17:15:14 +0100 Subject: [Tutor] Defining a "format string" References: <201106261205.01820.lisi.reisz@gmail.com><4E0716DC.5050400@pearwood.info> <201106261442.22784.lisi.reisz@gmail.com> Message-ID: "Lisi" wrote > So, if I have now understood correctly, a format string is a string > containing > at least one variable, and the variable(s) is/are preceded by the % > symbol. > Yes??? Umm, nearly... The format string contains format specifiers. They are not variables. The specifiers define the type of data to be inserted into the string as well as how the data will be formatted - hence the name. So you can specify how many decimal places for a float, whether numbers have leadig zeros, whether text is righ or left justified and more. (The new format specificiers in Python v3 are even more powerful) You can store a format string as a variable (as Steven demonstrated) and use it in several places to ensure consistent output. You can swupply the values to the format string by using variables (again, as Steven demonstrated). But they can also be literal values (as Noah demonstrated) so that no variables are used at all. You can also label format specifiers and then pass in a dictionary of values where the labels are the keys into the dictionary. This is very useful where the same values are used several times in a long string. For example you could have a set of standard letter templates into which you insert recipient data. You can then store the recipents as a list of dictionaries ( or even a dictionary of dictionaries!) and then do stuff like: for recipient in customer_list: print offer_letter % recipient Here is a small example: >>> p = {'name':'Alan', 'balance': 100, 'duration': 300} >>> msg = "\nHello %(name)s,\nWe haven't heard from you for >>> %(duration)s days.\nIf you come back we'll give you $10 off your >>> next order." >>> print msg % p Hello Alan, We haven't heard from you for 300 days. If you come back we'll give you $10 off your next order. >>> Notice I didn't need to use all the fields of p. The format operation only extracted the fields named in the format string. It will even work with classes if you implement a __getitem__() method HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From lisi.reisz at gmail.com Sun Jun 26 18:31:43 2011 From: lisi.reisz at gmail.com (Lisi) Date: Sun, 26 Jun 2011 17:31:43 +0100 Subject: [Tutor] Defining a "format string" In-Reply-To: References: <201106261205.01820.lisi.reisz@gmail.com> <201106261442.22784.lisi.reisz@gmail.com> Message-ID: <201106261731.43304.lisi.reisz@gmail.com> On Sunday 26 June 2011 17:15:14 Alan Gauld wrote: > "Lisi" wrote > Umm, nearly... > The format string contains format specifiers. They are not variables. > The specifiers define the type of data to be inserted into the string > as well as how the data will be formatted - hence the name. > > So you can specify how many decimal places for a float, whether > numbers have leadig zeros, whether text is righ or left justified and > more. > HTH, Definitely. I am very grateful. I have been unclear about this for some time and _think_that I have at last got it. The things I asked questions about were the things I either knew or thought that I had got wrong. I kept hoping that context would make things clear in the end, as indeed it often does. But on this subject it clearly didn't. So thanks for all the help. Lisi From vincentbalmori at yahoo.com Sun Jun 26 21:28:54 2011 From: vincentbalmori at yahoo.com (Vincent Balmori) Date: Sun, 26 Jun 2011 12:28:54 -0700 (PDT) Subject: [Tutor] Television In-Reply-To: References: <31925053.post@talk.nabble.com> <31928968.post@talk.nabble.com> Message-ID: <31932639.post@talk.nabble.com> I made in elif statement for the channel changer that works for it, but the volume systems system boundary does not the way I want it to. If the volume is 2 and I lower it by a value of 5, it will accept the volume at a negative number thus going past the boundary. The vice-versa for the high boundary as well. http://old.nabble.com/file/p31932639/TV.py TV.py Noah Hall-3 wrote: > > On Sun, Jun 26, 2011 at 2:02 AM, Vincent Balmori > wrote: >> >> It's working better now. The problem I have left is that I have to set >> the >> channel and volume values in a range (for both I intend for 0-10). I >> thought >> the range() would be the choice, but probably I'm not using it right. > > I think the best way to do this is probably to set two properties - > tv.channel_boundary and tv.volume_boundary, this is presuming that you > don't want to allow the lower boundary to be changed. If you do, > create an upper and lower boundary variable for each. > >>def channel_remote(tv, level = 1): >> if tv.channel in range(0,10): > > Here, it'd be better if you used > if tv.channel < 10: > > That way you're not wasting a whole list and a list search just to > test if something is less than ten. > Using the boundaries, that would be > if tv.channel < tv.channel_boundary: > > There's also no need for this, not here, anyway. You should be testing > in __init__, where the channel can be set incorrectly. > >> level = int(input("\n Which channel do you want to go up to: >> ")) > > Why have this when you allow level as an argument? It's a waste. > >> if 0 > level > 10: >> int(input("\n That's not valid! Choose another channel: >> ")) >> else: >> tv.channel += level > > This is your second problem you've found, I guess? > Well, how about this > tv.channel = level > Easy, right? :) > >> print("\n The channel is now:", tv.channel) > > >> Another one is for the tv.channel to hold a new value instead of just >> adding/subtracting the value and the only way I can think how is to use a >> list and then have the function replace the value each time. I'm sure >> there >> is a better way though. >> http://old.nabble.com/file/p31928968/TV TV > > > HTH > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- View this message in context: http://old.nabble.com/Television-tp31925053p31932639.html Sent from the Python - tutor mailing list archive at Nabble.com. From enalicho at gmail.com Sun Jun 26 22:03:26 2011 From: enalicho at gmail.com (Noah Hall) Date: Sun, 26 Jun 2011 21:03:26 +0100 Subject: [Tutor] Television In-Reply-To: <31932639.post@talk.nabble.com> References: <31925053.post@talk.nabble.com> <31928968.post@talk.nabble.com> <31932639.post@talk.nabble.com> Message-ID: On Sun, Jun 26, 2011 at 8:28 PM, Vincent Balmori wrote: > > I made in elif statement for the channel changer that works for it, but the > volume systems system boundary does not the way I want it to. If the volume > is 2 and I lower it by a value of 5, it will accept the volume at a negative > number thus going past the boundary. The vice-versa for the high boundary as > well. > > http://old.nabble.com/file/p31932639/TV.py TV.py In this case, you're testing in the wrong place again. >def volume_down(tv, down = 1): Again, no need for the variable "down" - you don't use it. > if tv.volume > tv.volume_lowboundary : tv.volume is always going to be less than tv.volume_lowboundary unless set via calling tv.volume = externally. > down = int(input("\n How much do you want to lower the volume?: ")) Note you haven't got any error catching. What happens if I enter "mouse"? > if down > 10: > int(input("\n That's too much! Choose another number?: ")) Here you need an elif clause, checking if down is too low, for example, elif tv.volume - down >1: > else: > tv.volume -= down > print("\n The volume is now:", tv.volume) > if tv.volume == 0: > print("\nVolume is at lowest value.") HTH From vincentbalmori at yahoo.com Mon Jun 27 02:31:11 2011 From: vincentbalmori at yahoo.com (Vincent Balmori) Date: Sun, 26 Jun 2011 17:31:11 -0700 (PDT) Subject: [Tutor] Critter Message-ID: <31933791.post@talk.nabble.com> I'm on the Critter Caretake problem that involves handling more than one critter. I have looked At David Merrick's threads for some answers, but the difference is that he created a whole new class to handle it, while I only made more critter objects. The only problem I have left is to have my actions (play and eat) apply to all my creatures ALL AT ONCE, instead of one at a time like it is in my code right now. http://old.nabble.com/file/p31933791/critter_caretaker3.py critter_caretaker3.py -- View this message in context: http://old.nabble.com/Critter-tp31933791p31933791.html Sent from the Python - tutor mailing list archive at Nabble.com. From merrickdav at gmail.com Mon Jun 27 04:12:11 2011 From: merrickdav at gmail.com (David Merrick) Date: Mon, 27 Jun 2011 14:12:11 +1200 Subject: [Tutor] Class methods Message-ID: Is it possible too have crit1 = Critter("Dave") crit2 = Critter("Sweetie") farm = [crit1,crit2] #List# and then be able to use Critters methods on farm? # Critter Caretaker # A virtual pet to care for class Critter(object): """A virtual pet""" def __init__(self, name, hunger = 0, boredom = 0): self.name = name self.hunger = hunger self.boredom = boredom # __ denotes private method def __pass_time(self): self.hunger += 1 self.boredom += 1 self.__str__() def __str__(self): print("Hunger is",self.hunger, "Boredom is " ,self.boredom) print("Unhappines is ",self.hunger + self.boredom," and Mood is ",self.mood) @property def mood(self): unhappiness = self.hunger + self.boredom if unhappiness < 5: m = "happy" elif 5 <= unhappiness <= 10: m = "okay" elif 11 <= unhappiness <= 15: m = "frustrated" else: m = "mad" return m def talk(self): print("I'm", self.name, "and I feel", self.mood, "now.\n") self.__pass_time() def eat(self): food = int(input("Enter how much food you want to feed your critter: ")) print("Brruppp. Thank you.") self.hunger -= food # hunger = 0 at iniatition # self.hunger = self.boredom - food if self.hunger < 0: self.hunger = 0 self.__pass_time() def play(self): fun = int(input("Enter how much fun you want your critter to have: ")) print("Wheee!") self.boredom -= fun # boredom = 0 at iniatition # self.boredom = self.boredom - fun if self.boredom < 0: self.boredom = 0 self.__pass_time() def main(): crit_name = input("What do you want to name your critter?: ") crit = Critter(crit_name) choice = None while choice != "0": print \ (""" Critter Caretaker 0 - Quit 1 - Listen to your critter 2 - Feed your critter 3 - Play with your critter """) choice = input("Choice: ") print() # exit if choice == "0": print("Good-bye.") # listen to your critter elif choice == "1": crit.talk() # feed your critter elif choice == "2": crit.eat() # play with your critter elif choice == "3": crit.play() # some unknown choice else: print("\nSorry, but", choice, "isn't a valid choice.") main() ("\n\nPress the enter key to exit.") -- Dave Merrick merrickdav at gmail.com Ph 03 3423 121 Cell 027 3089 169 -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Mon Jun 27 05:29:16 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Sun, 26 Jun 2011 20:29:16 -0700 Subject: [Tutor] Class methods In-Reply-To: References: Message-ID: On Sun, Jun 26, 2011 at 7:12 PM, David Merrick wrote: > Is it possible too have > > crit1 = Critter("Dave") > crit2 = Critter("Sweetie") > farm = [crit1,crit2] #List# > > and then be able to use Critters methods on farm? > > No. farm is a list, and lists don't inherit the methods of the objects inside them (imagine what a nightmare _that_ would be, especially since lists can contain more than one type of object at any given time!) Instead, you would refer to the members of the list: farm[0].talk() farm[1].talk() etc. Only you wouldn't generally hard-code those numbers; instead, you could use the "for x in y" style: for monster in farm: monster.talk() At this point, "monster" is one of your Critters. When I need a looping variable for a collection of custom objects, I like to use words that are synonymous with, or at least related to, the name of my custom class. It helps me keep track of what's going on - if I use x and y all over the place, I tend to get confused. You could also use a more traditional, less-Pythonic approach: for x in len(farm): farm[x].talk() But seriously, why would you want to use Python to imitate Visual Basic? By the way, you shouldn't ever need to refer to Dave and Sweetie by their hard-coded variable names, so instead of instead of creating "crit1, crit2", why not simply create them as members of the list? farm = [] for critter_name in ["Dave", "Sweetie"]: farm.append(Critter(critter_name)) Now the variables don't have names per se, but you can still refer to them by number if you need one in particular, or you can just loop over the list with "for monster in farm". Finally, maybe a dictionary would be more useful/intuitive than a list? farm = [] for critter_name in ["Dave", "Sweetie"]: farm[critter_name] = Critter(critter_name) farm["Dave"].talk() I do think that "farm" is going to be a little misleading as a name for a collection of Critters; might I suggest "herd" or "swarm"? Just a thought... -------------- next part -------------- An HTML attachment was scrubbed... URL: From jimsyyap at gmail.com Mon Jun 27 09:24:15 2011 From: jimsyyap at gmail.com (Jim Syyap) Date: Mon, 27 Jun 2011 19:24:15 +1200 Subject: [Tutor] learning how to convert script to python Message-ID: I am learning python at the moment--this is something I would like to work on/convert. It's a poker application that opens a table for you every x-minutes. The project has been discontinued and I would like to convert it to python, then use it. Can you tell me what language this is--lisp or autohotkey? What do I need to learn so I can convert these? Thanks! ; Thois TableOpener for PokerStars v1.05 > ; Opens new cash game tables from the lobby every x seconds (if there are less tables opened than your predefined settings). A great tool for multi-tablers. > ; Customize the variables below (between the lines) > ; 'Thois' on PS for donations > > ; Customizable variables (between the lines) > ;------------------------------------------ > rowheight := 13 ;In the PokerStars lobby go to View > Text Size: For Medium & smaller:13, For smallest:12, For Larger:15, For Largest:17 > recheck := 50 ;How often the script should open up new tables (if needed), 50=10seconds, 25=5seconds etc... Try not to set this too low for CPU performance issues > ;------------------------------------------ > > Gui, Font, s8, Arial > Gui, Add, Text,, Number Of Tables: > Gui, Add, Edit > Gui, Add, UpDown, vnumberoftablestokeepopen Range1-24, 12 > Gui, Add, Checkbox, venabledisable, Run! > Gui, Show,, Thois TableOpener for PokerStars v1.00 > Gui, Submit, NoHide > > numberofloopinstances := recheck - 1 > > Loop > { > Gui, Submit, NoHide > SendMessage, 0x115, 0, 0, PokerStarsListClass1, PokerStars Lobby > numberofloopinstances := numberofloopinstances + 1 > if (numberofloopinstances = recheck) > { > numberofloopinstances := 0 > WinGet, numberofwindows, Count, ahk_class PokerStarsTableFrameClass,,Lobby > beffen := numberoftablestokeepopen - numberofwindows > if (beffen > 0 AND enabledisable = 1) > { > Loop > { > ControlGet, tablesinthelobby, Hwnd, , PokerStarsListClass1, PokerStars Lobby > yclick := 1 + (rowheight * A_Index) - rowheight > PostLeftClick(1, yclick, tablesinthelobby) > ControlClick, PokerStarsButtonClass10, PokerStars Lobby > Sleep, 500 > WinGet, numberofwindows, Count, ahk_class PokerStarsTableFrameClass,,Lobby > beffen := numberoftablestokeepopen - numberofwindows > if (beffen = 0) > { > break > } > } > } > } > Sleep, 200 > } > > ; Hotkeys (disabled) > > ;~Xbutton1:: ;Endlessly cycles between all tables in the stack the cursor is pointing at (brings the front table to the back), disabled (remove ; marks to enable) > ;MouseGetPos,,,tableID > ;WinGetClass, classoftableid, ahk_id %tableID% > ;if (classoftableid = "PokerStarsTableFrameClass") > ; { > ; WinSet, Bottom,, ahk_id %tableID% > ; } > ;return > > ;~Xbutton2:: ;Closes the table the mouse is pointing at (also clicks the OK warning button), disabled (remove ; marks to enable) > ;MouseGetPos,,,tableID > ;WinGetClass, classoftableid, ahk_id %tableID% > ;if (classoftableid = "PokerStarsTableFrameClass"); > ; { > ; WinClose, ahk_id %tableID% > ; Sleep,20 > ; ControlClick, Button1, Table, OK > ; } > ;return > > ;Juks rocks - I deactivated WinActivate so that the Lobby doesnt steal focus > PostLeftClick(x, y, table_id, activate=1) { > ; ### JUK: Send the down left click, then the mouse-up messages. > ; NOTE: This is relative to the top left of the client area and NOT the top left of the > ; window (ie: It *doesn't* include the title-bar like AHK's MouseClick does!!!). > If activate > ; WinActivate, ahk_id%table_id% > PostMessage, 0x201, 0x0001, ((y<<16)^x), , ahk_id%table_id% > PostMessage, 0x202 , 0, ((y<<16)^x), , ahk_id%table_id% > } > > GuiClose: > ExitApp > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Jun 27 09:54:21 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 27 Jun 2011 08:54:21 +0100 Subject: [Tutor] Class methods References: Message-ID: "David Merrick" wrote > Is it possible too have > > crit1 = Critter("Dave") > crit2 = Critter("Sweetie") > farm = [crit1,crit2] #List# > > and then be able to use Critters methods on farm? No, Marc has already answered that. > class Critter(object): > > """A virtual pet""" > def __init__(self, name, hunger = 0, boredom = 0): > > # __ denotes private method > def __pass_time(self): > self.hunger += 1 > self.boredom += 1 > self.__str__() > > def __str__(self): > print("Hunger is",self.hunger, "Boredom is " ,self.boredom) > print("Unhappines is ",self.hunger + self.boredom," and Mood > is > ",self.mood) This is a really bad idea. Please do not do this, it will almost certainly lead to problems later. __str__ should return a string. It should not print anything. Then you can simply call print (self) at the end of the pass_time method or call print (farm[0]) in your external code. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Jun 27 10:10:02 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 27 Jun 2011 09:10:02 +0100 Subject: [Tutor] Critter References: <31933791.post@talk.nabble.com> Message-ID: "Vincent Balmori" wrote > I'm on the Critter Caretake problem that involves handling more than > one > critter. I have looked At David Merrick's threads for some answers, Given that David hasn't solved the problem yet that may not be the best source! :-) > difference is that he created a whole new class to handle it, He has now reverted to a simple list. > made more critter objects. The only problem I have left is to have > my > actions (play and eat) apply to all my creatures ALL AT ONCE, > instead of one > at a time like it is in my code right now. You can't. You can only apply the methods to one critter at a time. You can write code to wrap it all up into a convenient single call, but that code will still need to call each item separately. There is no such thing as a "call all" mechanism in Python. BTW, You have the same issue as David with __str__. __str__() should return a string, it should not print anything itself. If you sdo that you can then, in your main code write print(crit1) instead of crit1.__str__() This makes using objects much more like using other data types. Also in your init method: def __init__(self, name, hunger = 0, boredom = 0): hunger = random.randint(0,15) boredom = random.randint(0,15) These two lines mean you throw away the values being passed in to the constructor, so you might as well not have them. And... self.name = name self.hunger = hunger self.boredom = boredom Since you just assign them to the attributes you might as well just do the call to randint() here and delete the first two lines completely. Finally in play() def play(self, fun = 4): while self.boredom >= 3: fun = int(input("\n How long do you want to play?: ")) if fun > 5: int(input("\n How long do you want to play?: ")) You ignore the value of fun passed into the method. (And in your code never pass a value) So again you could just lose the fun parameter. Then if fun > 5 you ask the user for a value, convert it to an int then throw it away so it does no good. You probably should assign the new value to fun. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Jun 27 10:16:39 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 27 Jun 2011 09:16:39 +0100 Subject: [Tutor] learning how to convert script to python References: Message-ID: "Jim Syyap" wrote > The project has been discontinued and I would like to convert it to > python, then use it. > > Can you tell me what language this is--lisp or autohotkey? No idea what autohotkey looks like but it certainly is NOT Lisp. > What do I need to learn so I can convert these? Python and whatever the language is. But you will also need to convert all of the support modules that the code uses - like Gui for example, and they might be written in a different language - like C perhaps. Its an interesting challenge but it could be bigger than you think! Be prepared for the long run. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ >> Gui, Font, s8, Arial >> Gui, Add, Text,, Number Of Tables: >> Gui, Add, Edit >> Gui, Add, UpDown, vnumberoftablestokeepopen Range1-24, 12 >> Gui, Add, Checkbox, venabledisable, Run! >> Gui, Show,, Thois TableOpener for PokerStars v1.00 >> Gui, Submit, NoHide >> >> numberofloopinstances := recheck - 1 >> >> Loop >> { >> Gui, Submit, NoHide >> SendMessage, 0x115, 0, 0, PokerStarsListClass1, PokerStars Lobby >> numberofloopinstances := numberofloopinstances + 1 >> if (numberofloopinstances = recheck) >> { >> numberofloopinstances := 0 >> WinGet, numberofwindows, Count, ahk_class >> PokerStarsTableFrameClass,,Lobby >> beffen := numberoftablestokeepopen - numberofwindows From merrickdav at gmail.com Mon Jun 27 10:57:11 2011 From: merrickdav at gmail.com (David Merrick) Date: Mon, 27 Jun 2011 20:57:11 +1200 Subject: [Tutor] Tutor Digest, Vol 88, Issue 103 In-Reply-To: References: Message-ID: Thanks that should help -------------- next part -------------- An HTML attachment was scrubbed... URL: From vincentbalmori at yahoo.com Mon Jun 27 20:52:01 2011 From: vincentbalmori at yahoo.com (Vincent Balmori) Date: Mon, 27 Jun 2011 11:52:01 -0700 (PDT) Subject: [Tutor] Critter In-Reply-To: References: <31933791.post@talk.nabble.com> Message-ID: <31940427.post@talk.nabble.com> Last thing I need to do solve is the __str__ problem. I can print the name fine, but everytime I try to put in the self.hunger and self.boredom values I get: TypeError: Can't convert 'int' object to str implicitly http://old.nabble.com/file/p31940427/critter_caretaker3.py critter_caretaker3.py Alan Gauld wrote: > > > "Vincent Balmori" wrote > >> I'm on the Critter Caretake problem that involves handling more than >> one >> critter. I have looked At David Merrick's threads for some answers, > > Given that David hasn't solved the problem yet that may not > be the best source! :-) > >> difference is that he created a whole new class to handle it, > > He has now reverted to a simple list. > >> made more critter objects. The only problem I have left is to have >> my >> actions (play and eat) apply to all my creatures ALL AT ONCE, >> instead of one >> at a time like it is in my code right now. > > You can't. You can only apply the methods to one critter at a time. > You can write code to wrap it all up into a convenient single call, > but that code will still need to call each item separately. There is > no such thing as a "call all" mechanism in Python. > > BTW, You have the same issue as David with __str__. > __str__() should return a string, it should not print anything itself. > If you sdo that you can then, in your main code write > > print(crit1) > > instead of > > crit1.__str__() > > This makes using objects much more like using other data types. > > Also in your init method: > > def __init__(self, name, hunger = 0, boredom = 0): > hunger = random.randint(0,15) > boredom = random.randint(0,15) > > These two lines mean you throw away the values being > passed in to the constructor, so you might as well not > have them. And... > > self.name = name > self.hunger = hunger > self.boredom = boredom > > Since you just assign them to the attributes you might as well > just do the call to randint() here and delete the first two lines > completely. > > Finally in play() > > def play(self, fun = 4): > while self.boredom >= 3: > fun = int(input("\n How long do you want to play?: ")) > if fun > 5: > int(input("\n How long do you want to play?: ")) > > You ignore the value of fun passed into the method. > (And in your code never pass a value) So again you could > just lose the fun parameter. > > Then if fun > 5 you ask the user for a value, convert it to an > int then throw it away so it does no good. You probably should > assign the new value to fun. > > 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 > > -- View this message in context: http://old.nabble.com/Critter-tp31933791p31940427.html Sent from the Python - tutor mailing list archive at Nabble.com. From gagnrath at verizon.net Mon Jun 27 21:45:45 2011 From: gagnrath at verizon.net (gagnrath at verizon.net) Date: Mon, 27 Jun 2011 14:45:45 -0500 (CDT) Subject: [Tutor] Zipping files and Mysql Message-ID: <1519748939.2182300.1309203945026.JavaMail.root@vznit170128> I am trying to write a script that will dump a mysql db and then zip the file. I do know about mysqldb, but I was wondering if there is anything native to the libraries that will allow me to do this without using a seperate piece. Then after I gather the DBs, I need to zip them. I wrote the following, but wanted to know if I am heading in the correct direction. zipfile.zipfile(/myfiles/my_db/, w, zip_stored) From kpguy1975 at gmail.com Mon Jun 27 23:07:43 2011 From: kpguy1975 at gmail.com (Vikram K) Date: Mon, 27 Jun 2011 17:07:43 -0400 Subject: [Tutor] nested list query Message-ID: Suppose i have the following nested list: >>> x [['19600894', '1', 'chr15_76136768', 'MISSENSE'], ['19600894', '2', 'chr15_76136768', 'MISSENSE'], ['18467762', '1', 'chr14_23354066', 'MISSENSE']] How do i obtain from nested list x (given above), the following nested list z: >>> z [['chr15_76136768', 'MISSENSE'], ['chr14_23354066', 'MISSENSE']] ------ In other words, if the third element of an element of x is the same, then i wish to combine it into a single element. -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Tue Jun 28 00:05:55 2011 From: wprins at gmail.com (Walter Prins) Date: Mon, 27 Jun 2011 23:05:55 +0100 Subject: [Tutor] Critter In-Reply-To: <31940427.post@talk.nabble.com> References: <31933791.post@talk.nabble.com> <31940427.post@talk.nabble.com> Message-ID: On 27 June 2011 19:52, Vincent Balmori wrote: > > Last thing I need to do solve is the __str__ problem. I can print the name > fine, but everytime I try to put in the self.hunger and self.boredom values > I get: > > TypeError: Can't convert 'int' object to str implicitly > > OK, so if Python can't convert an int to a str implicitly, then it's up to you to do it *explicitly*, by using the str() conversion function or perhaps by using a format string operation. #For example: a_number = 123 print(a_number) a_number_str = str(a_number) print(a_number_str) a_number_str_nicely_formatted = 'The number value is %4d.' % a_number print(a_number_str_nicely_formatted) Additionally I'd like to point out that your solution is fixed to 3 critters, whilst using a list would allow you to have a variable number of critters and add more if you wanted them while the program was running and without having to go and modify your program to do so. So, I'd suggest that you try to figure out how to eliminate managing your 3 critters via 3 explicit variables and instead store them in a list, and enhancing the program so you can add critters from the menu. (If this is expanding the scope of the excercise beyond what is intended then please ignore my suggestion.) Regards Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From bfkhiya at gmail.com Tue Jun 28 00:27:10 2011 From: bfkhiya at gmail.com (Esther Showalter) Date: Mon, 27 Jun 2011 18:27:10 -0400 Subject: [Tutor] Beginner troubleshooting py2exe Message-ID: Hello! I'm trying to follow the introductory tutorial on using py2exe at http://py2exe.org/index.cgi/Tutorial. It's very straightforward except that I keep getting an error when I come to step #3 and I don't know what I need to do about it: I'm running Python 2.7 on Windows Vista (32-bit). I've installed Python in C:\Python27 and py2exe in C:\Python27\Lib\site-packages\py2exe. When I reach step #3 in the tutorial and run my setup script that I just wrote from the tutorial's guidelines, I get the following error: C:\Python27>python setup.py py2exe running py2exe *** searching for required modules *** *** parsing results *** creating python loader for extension 'unicodedata' (C:\Python27\DLLs\unicodedata .pyd -> unicodedata.pyd) creating python loader for extension 'select' (C:\Python27\DLLs\select.pyd -> se lect.pyd) creating python loader for extension '_hashlib' (C:\Python27\DLLs\_hashlib.pyd - > _hashlib.pyd) creating python loader for extension 'bz2' (C:\Python27\DLLs\bz2.pyd -> bz2.pyd) *** finding dlls needed *** Traceback (most recent call last): File "setup.py", line 6, in setup(console=['hello.py']) File "C:\Python27\lib\distutils\core.py", line 152, in setup dist.run_commands() File "C:\Python27\lib\distutils\dist.py", line 953, in run_commands self.run_command(cmd) File "C:\Python27\lib\distutils\dist.py", line 972, in run_command cmd_obj.run() File "C:\Python27\lib\site-packages\py2exe\build_exe.py", line 243, in run self._run() File "C:\Python27\lib\site-packages\py2exe\build_exe.py", line 305, in _run dlls = self.find_dlls(extensions) File "C:\Python27\lib\site-packages\py2exe\build_exe.py", line 389, in find_dl ls self.dll_excludes) File "C:\Python27\lib\site-packages\py2exe\build_exe.py", line 1021, in find_d ependend_dlls import py2exe_util ImportError: DLL load failed: %1 is not a valid Win32 application. After this error occurs I checked my directories and saw that the dist and build folders were created inside the C:\Python27 folder as predicted in the tutorial, but they don't contain any folders or files. I'm assuming this is a problem with something system not being able to locate the proper file, but I have exactly no idea how to solve it. Advice? Enlightenmnet? Thanks very much. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Jun 28 00:47:23 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 27 Jun 2011 23:47:23 +0100 Subject: [Tutor] Critter References: <31933791.post@talk.nabble.com> <31940427.post@talk.nabble.com> Message-ID: "Vincent Balmori" wrote > Last thing I need to do solve is the __str__ problem. I can print > the name > fine, but everytime I try to put in the self.hunger and self.boredom > values > I get: > > TypeError: Can't convert 'int' object to str implicitly That's right you need to do it explicitly. Either by using str() or by using a format string. (see the thread yesterday for that topic) See one of my earlier posts for the code using a format string. Alan G From alan.gauld at btinternet.com Tue Jun 28 00:54:02 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 27 Jun 2011 23:54:02 +0100 Subject: [Tutor] nested list query References: Message-ID: "Vikram K" wrote > Suppose i have the following nested list: > >>>> x > [['19600894', '1', 'chr15_76136768', 'MISSENSE'], ['19600894', '2', > 'chr15_76136768', 'MISSENSE'], ['18467762', '1', 'chr14_23354066', > 'MISSENSE']] > > > How do i obtain from nested list x (given above), the following > nested list > z: > >>>> z > [['chr15_76136768', 'MISSENSE'], ['chr14_23354066', 'MISSENSE']] Since it is not clear what exact algorithm you are following to derive the second from the first I'll take the brute force sinplistic route: [x[0][-2:],x[-1][-2:]] Now, I'm pretty sure you have a more complex algorithm that just using the first and last elements of the list, but since I don't know what it is, this will have to do... -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From delegbede at dudupay.com Tue Jun 28 07:57:29 2011 From: delegbede at dudupay.com (delegbede at dudupay.com) Date: Tue, 28 Jun 2011 05:57:29 +0000 Subject: [Tutor] Beginner troubleshooting py2exe In-Reply-To: References: Message-ID: <1837425770-1309240650-cardhu_decombobulator_blackberry.rim.net-974680237-@b28.c12.bise7.blackberry> Just curious. Going by the last line of the error generated, it says something you tried to import is not a valid windows application. Can you confirm you installed the right py2exe for python 2.7 on Win32? You may want to check that to be sure. The last line of your error stack should point you in the direction to go. Regards. Sent from my BlackBerry wireless device from MTN -----Original Message----- From: Esther Showalter Sender: tutor-bounces+delegbede=dudupay.com at python.org Date: Mon, 27 Jun 2011 18:27:10 To: Subject: [Tutor] Beginner troubleshooting py2exe _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From timomlists at gmail.com Tue Jun 28 09:56:57 2011 From: timomlists at gmail.com (Timo) Date: Tue, 28 Jun 2011 09:56:57 +0200 Subject: [Tutor] Zipping files and Mysql In-Reply-To: <1519748939.2182300.1309203945026.JavaMail.root@vznit170128> References: <1519748939.2182300.1309203945026.JavaMail.root@vznit170128> Message-ID: <4E098949.2080609@gmail.com> On 27-06-11 21:45, gagnrath at verizon.net wrote: > I am trying to write a script that will dump a mysql db and then zip the file. > > > I do know about mysqldb, but I was wondering if there is anything native to the libraries that will allow me to do this without using a seperate piece. Then after I gather the DBs, I need to zip them. I wrote the following, but wanted to know if I am heading in the correct direction. > > zipfile.zipfile(/myfiles/my_db/, w, zip_stored) Well, for what it's worth, I'm using the zipfile module as well in one of my projects to make a backup of the user's configuration directory. Which works pretty good. Do have a good look though at the documentation or find some examples through your search engine, because the above line won't work at all. Cheers, Timo > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From gagnrath at verizon.net Tue Jun 28 18:40:31 2011 From: gagnrath at verizon.net (gagnrath at verizon.net) Date: Tue, 28 Jun 2011 11:40:31 -0500 (CDT) Subject: [Tutor] Zipping files and Mysql Message-ID: <735481110.6397612.1309279231618.JavaMail.root@vznit170080> First time trying to use it, so I don't expect it to work. Got to see if I have a file i don't mind playing around with to see if I can zip it up using the zipfile. As for the MySQL, I think I may have to resign myself to using an alternate method than the straight python libraries. Jun 28, 2011 04:02:48 AM, timomlists at gmail.com wrote: =========================================== On 27-06-11 21:45, gagnrath at verizon.net wrote: > I am trying to write a script that will dump a mysql db and then zip the file. > > > I do know about mysqldb, but I was wondering if there is anything native to the libraries that will allow me to do this without using a seperate piece. Then after I gather the DBs, I need to zip them. I wrote the following, but wanted to know if I am heading in the correct direction. > > zipfile.zipfile(/myfiles/my_db/, w, zip_stored) Well, for what it's worth, I'm using the zipfile module as well in one of my projects to make a backup of the user's configuration directory. Which works pretty good. Do have a good look though at the documentation or find some examples through your search engine, because the above line won't work at all. Cheers, Timo > _______________________________________________ > 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 merrickdav at gmail.com Wed Jun 29 06:28:25 2011 From: merrickdav at gmail.com (David Merrick) Date: Wed, 29 Jun 2011 16:28:25 +1200 Subject: [Tutor] Python GUI Message-ID: # Guess My Number GUI # Create a story based on user input from tkinter import * import random class Application(Frame): """ GUI application that creates a story based on user input. """ def __init__(self, master): """ Initialize Frame. """ super(Application, self).__init__(master) self.grid() self.create_widgets() def create_widgets(self): """ Create widgets to get story information and to display story. """ # create instruction label Label(self, text = "Welcome to 'Guess My Number'!\n\nI'm thinking of a number between 1 and 100.\nTry to guess it in as few attempts as possible." ).grid(row = 0, column = 0, columnspan = 2, sticky = W) # create a label for body parts radio buttons Label(self, text = "Take a guess:" ).grid(row = 6, column = 0, sticky = W) self.numberEnt = Entry(self) self.numberEnt.grid(row = 6, column = 1, sticky = W) # create a submit button Button(self, text = "Click to see if you got it", command = self.testNumber ).grid(row = 7, column = 0, sticky = W) self.numberTxt = Text(self, width = 75, height = 10, wrap = WORD) self.numberTxt.grid(row = 8, column = 0, columnspan = 4) def testNumber(self): """ Fill text box with new story based on user input. """ # get values from the GUI # create the story guess = int(self.numberEnt.get()) tries = 1 while guess != the_number: if guess > the_number: number += "Lower..." else: number += "Higher..." guess = int(self.numberEnt.get()) tries += 1 # display the text self.numberTxt.delete(0.0, END) self.numberTxt.insert(0.0, number) number += "You guessed it! The number was" + the_number number += "And it only took you " + tries + " tries!\n" self.numberTxt.delete(0.0, END) self.numberTxt.insert(0.0, number) # main number = "" the_number = random.randint(1, 100) root = Tk() root.title("Mad Lib") app = Application(root) root.mainloop() *Output* Traceback (most recent call last): File "I:\Python\programs\guess_my_ numberChapter10.py", line 60, in number += "You guessed it! The number was" + the_number NameError: name 'number' is not defined Any ides??????????? Is my code going to work apart from this problem????????????? -- Dave Merrick merrickdav at gmail.com Ph 03 3423 121 Cell 027 3089 169 -------------- next part -------------- An HTML attachment was scrubbed... URL: From rabidpoobear at gmail.com Wed Jun 29 06:52:15 2011 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 28 Jun 2011 23:52:15 -0500 Subject: [Tutor] Python GUI In-Reply-To: References: Message-ID: The error message tells you everything... On line 60, you try to add to "number" but the variable hasn't been defined. We aren't going to debug your code for you, do YOU think it will work apart from this? Have you tried running any of the code? It's almost always better to build small parts and test along the way than to write out a whole program and try it at the end. ----------------------------- Sent from a mobile device. Apologies for brevity and top-posting. ----------------------------- On Jun 28, 2011, at 11:28 PM, David Merrick wrote: > # Guess My Number GUI > # Create a story based on user input > > from tkinter import * > import random > class Application(Frame): > """ GUI application that creates a story based on user input. """ > def __init__(self, master): > """ Initialize Frame. """ > super(Application, self).__init__(master) > self.grid() > self.create_widgets() > > def create_widgets(self): > """ Create widgets to get story information and to display story. """ > # create instruction label > Label(self, > text = "Welcome to 'Guess My Number'!\n\nI'm thinking of a number between 1 and 100.\nTry to guess it in as few attempts as possible." > ).grid(row = 0, column = 0, columnspan = 2, sticky = W) > > > # create a label for body parts radio buttons > Label(self, > text = "Take a guess:" > ).grid(row = 6, column = 0, sticky = W) > self.numberEnt = Entry(self) > self.numberEnt.grid(row = 6, column = 1, sticky = W) > > # create a submit button > Button(self, > text = "Click to see if you got it", > command = self.testNumber > ).grid(row = 7, column = 0, sticky = W) > > self.numberTxt = Text(self, width = 75, height = 10, wrap = WORD) > self.numberTxt.grid(row = 8, column = 0, columnspan = 4) > > def testNumber(self): > """ Fill text box with new story based on user input. """ > # get values from the GUI > > # create the story > > guess = int(self.numberEnt.get()) > tries = 1 > > while guess != the_number: > if guess > the_number: > number += "Lower..." > else: > number += "Higher..." > guess = int(self.numberEnt.get()) > tries += 1 > > # display the text > self.numberTxt.delete(0.0, END) > self.numberTxt.insert(0.0, number) > > > number += "You guessed it! The number was" + the_number > number += "And it only took you " + tries + " tries!\n" > self.numberTxt.delete(0.0, END) > self.numberTxt.insert(0.0, number) > > > > # main > number = "" > the_number = random.randint(1, 100) > root = Tk() > root.title("Mad Lib") > app = Application(root) > root.mainloop() > > Output > > Traceback (most recent call last): > File "I:\Python\programs\guess_my_ numberChapter10.py", line 60, in > number += "You guessed it! The number was" + the_number > NameError: name 'number' is not defined > > Any ides??????????? Is my code going to work apart from this problem????????????? > > -- > Dave Merrick > > merrickdav at gmail.com > > Ph 03 3423 121 > Cell 027 3089 169 > _______________________________________________ > 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 raj.priyesh at gmail.com Wed Jun 29 07:11:20 2011 From: raj.priyesh at gmail.com (priyesh raj) Date: Wed, 29 Jun 2011 10:41:20 +0530 Subject: [Tutor] Python GUI Message-ID: > > Message: 2 > Date: Wed, 29 Jun 2011 16:28:25 +1200 > From: David Merrick > To: tutor at python.org > Subject: [Tutor] Python GUI > Message-ID: > Content-Type: text/plain; charset="utf-8" > > # Guess My Number GUI > # Create a story based on user input > > from tkinter import * > import random > class Application(Frame): > """ GUI application that creates a story based on user input. """ > def __init__(self, master): > """ Initialize Frame. """ > super(Application, self).__init__(master) > self.grid() > self.create_widgets() > > def create_widgets(self): > """ Create widgets to get story information and to display story. > """ > # create instruction label > Label(self, > text = "Welcome to 'Guess My Number'!\n\nI'm thinking of a > number between 1 and 100.\nTry to guess it in as few attempts as possible." > ).grid(row = 0, column = 0, columnspan = 2, sticky = W) > > > # create a label for body parts radio buttons > Label(self, > text = "Take a guess:" > ).grid(row = 6, column = 0, sticky = W) > self.numberEnt = Entry(self) > self.numberEnt.grid(row = 6, column = 1, sticky = W) > > # create a submit button > Button(self, > text = "Click to see if you got it", > command = self.testNumber > ).grid(row = 7, column = 0, sticky = W) > > self.numberTxt = Text(self, width = 75, height = 10, wrap = WORD) > self.numberTxt.grid(row = 8, column = 0, columnspan = 4) > > def testNumber(self): > """ Fill text box with new story based on user input. """ > # get values from the GUI > > # create the story > > guess = int(self.numberEnt.get()) > tries = 1 > > while guess != the_number: > if guess > the_number: > number += "Lower..." > else: > number += "Higher..." > guess = int(self.numberEnt.get()) > tries += 1 > > # display the text > self.numberTxt.delete(0.0, END) > self.numberTxt.insert(0.0, number) > > > ----> The problem is here. You have initialised the variable "number" as a part of the main function and trying to call it within the function of class. You need to initialise the variable here itself, or need to pass the variable (which you initialised in main) to this function. > number += "You guessed it! The number was" + the_number > number += "And it only took you " + tries + " tries!\n" > self.numberTxt.delete(0.0, END) > self.numberTxt.insert(0.0, number) > > > > # main > number = "" > the_number = random.randint(1, 100) > root = Tk() > root.title("Mad Lib") > app = Application(root) > root.mainloop() > > *Output* > > Traceback (most recent call last): > File "I:\Python\programs\guess_my_ numberChapter10.py", line 60, in > > number += "You guessed it! The number was" + the_number > NameError: name 'number' is not defined > > Any ides??????????? Is my code going to work apart from this > problem????????????? > > -- > Dave Merrick > > merrickdav at gmail.com > > Ph 03 3423 121 > Cell 027 3089 169 > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20110629/4057af9d/attachment-0001.html > > > Regards, Priyesh -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Jun 29 09:58:55 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 29 Jun 2011 08:58:55 +0100 Subject: [Tutor] Python GUI References: Message-ID: "David Merrick" wrote Others have answered the immediate issue. But... > def testNumber(self): > guess = int(self.numberEnt.get()) > tries = 1 > > while guess != the_number: > if guess > the_number: > number += "Lower..." > else: > number += "Higher..." > guess = int(self.numberEnt.get()) > tries += 1 This is all wrong for a GUI appluication. You should not use loops in an event handler. Instead let the event loop in Tkinter do the looping. You respond to the user clicking the submit button and evaluate that single value. You then wait for the next button press to signal that there is a new value to check. Any time you see a loop inside a GUI event handler you should stop and check that it belongs there. Usually it doesn't! > number += "You guessed it! The number was" + the_number > number += "And it only took you " + tries + " tries!\n" > self.numberTxt.delete(0.0, END) > self.numberTxt.insert(0.0, number) It may just be mail but this appears to be outside the method definition and indeed outside the class. Is that correct? Or just a mail glitch? Since they refer to self they should be inside a method so I'll assume its a mail thing. > # main > number = "" > the_number = random.randint(1, 100) If you are using classes its normal to put most of the variables inside the classes. There is no reason for the_number to be a global value, it would be better as part of the Application. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From wprins at gmail.com Wed Jun 29 15:03:38 2011 From: wprins at gmail.com (Walter Prins) Date: Wed, 29 Jun 2011 14:03:38 +0100 Subject: [Tutor] Python GUI In-Reply-To: References: Message-ID: Just to add to what Alan's said: A key thing you will need to wrap your head around when transitioning to GUI applications is the fact that the application is then not linear (or as linear) as a console/text application. In a console application you basically control everything, and if there needs to be a loop in the application to repeatedly collect user actions or events (such as menu selections and so on) etc, then it's up to you to write this yourself. GUI applications are however different, in that the entire GUI system is "event driven". Conceptually what this means is that operating system is ultimately responsible for collecting events (such as mouse clicks, keyboard input, and so on) and it delivers these events/actions to your application by sending it messages (which ultimately translates into functions and methods in your application being called, as if by magic, from the outside.) The upshot of this is, as Alan said, that in most GUI applications you don't write loops to "wait for input" yourself, you instead hand this off to the operating system. And it knows to call your methods by the fact that in some part of your application you "register your interest" in receiving various events, typically by providing an event handler (a method to be called when that event happens.) So conceptually, in a console application, you write the "main" loop yourself, and directly call other methods/functions when certain "events" happen (such as the user selecting a menu option.) In a GUI application, you can imagine this loop is somewhere inside the operating system (not inside your application), and so your application doesn't provide one itself, instead your application collaborates with the operating system to make your application happen. Object orientation conceptually is all about objects collaborating with other objects by sending and receiving messages, collectively working towards a solution. Hope that helps. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Jun 29 19:27:56 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 29 Jun 2011 18:27:56 +0100 Subject: [Tutor] Python GUI References: Message-ID: "Walter Prins" wrote > Just to add to what Alan's said: A key thing you will need to wrap > your > head around when transitioning to GUI applications is the fact that > the > application is then not linear (or as linear) as a console/text > application. Thanks for the extra detail Walter, I was in a hurry this morning :-) > So conceptually, in a console application, you write the "main" loop > ...In a GUI application, you can imagine this loop is somewhere > inside the operating system And if you want to compare the two approaches the Event Driven Programming topic in my tutorial has essentially the same application implemented as both a console and GUI app. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From naheedcse at gmail.com Thu Jun 30 06:29:54 2011 From: naheedcse at gmail.com (naheed arafat) Date: Thu, 30 Jun 2011 10:29:54 +0600 Subject: [Tutor] POST request using httplib2 Message-ID: On the way of learning " handling POST request in php" i tried to make a simple python http client using httplib2 & urllib module.. what i wanted to do was submitting username & password field to a php script (which just echo's the username & password) & prints the response in python,not in html/php.. import httplib2 import urllib url="http://localhost/form_process.php" body={'username':'xyz','password':'abc'} h=httplib2.Http() response,content=h.request(url,'POST',urllib.urlencode(body)) print content I got the following content: * Form processing : * instead of: * Form processing xyz: abc * attachments: form.php # takes username,password from the user,pass those to # form_process.php as GET parameter form_process.php # echo username,password. sorry for my long email. -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: form.php Type: application/x-httpd-php Size: 406 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: form_process.php Type: application/x-httpd-php Size: 175 bytes Desc: not available URL: From vincentbalmori at yahoo.com Thu Jun 30 10:39:57 2011 From: vincentbalmori at yahoo.com (Vincent Balmori) Date: Thu, 30 Jun 2011 01:39:57 -0700 (PDT) Subject: [Tutor] War: The Card Game Message-ID: <31961149.post@talk.nabble.com> I am working on the card game of war challenge where each player is given a single card and the highest value wins. I keep getting a Type Error since for the moment since the values of the cards cannot be compared due to their types. I am thinking of creating a Card_Value class that will give each rank and suit a certain value. If there is also a more elegant way of handling some of the code in the main section that will be welcome. http://old.nabble.com/file/p31961149/war.py war.py -- View this message in context: http://old.nabble.com/War%3A-The-Card-Game-tp31961149p31961149.html Sent from the Python - tutor mailing list archive at Nabble.com. From alan.gauld at btinternet.com Thu Jun 30 11:35:18 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 30 Jun 2011 10:35:18 +0100 Subject: [Tutor] The Card Game References: <31961149.post@talk.nabble.com> Message-ID: "Vincent Balmori" wrote > I keep getting a Type Error since for the moment since the > values of the cards cannot be compared due to their > types. Please send the complete error text sincethat will tell us where to look etc. > I am thinking of creating a Card_Value class that will give each > rank > and suit a certain value. If there is also a more elegant way of > handling > some of the code in the main section that will be welcome. You can get cards to compare themselves by adding a few more "magic methods". Then you can do stuff like if card1 < card2: # .... elif card2 > card1: # .... else:.... The methods you need to create are __gt__(), __lt__(), __eq__(), __le__(), __ge__() for >,<,==,<=,>= operations. BTW, In your code you have a comparison using = instead of ==. That will fail. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From g.nius.ck at gmail.com Thu Jun 30 19:00:55 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Thu, 30 Jun 2011 13:00:55 -0400 Subject: [Tutor] Trivia In-Reply-To: <31917979.post@talk.nabble.com> References: <31917610.post@talk.nabble.com> <31917637.post@talk.nabble.com> <31917701.post@talk.nabble.com> <31917979.post@talk.nabble.com> Message-ID: Just some programming philosophy. On Fri, Jun 24, 2011 at 3:58 AM, Vincent Balmori wrote: > > "Your whole approach is very fragile in this respect, it only > takes one small mistake in the data to wreck your program,. > Somethjing like a config file format would be much more > robust (and readable) the config reader module would make > sure you got what you expected back. " > > Can you please explain more on what you mean by this? > > > Alan Gauld wrote: > > > > > > "Vincent Balmori" wrote > > > >> It's working fine now with the scoring, but now at the end of the > >> program > >> for some reason I get this error message: > >> > > > "/Users/vincentbalmori/Desktop/Python/py3e_source/chapter07/trivia_challenge2.py", > >> line 27, in next_block > >> point = int(next_line(the_file)) > >> ValueError: invalid literal for int() with base 10: '' > > > > Thats because after the last question you try to read another > > block and don't check anywhere whether you actually read > > anything. Your next_block code just assumes there will > > always be valid data there, but at the end of the file there > > won't be. You get away with category being blank > > because replace() doesn't complain. But int() does. > > > > Your whole approach is very fragile in this respect, it only > > takes one small mistake in the data to wreck your program,. > > Somethjing like a config file format would be much more > > robust (and readable) the config reader module would make > > sure you got what you expected back. > > > > 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 > > > > > > -- > View this message in context: > http://old.nabble.com/Trivia-tp31917610p31917979.html > Sent from the Python - tutor mailing list archive at Nabble.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 g.nius.ck at gmail.com Thu Jun 30 19:09:00 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Thu, 30 Jun 2011 13:09:00 -0400 Subject: [Tutor] decorators In-Reply-To: <4E03FEF3.6050408@pearwood.info> References: <4E03FEF3.6050408@pearwood.info> Message-ID: It would be cool if their where decorators that modified decorators. I know its possible, but I can't think of a use. On Thu, Jun 23, 2011 at 11:05 PM, Steven D'Aprano wrote: > Robert wrote: > >> Is there a good tutorial out there somewhere about decorators? Google >> doesn't bring up much. >> >> > > Define "good" :) > > I'm interested in what you think about this article: > > http://www.artima.com/weblogs/**viewpost.jsp?thread=240808 > > Personally, I think it's filled with jargon that will be alien to most > Python coders, but otherwise interesting. > > Here's my cheap introduction to decorators... > > Before you understand decorators, you have to understand two things about > Python: > > (1) Functions are "first class objects"; > > (2) and therefore you can write "factory functions". > > Everything else is just a bonus. > > What I mean by "first class" is best explained by giving an example of the > opposite, second class objects. In some languages, functions are "special", > and by special I mean they are more restricted. You cannot (easily, or at > all) pass a function as an argument to another function, or give it a new > name. This makes a lot of code hard to write. For instance, you might want > to create a Grapher application, that lets the user draw the graph of some > function. The basic algorithm would be something like this: > > def grapher(function, low, high, step): > for x in range(low, high, step): > y = function(x) > draw_pixel(x, y) # draw a pixel on the graph, somehow... > > This is easy in Python, but very hard in languages where functions are > second class. Because they are second class, you cannot pass them as > arguments: > > grapher(math.sin, 0, 100, 1) > > is not allowed in some languages, but is allowed in Python. > > One consequence of this is the idea of "factory functions" is allowed. You > can write a function which builds new functions, and returns them: > > >>> def factory(x): > ... def inner(arg): > ... return arg + x > ... return inner # return the function object itself > ... > >>> plusone = factory(1) > >>> plustwo = factory(2) > >>> > >>> plusone(23) > 24 > > > Decorators are a special type of factory function. They take as their > argument a function, and then modify, wrap, or replace the function to > perform special processing. Because the decorator itself is a function, > anything you can do in Python, you can do in a decorator. The only > limitation is that it must take a single argument, expected to be a > function. (Or a class, in newer versions of Python.) Everything else is up > to you! > > "Decorator syntax" is the special syntax you often see: > > @decorator > def spam(): > pass > > > is syntactic sugar for the longer version: > > def spam(): > pass > > spam = decorator(spam) > > > > What are decorators good for? > > The most common use is to *wrap* the function so as to eliminate > boilerplate code. > > Suppose you have a bunch of functions that look like this: > > > def func(arg): > if isinstance(arg, int) and arg > 0: > arg = min(arg, 1000) > do stuff > else: > raise ValueError('bad argument') > > def func2(arg): > if isinstance(arg, int) and arg > 0: > arg = min(arg, 1000) > do different stuff > else: > raise ValueError('bad argument') > > def func3(arg): > if isinstance(arg, int) and arg > 0: > arg = min(arg, 1000) > do something else > else: > raise ValueError('bad argument') > > All of the functions go through the same boilerplate at the beginning and > end, testing for a valid argument, raising an error if not, adjusting the > argument value... Only the "do stuff" parts are different. This is a lot of > duplicated code. We can reduce the duplication, making it easier to maintain > and test, by moving all the common code into one place: > > > def test_argument(func): > def inner(arg): > if not (isinstance(arg, int) and arg > 0): > raise ValueError('bad argument') > arg = min(arg, 1000) > return func(arg) > return inner > > > @test_argument > def func(arg): > do stuff > > @test_argument > def func2(arg): > do different stuff > > @test_argument > def func3(arg): > do something else again > > > The common code (the boilerplate) is now inside the decorator. The > decorator takes a function as an argument, wraps it with an inner function > that calls the common boilerplate code, tests the argument, raises an error > if needed, and returns the result of calling the unique "do stuff" part. > > > -- > 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 vincentbalmori at yahoo.com Thu Jun 30 20:48:44 2011 From: vincentbalmori at yahoo.com (Vincent Balmori) Date: Thu, 30 Jun 2011 11:48:44 -0700 (PDT) Subject: [Tutor] Blackjack Betting Message-ID: <31966195.post@talk.nabble.com> I have been working on another challenge that involves improving the Blackjack program so the players can wager an amount. If a player loses they will be removed from the game. I keep getting the error: ?NameError: global name 'bet' is not defined.? I know I came across this error before in a previous thread, but I am confused on how to solve this, since I am also trying to juggle it with inherited methods at the same time. Here is the old and new file for the blackjack program for comparison: http://old.nabble.com/file/p31966195/blackjack.py blackjack.py http://old.nabble.com/file/p31966195/blackjackbetting.py blackjackbetting.py -- View this message in context: http://old.nabble.com/Blackjack-Betting-tp31966195p31966195.html Sent from the Python - tutor mailing list archive at Nabble.com. From gagnrath at verizon.net Thu Jun 30 20:03:13 2011 From: gagnrath at verizon.net (gagnrath at verizon.net) Date: Thu, 30 Jun 2011 13:03:13 -0500 (CDT) Subject: [Tutor] Copying Files Message-ID: <1661199868.2327778.1309456994032.JavaMail.root@vznit170070> I was using glob and shutil to copy logs from one location to another successfully, however, I have run into a snag when trying to copy a directory. Not sure how to fix this. Current Code is as follows: for file in glob.glob("/drbd1/monitorcenter/Apps/WEB-INF/*"): #This line is holding up the script due to copying a directory and not a single file shutil.copy(file, path_2_b_2) Any ideas? From g.nius.ck at gmail.com Thu Jun 30 21:05:24 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Thu, 30 Jun 2011 15:05:24 -0400 Subject: [Tutor] Conceptual Question About Use of Python for Employee Training Program In-Reply-To: <20110625160852.0476cb63@jabbar> References: <1309007894.48569.YahooMailRC@web35301.mail.mud.yahoo.com> <20110625160852.0476cb63@jabbar> Message-ID: What's step 4? On Sat, Jun 25, 2011 at 10:08 AM, Mac Ryan wrote: > On Sat, 25 Jun 2011 06:18:14 -0700 (PDT) > Adam Carr wrote: > > > Good Morning: > > > > I am very new to Python but I am enjoying the learning process. I > > have a question about the application of Python to a problem at the > > industrial business where I work. My two main questions are: > > > > 1. Can Python be used to achieve the goals of the possible project? > > 2. Where are the best places to look (books, blogs, websites, etc.) > > for programming examples or modules that would help me begin to > > assemble and test some code? > > > > We currently have a Windows-PC based safety training program that was > > put together in MS Access around 2001.... > > > > > Thanks in advance for taking the time to read my long note. I > > appreciate any help or direction that can be offered. > > Hi Adam, > > from the way you describe your problem, to me the obvious > answer would be "web application". This way you will be able to: > > 1. Make sure all employees will use the latest up-to-date training > material and software version. > > 2. Have a central DB able to track employees' activity (this opens up > the possibility for extra functionalities like sending a "gentle > reminder e-mail" to those who are not taking tests frequently > enough, statistics on what topics employees struggle most with, > etc...) > > 3. Be platform independent. > > 5. Save time on developing the GUI (which - done properly - is a very > time consuming part of desktop projects). > > That said, python is a great tool for web apps too. I personally looked > a bit into Django (www.djangoproject.com), which is one of the python > web frameworks and I was impressed by the speed you can prototype a > fully working application. > > As for presenting the training material, for iteration #1 I would > simply make them available as a download link. But in following > iteration of the project I would also integrate them with the web (so > as to make the entire application truly portable. I once used S5 for a > project. Here you can see a presentation of it that is - coherentely - > done with the standard presented: > http://meyerweb.com/eric/tools/s5/s5-intro.html#slide1 > However an alternative I did not experiment with is XOXO, which I read > has python code examples available (see > http://microformats.org/wiki/xoxo-sample-code-python) > > HTH, > Mac. > _______________________________________________ > 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 g.nius.ck at gmail.com Thu Jun 30 21:37:09 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Thu, 30 Jun 2011 15:37:09 -0400 Subject: [Tutor] Python GUI In-Reply-To: References: Message-ID: dude, what are all those story comments, did you just edit the mad lib program from Python for Absolute Beginners? On Wed, Jun 29, 2011 at 12:28 AM, David Merrick wrote: > # Guess My Number GUI > # Create a story based on user input > > from tkinter import * > import random > class Application(Frame): > """ GUI application that creates a story based on user input. """ > def __init__(self, master): > """ Initialize Frame. """ > super(Application, self).__init__(master) > self.grid() > self.create_widgets() > > def create_widgets(self): > """ Create widgets to get story information and to display story. > """ > # create instruction label > Label(self, > text = "Welcome to 'Guess My Number'!\n\nI'm thinking of a > number between 1 and 100.\nTry to guess it in as few attempts as possible." > ).grid(row = 0, column = 0, columnspan = 2, sticky = W) > > > > # create a label for body parts radio buttons > Label(self, > text = "Take a guess:" > ).grid(row = 6, column = 0, sticky = W) > self.numberEnt = Entry(self) > self.numberEnt.grid(row = 6, column = 1, sticky = W) > > # create a submit button > Button(self, > text = "Click to see if you got it", > command = self.testNumber > ).grid(row = 7, column = 0, sticky = W) > > self.numberTxt = Text(self, width = 75, height = 10, wrap = WORD) > self.numberTxt.grid(row = 8, column = 0, columnspan = 4) > > def testNumber(self): > """ Fill text box with new story based on user input. """ > # get values from the GUI > > # create the story > > guess = int(self.numberEnt.get()) > tries = 1 > > while guess != the_number: > if guess > the_number: > number += "Lower..." > else: > number += "Higher..." > guess = int(self.numberEnt.get()) > tries += 1 > > # display the text > self.numberTxt.delete(0.0, END) > self.numberTxt.insert(0.0, number) > > > number += "You guessed it! The number was" + the_number > number += "And it only took you " + tries + " tries!\n" > self.numberTxt.delete(0.0, END) > self.numberTxt.insert(0.0, number) > > > > # main > number = "" > the_number = random.randint(1, 100) > root = Tk() > root.title("Mad Lib") > app = Application(root) > root.mainloop() > > *Output* > > Traceback (most recent call last): > File "I:\Python\programs\guess_my_ numberChapter10.py", line 60, in > > number += "You guessed it! The number was" + the_number > NameError: name 'number' is not defined > > Any ides??????????? Is my code going to work apart from this > problem????????????? > > -- > Dave Merrick > > merrickdav at gmail.com > > Ph 03 3423 121 > Cell 027 3089 169 > > _______________________________________________ > 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 g.nius.ck at gmail.com Thu Jun 30 21:32:33 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Thu, 30 Jun 2011 15:32:33 -0400 Subject: [Tutor] Zipping files and Mysql In-Reply-To: <1519748939.2182300.1309203945026.JavaMail.root@vznit170128> References: <1519748939.2182300.1309203945026.JavaMail.root@vznit170128> Message-ID: /myfiles/my_db/ needs to be a string that right there is trying to divide nothing by the variable called myfiles, divided by my_db, divide by nothing On Mon, Jun 27, 2011 at 3:45 PM, wrote: > I am trying to write a script that will dump a mysql db and then zip the > file. > > > I do know about mysqldb, but I was wondering if there is anything native to > the libraries that will allow me to do this without using a seperate piece. > Then after I gather the DBs, I need to zip them. I wrote the following, > but wanted to know if I am heading in the correct direction. > > zipfile.zipfile(/myfiles/my_db/, w, zip_stored) > _______________________________________________ > 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 g.nius.ck at gmail.com Thu Jun 30 21:43:29 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Thu, 30 Jun 2011 15:43:29 -0400 Subject: [Tutor] The Card Game In-Reply-To: References: <31961149.post@talk.nabble.com> Message-ID: I would go with __cmp__ which covers them all. 1 for greater, 0 for equal, -1 for less than. On Thu, Jun 30, 2011 at 5:35 AM, Alan Gauld wrote: > > "Vincent Balmori" wrote > >> I keep getting a Type Error since for the moment since the >> values of the cards cannot be compared due to their >> types. >> > > Please send the complete error text sincethat will tell us > where to look etc. > > I am thinking of creating a Card_Value class that will give each rank >> and suit a certain value. If there is also a more elegant way of handling >> some of the code in the main section that will be welcome. >> > > You can get cards to compare themselves by adding a few > more "magic methods". Then you can do stuff like > > if card1 < card2: > # .... > elif card2 > card1: > # .... > else:.... > > The methods you need to create are > __gt__(), __lt__(), __eq__(), __le__(), __ge__() > > for > > ,<,==,<=,>= >> > > operations. > > BTW, In your code you have a comparison using = instead of ==. > That will fail. > > 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 ramit.prasad at jpmchase.com Thu Jun 30 21:52:47 2011 From: ramit.prasad at jpmchase.com (Prasad, Ramit) Date: Thu, 30 Jun 2011 15:52:47 -0400 Subject: [Tutor] Blackjack Betting In-Reply-To: <31966195.post@talk.nabble.com> References: <31966195.post@talk.nabble.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2E4E8A78CE@EMARC112VS01.exchad.jpmchase.net> >I keep getting the error: ?NameError: global >name 'bet' is not defined.? I know I came across this error before in a >previous thread, but I am confused on how to solve this, since I am also >trying to juggle it with inherited methods at the same time. Telling us this without the stack trace is pretty unhelpful. The Python exceptions include a very good stack trace (with line numbers +- 1 line) and a decent description. This error means that wherever this error was raised was a reference to the name "bet" and it had no reference to any "bet" at that point. The reasons could be that you forgot to assign a value to the name first, maybe it was a typo, in a preceding function, forgot the reference to self, etc, etc. I took a *quick* look at the code and found this (I did not check for other problems or if this error happens in more than one place): class BJ_Player(BJ_Hand, Bet): """ A Blackjack Player. """ def is_hitting(self): response = games.ask_yes_no("\n" + self.name + ", do you want a hit? (Y/N): ") return response == "y" def bust(self): print(self.name, "busts.") self.lose() def lose(self): print(self.name, "loses.") betting = Bet() bet.stash -= bet.wager def win(self): print(self.name, "wins.") bet = Bet() bet.stash += bet.wager def push(self): print(self.name, "pushes.") There are a couple things wrong with this class. First, you never define an __init__ which might be technically okay but is unlikely to be what you want for any user defined class (especially one with multiple inheritance). Since there is no __init__ defined, it will call the first parent class BJ_Hand.__init__ but not the second parent class Bet.__init__ (if it has one). Next for BJ_Player.lose(), bet is never defined and thus neither is bet.stash. Maybe you meant betting.stash -= betting.wager? I bet if you ran lint/pylint on this module it would have told you the error without even having to run it. 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 Vincent Balmori Sent: Thursday, June 30, 2011 1:49 PM To: tutor at python.org Subject: [Tutor] Blackjack Betting I have been working on another challenge that involves improving the Blackjack program so the players can wager an amount. If a player loses they will be removed from the game. I keep getting the error: ?NameError: global name 'bet' is not defined.? I know I came across this error before in a previous thread, but I am confused on how to solve this, since I am also trying to juggle it with inherited methods at the same time. Here is the old and new file for the blackjack program for comparison: http://old.nabble.com/file/p31966195/blackjack.py blackjack.py http://old.nabble.com/file/p31966195/blackjackbetting.py blackjackbetting.py -- View this message in context: http://old.nabble.com/Blackjack-Betting-tp31966195p31966195.html Sent from the Python - tutor mailing list archive at Nabble.com. _______________________________________________ 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 Thu Jun 30 22:00:49 2011 From: ramit.prasad at jpmchase.com (Prasad, Ramit) Date: Thu, 30 Jun 2011 16:00:49 -0400 Subject: [Tutor] Copying Files In-Reply-To: <1661199868.2327778.1309456994032.JavaMail.root@vznit170070> References: <1661199868.2327778.1309456994032.JavaMail.root@vznit170070> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2E4E8A7911@EMARC112VS01.exchad.jpmchase.net> -----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 gagnrath at verizon.net Sent: Thursday, June 30, 2011 1:03 PM To: tutor at python.org Subject: [Tutor] Copying Files I was using glob and shutil to copy logs from one location to another successfully, however, I have run into a snag when trying to copy a directory. Not sure how to fix this. Current Code is as follows: for file in glob.glob("/drbd1/monitorcenter/Apps/WEB-INF/*"): #This line is holding up the script due to copying a directory and not a single file shutil.copy(file, path_2_b_2) Any ideas? Why not try shutil.copytree instead? Shutil.copytree('/drbd1/monitorcenter/Apps/WEB-INF', path_2_b_2 ) http://docs.python.org/library/shutil.html 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 alan.gauld at btinternet.com Thu Jun 30 23:04:42 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Thu, 30 Jun 2011 22:04:42 +0100 (BST) Subject: [Tutor] The Card Game In-Reply-To: References: <31961149.post@talk.nabble.com> Message-ID: <1309467882.54169.YahooMailRC@web86707.mail.ird.yahoo.com> I may be wrong but I thought __cmp__ was deprecated. In fact I thought it was one oof the things removed in Python v3.... But I may have just imagined it! :-) Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ ________________________________ From: Christopher King To: Alan Gauld Cc: tutor at python.org Sent: Thursday, 30 June, 2011 20:43:29 Subject: Re: [Tutor] The Card Game I would go with __cmp__ which covers them all. 1 for greater, 0 for equal, -1 for less than. On Thu, Jun 30, 2011 at 5:35 AM, Alan Gauld wrote: >"Vincent Balmori" wrote > >I keep getting a Type Error since for the moment since the >>values of the cards cannot be compared due to their >>types. >> Please send the complete error text sincethat will tell us where to look etc. I am thinking of creating a Card_Value class that will give each rank >and suit a certain value. If there is also a more elegant way of handling >some of the code in the main section that will be welcome. > You can get cards to compare themselves by adding a few more "magic methods". Then you can do stuff like if card1 < card2: # .... elif card2 > card1: # .... else:.... The methods you need to create are __gt__(), __lt__(), __eq__(), __le__(), __ge__() for ,<,==,<=,>= > operations. BTW, In your code you have a comparison using = instead of ==. That will fail. 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: