From ramit.prasad at jpmorgan.com Thu Sep 1 00:41:04 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Wed, 31 Aug 2011 18:41:04 -0400 Subject: [Tutor] Quote of the Day version 1.0 In-Reply-To: <CACipEsjQh_Of0eMKJRaOVz7P1LXpn5pyBjkDgEt5mCyu5b21Ow@mail.gmail.com> References: <CAON5Gn1h-uN=i=OoH1=m5TwVE-c8fzAFrCUE5kz77dtt_Ap7PQ@mail.gmail.com> <CACipEsjQh_Of0eMKJRaOVz7P1LXpn5pyBjkDgEt5mCyu5b21Ow@mail.gmail.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F164EFC4C@EMARC112VS01.exchad.jpmchase.net> [snip] > Do not hesitate to ask questions as I added tuple unpacking and string >formatting which you might not have covered in depth yet in your >tutorial. [snip] >author, quote = random.choice(quotes) >print "%s\n\tBy %s" % (quote, author) I figured I might as well add my preferred method of string formatting. :) print 'The quote "{0}" is by {1}. I {2} {1}'.format(quote, author, 'love') # although you might hate {1} ;) Ramit P.S. Notice the mixed quote convention. Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From questions.anon at gmail.com Thu Sep 1 01:17:45 2011 From: questions.anon at gmail.com (questions anon) Date: Thu, 1 Sep 2011 09:17:45 +1000 Subject: [Tutor] reclassify values in an array Message-ID: <CAN_=ogvJ36sGArRQa-CEek_pZo35gaPnWtLE3E-koA+ujvf5Ew@mail.gmail.com> Dear All, I have been going round in circles trying to solve something that sounds simple. I have a huge array and I would like to reclassify the values. Firstly just make them zeros and ones, for example if the values in the array are less than 100 make them 0 and if greater than 100 make them 1. And then finally sum them together. I have attempted a few methods, see code below. Any feedback will be greatly appreciated. Attempt 1: big_array=N.ma.concatenate(all_FFDI) for i in big_array: if i<100: i=0 elif i>=100: i=1 print big_array sum=big_array.sum(axis=0) print "the sum is", sum Attempt 2: big_array=N.ma.concatenate(all_FFDI) for i, value in enumerate(big_array): if value==100: big_array[i]=0 elif value>=100: big_array[i]=1 print big_array sum=big_array.sum(axis=0) print "the sum is", sum -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110901/a9258f4a/attachment.html> From alan.gauld at btinternet.com Thu Sep 1 01:23:02 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 01 Sep 2011 00:23:02 +0100 Subject: [Tutor] Quote of the Day version 1.0 In-Reply-To: <CAON5Gn1h-uN=i=OoH1=m5TwVE-c8fzAFrCUE5kz77dtt_Ap7PQ@mail.gmail.com> References: <CAON5Gn1h-uN=i=OoH1=m5TwVE-c8fzAFrCUE5kz77dtt_Ap7PQ@mail.gmail.com> Message-ID: <j3mfop$d2t$1@dough.gmane.org> On 31/08/11 20:14, Cranky Frankie wrote: > This code works. Now I just have to figure out: > - how to associate .py files in Ubuntu to IDLE You probably don't want to do that. IDLE is fine for developing code but you don't want to run it in IDLE for general use you want to use the interpreter. And the shebang (#!) line at the start will do that for you. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Sep 1 01:32:46 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 01 Sep 2011 00:32:46 +0100 Subject: [Tutor] meaning of % in: if n % x == 0: In-Reply-To: <201108312035.43801.lisi.reisz@gmail.com> References: <201108312035.43801.lisi.reisz@gmail.com> Message-ID: <j3mgb2$h2d$1@dough.gmane.org> On 31/08/11 20:35, Lisi wrote: > ?? If either n or x or both were 0, and % were the same thing as *, the > statement would be true, but from the context I don't think that % does mean > the same as *, because * appears very soon after in the same fragment of > code. It's the remainder operator: IF N MOD X = 0 in BASIC It's explained in the Simple Sequences topic of my tutorial and mentioned again in the Raw Materials topic under integers. The use of % as the operator goes back to C. Many of Python's operators are just inherited directly from C. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Sep 1 01:41:19 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 01 Sep 2011 00:41:19 +0100 Subject: [Tutor] reclassify values in an array In-Reply-To: <CAN_=ogvJ36sGArRQa-CEek_pZo35gaPnWtLE3E-koA+ujvf5Ew@mail.gmail.com> References: <CAN_=ogvJ36sGArRQa-CEek_pZo35gaPnWtLE3E-koA+ujvf5Ew@mail.gmail.com> Message-ID: <j3mgr2$jpj$1@dough.gmane.org> On 01/09/11 00:17, questions anon wrote: > Dear All, > I have been going round in circles trying to solve something that sounds > simple. I have a huge array and I would like to reclassify the values. > Firstly just make them zeros and ones,... > And then finally sum them together. And what has been the problem? > I have attempted a few methods, see code below. I'm not familiar with NumPy (which I assume is what you are using?) However the second approach looks more likely to succeed than the first. Assuming enumerate works with NumPy arrays. Is there any reason why you cannot use a normal list? Then it would just be: result = sum(1 for item in array if item >= 100) HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Thu Sep 1 02:09:47 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 01 Sep 2011 10:09:47 +1000 Subject: [Tutor] meaning of % in: if n % x == 0: In-Reply-To: <CAJmBOfnxJboHEGXzCTbUTs-M5YSp0wEvftevbD8w1XYjXEKGVQ@mail.gmail.com> References: <201108312035.43801.lisi.reisz@gmail.com> <CAJmBOfnxJboHEGXzCTbUTs-M5YSp0wEvftevbD8w1XYjXEKGVQ@mail.gmail.com> Message-ID: <4E5ECD4B.9010203@pearwood.info> Hugo Arts wrote: > n % y == 0 if n is divisible by y. This is useful in factoring prime > numbers If you find a way to factor *prime numbers*, you're doing something wrong. :) (By definition, a prime number has no factors apart from itself and one, which are trivial.) You mean, factorising numbers into the product of primes. -- Steven From bgailer at gmail.com Thu Sep 1 04:29:49 2011 From: bgailer at gmail.com (bob gailer) Date: Wed, 31 Aug 2011 22:29:49 -0400 Subject: [Tutor] meaning of % in: if n % x == 0: In-Reply-To: <j3mgb2$h2d$1@dough.gmane.org> References: <201108312035.43801.lisi.reisz@gmail.com> <j3mgb2$h2d$1@dough.gmane.org> Message-ID: <4E5EEE1D.9000007@gmail.com> % is not remainder - it is modulo. Difference shows up when left agument is negative. -- Bob Gailer 919-636-4239 Chapel Hill NC From hugo.yoshi at gmail.com Thu Sep 1 04:29:32 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Thu, 1 Sep 2011 04:29:32 +0200 Subject: [Tutor] meaning of % in: if n % x == 0: In-Reply-To: <4E5ECD4B.9010203@pearwood.info> References: <201108312035.43801.lisi.reisz@gmail.com> <CAJmBOfnxJboHEGXzCTbUTs-M5YSp0wEvftevbD8w1XYjXEKGVQ@mail.gmail.com> <4E5ECD4B.9010203@pearwood.info> Message-ID: <CAJmBOf=CoHwkkFMAP74dfTxGn_OdyYL1aKOvdNELKRh8Sohayg@mail.gmail.com> ah, my mistake. I was in a hurry writing that post, which is a really bad idea :/ On Thu, Sep 1, 2011 at 2:09 AM, Steven D'Aprano <steve at pearwood.info> wrote: > Hugo Arts wrote: > >> ?n % y == 0 if n is divisible by y. This is useful in factoring prime >> numbers > > If you find a way to factor *prime numbers*, you're doing something wrong. > > :) > > (By definition, a prime number has no factors apart from itself and one, > which are trivial.) > > You mean, factorising numbers into the product of primes. > > > > -- > Steven > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From walksloud at gmail.com Thu Sep 1 07:02:32 2011 From: walksloud at gmail.com (Andre' Walker-Loud) Date: Wed, 31 Aug 2011 22:02:32 -0700 Subject: [Tutor] reclassify values in an array In-Reply-To: <CAN_=ogvJ36sGArRQa-CEek_pZo35gaPnWtLE3E-koA+ujvf5Ew@mail.gmail.com> References: <CAN_=ogvJ36sGArRQa-CEek_pZo35gaPnWtLE3E-koA+ujvf5Ew@mail.gmail.com> Message-ID: <EE081F19-B0CF-4049-A575-7E70D0713C87@gmail.com> Hi anonymous questioner, Like Alan, I suspect you are using numpy as import numpy as N there is probably a numpy email list where this would be more appropriate (personally I don't object, but I don't want to speak for all the subscribers). the 2nd attempt is closer to the right answer. To help yourself answer the question, try > for i, value in enumerate(big_array): print i,value and see what you get. Are you allowed to compare value with 100? Then, when performing the sum, you are asking to sum over axis=0. I assume you are trying to sum all the individual elements, rather than sum the rows. asking to sum over axis=0 is telling numpy to treat each row as an object, and sum all those objects, preserving all other dimensions of your array. In your case, you have a 2 dimensional array, so summing over axis=0 is taking all the rows of your array (matrix) and summing them to produce a new row. Specifically, it will take the first entry of each row, and add them to make the first entry of the summed row, then likewise for each additional entry. In math language, you are doing r_j = sum_i big_array_{i,j} if you do big_array.sum() then it will sum all of the individual elements sum = sum_i sum_j big_array_{i,j} play around more with the interactive interpreter. If you try these things, and they fail, reproduce your code from the top to bottom, adding only one line at a time, and see what happens (at least for these simple short code snippets). That should help you improve your understanding faster - which I assume is one of your goals :) Andre On Aug 31, 2011, at 4:17 PM, questions anon wrote: > Dear All, > I have been going round in circles trying to solve something that sounds simple. I have a huge array and I would like to reclassify the values. Firstly just make them zeros and ones, for example if the values in the array are less than 100 make them 0 and if greater than 100 make them 1. And then finally sum them together. > I have attempted a few methods, see code below. Any feedback will be greatly appreciated. > > Attempt 1: > big_array=N.ma.concatenate(all_FFDI) > for i in big_array: > if i<100: > i=0 > elif i>=100: > i=1 > print big_array > sum=big_array.sum(axis=0) > print "the sum is", sum > > > Attempt 2: > big_array=N.ma.concatenate(all_FFDI) > for i, value in enumerate(big_array): > if value==100: > big_array[i]=0 > elif value>=100: > big_array[i]=1 > print big_array > sum=big_array.sum(axis=0) > print "the sum is", sum > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From sander.sweers at gmail.com Thu Sep 1 10:12:03 2011 From: sander.sweers at gmail.com (Sander Sweers) Date: Thu, 01 Sep 2011 10:12:03 +0200 Subject: [Tutor] reclassify values in an array In-Reply-To: <CAN_=ogvJ36sGArRQa-CEek_pZo35gaPnWtLE3E-koA+ujvf5Ew@mail.gmail.com> References: <CAN_=ogvJ36sGArRQa-CEek_pZo35gaPnWtLE3E-koA+ujvf5Ew@mail.gmail.com> Message-ID: <1314864723.5501.16.camel@Nokia-N900> On Thu,? 1 Sep 2011, 01:17:45 CEST, questions anon <questions.anon at gmail.com> wrote: > Firstly just make them zeros and ones, for example if the values in the > array are less than 100 make them 0 and if greater than 100 make them 1. > And then finally sum them together. > I have attempted a few methods, see code below. Any feedback will be > greatly appreciated. *If* you do not need the array after you summed you can do something like below (untested!): big_array = N.ma.concatenate(all_FFDI) rusult = 0 for i in big_array: if i >= 100: result += 1 greets sander -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110901/0d406101/attachment.html> From __peter__ at web.de Thu Sep 1 10:33:49 2011 From: __peter__ at web.de (Peter Otten) Date: Thu, 01 Sep 2011 10:33:49 +0200 Subject: [Tutor] reclassify values in an array References: <CAN_=ogvJ36sGArRQa-CEek_pZo35gaPnWtLE3E-koA+ujvf5Ew@mail.gmail.com> Message-ID: <j3ng0b$2jr$1@dough.gmane.org> questions anon wrote: > I have been going round in circles trying to solve something that sounds > simple. I have a huge array and I would like to reclassify the values. > Firstly just make them zeros and ones, for example if the values in the > array are less than 100 make them 0 and if greater than 100 make them 1. > And then finally sum them together. > I have attempted a few methods, see code below. Any feedback will be > greatly appreciated. >>> import numpy >>> all_FFDI = numpy.arange(60).reshape((3,4,5)) >>> all_FFDI array([[[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19]], [[20, 21, 22, 23, 24], [25, 26, 27, 28, 29], [30, 31, 32, 33, 34], [35, 36, 37, 38, 39]], [[40, 41, 42, 43, 44], [45, 46, 47, 48, 49], [50, 51, 52, 53, 54], [55, 56, 57, 58, 59]]]) >>> all_FFDI >= 25 array([[[False, False, False, False, False], [False, False, False, False, False], [False, False, False, False, False], [False, False, False, False, False]], [[False, False, False, False, False], [ True, True, True, True, True], [ True, True, True, True, True], [ True, True, True, True, True]], [[ True, True, True, True, True], [ True, True, True, True, True], [ True, True, True, True, True], [ True, True, True, True, True]]], dtype=bool) >>> (all_FFDI >= 25).sum() 35 From lisi.reisz at gmail.com Thu Sep 1 16:30:26 2011 From: lisi.reisz at gmail.com (Lisi) Date: Thu, 1 Sep 2011 15:30:26 +0100 Subject: [Tutor] SOLVED and thank you was: Re: meaning of % in: if n % x == 0: In-Reply-To: <201108312035.43801.lisi.reisz@gmail.com> References: <201108312035.43801.lisi.reisz@gmail.com> Message-ID: <201109011530.27042.lisi.reisz@gmail.com> This was meant to go to the list. I did notrealise that it had not until I looked at the list just now and couln't see my reply. Sorry, "delegbede", and sorry list. On Wednesday 31 August 2011 Lisi wrote: > ?? If either n or x or both were 0, and % were the same thing as *, the > statement would be true, but from the context I don't think that % does > mean the same as *, because * appears very soon after in the same fragment > of code. On Wednesday 31 August 2011 20:59:05 delegbede at dudupay.com wrote: > % is a remainder division. I think its called modulo. Yes! Thank you. :-) I ought to have been able to guess that it was modulo - shows that I am indeed becoming slow-witted. :-( Thank you, all three of you, for such fast and helpful responses. Lisi From rdmoores at gmail.com Thu Sep 1 16:32:01 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Thu, 1 Sep 2011 07:32:01 -0700 Subject: [Tutor] Is there a test for hashability? Message-ID: <CALMxxxkHy9REFm-uACW9xnoBRTWpm4wQYvrzyA5VnSrUypUk6g@mail.gmail.com> The glossary defines "hashable" as: hashable An object is hashable if it has a hash value which never changes during its lifetime (it needs a __hash__() method), and can be compared to other objects (it needs an __eq__() method). Hashable objects which compare equal must have the same hash value. Hashability makes an object usable as a dictionary key and a set member, because these data structures use the hash value internally. All of Python?s immutable built-in objects are hashable, while no mutable containers (such as lists or dictionaries) are. Objects which are instances of user-defined classes are hashable by default; they all compare unequal, and their hash value is their id(). I'm trying to write a general test for hashability. How can I test if an object has both a __hash__() method and an __eq__() method? Thanks, Dick Moores From eire1130 at gmail.com Thu Sep 1 16:51:47 2011 From: eire1130 at gmail.com (James Reynolds) Date: Thu, 1 Sep 2011 10:51:47 -0400 Subject: [Tutor] Is there a test for hashability? In-Reply-To: <CALMxxxkHy9REFm-uACW9xnoBRTWpm4wQYvrzyA5VnSrUypUk6g@mail.gmail.com> References: <CALMxxxkHy9REFm-uACW9xnoBRTWpm4wQYvrzyA5VnSrUypUk6g@mail.gmail.com> Message-ID: <CAE0jAbqGvVxXzQgk6tDQF5Kt-6xOx7jmTF9zJ17_BtGw1b4XSA@mail.gmail.com> On Thu, Sep 1, 2011 at 10:32 AM, Richard D. Moores <rdmoores at gmail.com>wrote: > The glossary defines "hashable" as: > > hashable > An object is hashable if it has a hash value which never changes > during its lifetime (it needs a __hash__() method), and can be > compared to other objects (it needs an __eq__() method). Hashable > objects which compare equal must have the same hash value. > > Hashability makes an object usable as a dictionary key and a set > member, because these data structures use the hash value internally. > > > All of Python?s immutable built-in objects are hashable, while no > mutable containers (such as lists or dictionaries) are. Objects which > are instances of user-defined classes are hashable by default; they > all compare unequal, and their hash value is their id(). > > I'm trying to write a general test for hashability. How can I test if > an object has both a __hash__() method and an __eq__() method? > > Thanks, > > Dick Moores > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > To test for a method within any object you can just go like this: >>> a = () >>> type(a) <type 'tuple'> >>> if '__hash__' in dir(a): print True True >>> if '__eq__' in dir(a): print True True >>> But, I think the method you are approaching it from will only test for hashability. For example, you could do this: >>> a = [] >>> type(a) <type 'list'> >>> if '__hash__' in dir(a): print True True >>> if '__eq__' in dir(a): print True True >>> and then do this: >>> b = [] >>> c = {b:1} Traceback (most recent call last): File "<pyshell#36>", line 1, in <module> c = {b:1} TypeError: unhashable type: 'list' here is the dir for a list (not hashable): >>> dir(b) ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] here is the dir for a tuple (hashable): >>> dir(()) ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index'] What I would probably do though is use the built in method hash so you could do something like this: >>> a = 'a' >>> b = () >>> c = [] >>> print type(a), type(b), type(c) <type 'str'> <type 'tuple'> <type 'list'> >>> print hash(a) -468864544 >>> print hash(b) 3527539 >>> print hash(c) Traceback (most recent call last): File "<pyshell#48>", line 1, in <module> print hash(c) TypeError: unhashable type: 'list' >>> You can then use try, except to catch it on an as needed basis. Not sure if this answers the question you are asking though. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110901/12029ba9/attachment.html> From rdmoores at gmail.com Thu Sep 1 17:28:26 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Thu, 1 Sep 2011 08:28:26 -0700 Subject: [Tutor] Is there a test for hashability? In-Reply-To: <CAE0jAbqGvVxXzQgk6tDQF5Kt-6xOx7jmTF9zJ17_BtGw1b4XSA@mail.gmail.com> References: <CALMxxxkHy9REFm-uACW9xnoBRTWpm4wQYvrzyA5VnSrUypUk6g@mail.gmail.com> <CAE0jAbqGvVxXzQgk6tDQF5Kt-6xOx7jmTF9zJ17_BtGw1b4XSA@mail.gmail.com> Message-ID: <CALMxxxnkC0+Q5ezTvf1m_LCTQ4cDAu2XjG2whYnutpyUv=sztA@mail.gmail.com> Thanks, James, from your ideas I've come up with this function as a general test for hashibility of any object: def is_hashable(object): try: if hash(object): return True except TypeError: return False But is it? It returns True for ints, floats, sets, tuples, strings, functions; and False for lists Dick From hugo.yoshi at gmail.com Thu Sep 1 17:37:50 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Thu, 1 Sep 2011 17:37:50 +0200 Subject: [Tutor] Is there a test for hashability? In-Reply-To: <CALMxxxnkC0+Q5ezTvf1m_LCTQ4cDAu2XjG2whYnutpyUv=sztA@mail.gmail.com> References: <CALMxxxkHy9REFm-uACW9xnoBRTWpm4wQYvrzyA5VnSrUypUk6g@mail.gmail.com> <CAE0jAbqGvVxXzQgk6tDQF5Kt-6xOx7jmTF9zJ17_BtGw1b4XSA@mail.gmail.com> <CALMxxxnkC0+Q5ezTvf1m_LCTQ4cDAu2XjG2whYnutpyUv=sztA@mail.gmail.com> Message-ID: <CAJmBOfng_9+3ny_7Oq1xONfqk_qtksjey6FYQ+3BUzdpYj0QGA@mail.gmail.com> On Thu, Sep 1, 2011 at 5:28 PM, Richard D. Moores <rdmoores at gmail.com> wrote: > Thanks, James, from your ideas I've come up with this function as a > general test for hashibility of any object: > > def is_hashable(object): > ? ?try: > ? ? ? ?if hash(object): > ? ? ? ? ? ?return True > ? ?except TypeError: > ? ? ? ?return False > > But is it? ?It returns True for ints, floats, sets, tuples, strings, > functions; and False for lists > > Dick Are you sure? In my testing it returns False for sets, but True for frozensets as it should. From eire1130 at gmail.com Thu Sep 1 17:58:59 2011 From: eire1130 at gmail.com (James Reynolds) Date: Thu, 1 Sep 2011 11:58:59 -0400 Subject: [Tutor] Is there a test for hashability? In-Reply-To: <CAJmBOfng_9+3ny_7Oq1xONfqk_qtksjey6FYQ+3BUzdpYj0QGA@mail.gmail.com> References: <CALMxxxkHy9REFm-uACW9xnoBRTWpm4wQYvrzyA5VnSrUypUk6g@mail.gmail.com> <CAE0jAbqGvVxXzQgk6tDQF5Kt-6xOx7jmTF9zJ17_BtGw1b4XSA@mail.gmail.com> <CALMxxxnkC0+Q5ezTvf1m_LCTQ4cDAu2XjG2whYnutpyUv=sztA@mail.gmail.com> <CAJmBOfng_9+3ny_7Oq1xONfqk_qtksjey6FYQ+3BUzdpYj0QGA@mail.gmail.com> Message-ID: <CAE0jAbpq1i+gPDnAP9h7KJsik4PO9hsganywY3sX+V4Y_xFOkQ@mail.gmail.com> On Thu, Sep 1, 2011 at 11:37 AM, Hugo Arts <hugo.yoshi at gmail.com> wrote: > On Thu, Sep 1, 2011 at 5:28 PM, Richard D. Moores <rdmoores at gmail.com> > wrote: > > Thanks, James, from your ideas I've come up with this function as a > > general test for hashibility of any object: > > > > def is_hashable(object): > > try: > > if hash(object): > > return True > > except TypeError: > > return False > > > > But is it? It returns True for ints, floats, sets, tuples, strings, > > functions; and False for lists > > > > Dick > > Are you sure? In my testing it returns False for sets, but True for > frozensets as it should. > I agree with hugo, I just tested with all of these: a = 'a' b = [] c = 1 d = () e = set() f = frozenset() it gave the correct response for each a = 'a' - True b = [] - False c = 1 - True d = () - True e = set() - False f = frozenset() - True -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110901/cc94a8b6/attachment-0001.html> From cfuller084 at thinkingplanet.net Thu Sep 1 20:30:55 2011 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Thu, 1 Sep 2011 13:30:55 -0500 Subject: [Tutor] Is there a test for hashability? In-Reply-To: <CALMxxxnkC0+Q5ezTvf1m_LCTQ4cDAu2XjG2whYnutpyUv=sztA@mail.gmail.com> References: <CALMxxxkHy9REFm-uACW9xnoBRTWpm4wQYvrzyA5VnSrUypUk6g@mail.gmail.com> <CAE0jAbqGvVxXzQgk6tDQF5Kt-6xOx7jmTF9zJ17_BtGw1b4XSA@mail.gmail.com> <CALMxxxnkC0+Q5ezTvf1m_LCTQ4cDAu2XjG2whYnutpyUv=sztA@mail.gmail.com> Message-ID: <201109011330.56342.cfuller084@thinkingplanet.net> On Thursday 01 September 2011, Richard D. Moores wrote: > Thanks, James, from your ideas I've come up with this function as a > general test for hashibility of any object: > > def is_hashable(object): > try: > if hash(object): > return True > except TypeError: > return False > > But is it? It returns True for ints, floats, sets, tuples, strings, > functions; and False for lists > > Dick > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor You shouldn't be checking the truth value of the hash. If it's zero, this function will fall through and return None! def is_hashable(object): try: hash(object): return True except TypeError: return False Is what you want. Cheers From emile at fenx.com Thu Sep 1 21:47:40 2011 From: emile at fenx.com (Emile van Sebille) Date: Thu, 01 Sep 2011 12:47:40 -0700 Subject: [Tutor] Is there a test for hashability? In-Reply-To: <201109011330.56342.cfuller084@thinkingplanet.net> References: <CALMxxxkHy9REFm-uACW9xnoBRTWpm4wQYvrzyA5VnSrUypUk6g@mail.gmail.com> <CAE0jAbqGvVxXzQgk6tDQF5Kt-6xOx7jmTF9zJ17_BtGw1b4XSA@mail.gmail.com> <CALMxxxnkC0+Q5ezTvf1m_LCTQ4cDAu2XjG2whYnutpyUv=sztA@mail.gmail.com> <201109011330.56342.cfuller084@thinkingplanet.net> Message-ID: <j3onh6$h8j$1@dough.gmane.org> On 9/1/2011 11:30 AM Chris Fuller said... > On Thursday 01 September 2011, Richard D. Moores wrote: >> Thanks, James, from your ideas I've come up with this function as a >> general test for hashibility of any object: >> >> def is_hashable(object): >> try: >> if hash(object): >> return True >> except TypeError: >> return False >> >> But is it? It returns True for ints, floats, sets, tuples, strings, >> functions; and False for lists >> >> Dick >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > You shouldn't be checking the truth value of the hash. If it's zero, this > function will fall through and return None! > > def is_hashable(object): > try: > hash(object): > return True > except TypeError: > return False > > Is what you want. You should, of course, express it as valid python code though. :) def is_hashable(object): try: hash(object) return True except TypeError: return False From g.nius.ck at gmail.com Thu Sep 1 21:54:59 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Thu, 1 Sep 2011 15:54:59 -0400 Subject: [Tutor] Quote of the Day version 1.0 In-Reply-To: <CAON5Gn1h-uN=i=OoH1=m5TwVE-c8fzAFrCUE5kz77dtt_Ap7PQ@mail.gmail.com> References: <CAON5Gn1h-uN=i=OoH1=m5TwVE-c8fzAFrCUE5kz77dtt_Ap7PQ@mail.gmail.com> Message-ID: <CAKBg9Z1xha=mfMS5C4sBPTM6amcDtNFaSQHWomHhKZbAePw88w@mail.gmail.com> I would use a tuple of dictionaries. import random quotes = ( {'author':"Kahlil Gibran", 'quote':"A candle loses nothing of its light when lighting another."), #My favorite {'author':"Henrik Ibsen", 'quote':"The strongest man in the world is he who stands most alone."}) quote = random.choice(quotes) print "{quote}\n\tBy {author}".format(**quote) I use the dictionaries, because your not just storing a list of strings, your storing two strings of different purposes. I store the dictionaries in a tuple, because they are all quotes, but they currently never change during the course of the program. Some quotes have been omitted due to my laziness. I have not tested or debugged this code(I had to leave you something to do.) -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110901/51f61837/attachment.html> From rdmoores at gmail.com Thu Sep 1 22:06:58 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Thu, 1 Sep 2011 13:06:58 -0700 Subject: [Tutor] Is there a test for hashability? In-Reply-To: <j3onh6$h8j$1@dough.gmane.org> References: <CALMxxxkHy9REFm-uACW9xnoBRTWpm4wQYvrzyA5VnSrUypUk6g@mail.gmail.com> <CAE0jAbqGvVxXzQgk6tDQF5Kt-6xOx7jmTF9zJ17_BtGw1b4XSA@mail.gmail.com> <CALMxxxnkC0+Q5ezTvf1m_LCTQ4cDAu2XjG2whYnutpyUv=sztA@mail.gmail.com> <201109011330.56342.cfuller084@thinkingplanet.net> <j3onh6$h8j$1@dough.gmane.org> Message-ID: <CALMxxxkRx7tMXG=sZOLo3cBe0pUUQhk_mkcR6yvmeXcLPJFxoA@mail.gmail.com> def is_hashable(object): try: hash(object) return True except TypeError: return False it is then. Thanks to all! Dick From g.nius.ck at gmail.com Thu Sep 1 22:10:53 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Thu, 1 Sep 2011 16:10:53 -0400 Subject: [Tutor] [Python-ideas] aliasing In-Reply-To: <CAKBg9Z1gUT_roymy=UAvwJ+1iQS8HJBQzU3V0iKxA-BToxgtQQ@mail.gmail.com> References: <mailman.2909.1314804002.27777.python-ideas@python.org> <6BA1535A-8DB5-425A-94B5-8AD3AFA96AEE@gmail.com> <CAKBg9Z1gUT_roymy=UAvwJ+1iQS8HJBQzU3V0iKxA-BToxgtQQ@mail.gmail.com> Message-ID: <CAKBg9Z0jgQif0xaHmjAkz5VbaTHSaCVagNYnMQHCjxEmKSRVNA@mail.gmail.com> > > ------------------------ > >>> list = [3,] > >>> a = list > >>> list[0] = 6 > >>> a[0] > 3 > ------------------------- > Slight error in my code. It should be. ------------------------ >>> list = [3,] >>> a = list >>> list[0] = 6 >>> a[0] 6 ------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110901/cbc609b3/attachment.html> From cfuller084 at thinkingplanet.net Thu Sep 1 21:29:15 2011 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Thu, 1 Sep 2011 14:29:15 -0500 Subject: [Tutor] Is there a test for hashability? In-Reply-To: <201109011330.56342.cfuller084@thinkingplanet.net> References: <CALMxxxkHy9REFm-uACW9xnoBRTWpm4wQYvrzyA5VnSrUypUk6g@mail.gmail.com> <CALMxxxnkC0+Q5ezTvf1m_LCTQ4cDAu2XjG2whYnutpyUv=sztA@mail.gmail.com> <201109011330.56342.cfuller084@thinkingplanet.net> Message-ID: <201109011429.16131.cfuller084@thinkingplanet.net> On Thursday 01 September 2011, Chris Fuller wrote: > On Thursday 01 September 2011, Richard D. Moores wrote: > > Thanks, James, from your ideas I've come up with this function as a > > general test for hashibility of any object: > > > > def is_hashable(object): > > try: > > if hash(object): > > return True > > > > except TypeError: > > return False > > > > But is it? It returns True for ints, floats, sets, tuples, strings, > > functions; and False for lists > > > > Dick > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > You shouldn't be checking the truth value of the hash. If it's zero, this > function will fall through and return None! > > def is_hashable(object): > try: > hash(object): > return True > except TypeError: > return False > > Is what you want. > > Cheers > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor *Ahem* def is_hashable(object): try: hash(object) except TypeError: return False return True From rdmoores at gmail.com Thu Sep 1 22:58:59 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Thu, 1 Sep 2011 13:58:59 -0700 Subject: [Tutor] Is there a test for hashability? In-Reply-To: <201109011429.16131.cfuller084@thinkingplanet.net> References: <CALMxxxkHy9REFm-uACW9xnoBRTWpm4wQYvrzyA5VnSrUypUk6g@mail.gmail.com> <CALMxxxnkC0+Q5ezTvf1m_LCTQ4cDAu2XjG2whYnutpyUv=sztA@mail.gmail.com> <201109011330.56342.cfuller084@thinkingplanet.net> <201109011429.16131.cfuller084@thinkingplanet.net> Message-ID: <CALMxxx=wmT1fa2F1TOnKvCXQUHJtiCZt5xenbAeSzbbtPy=zVA@mail.gmail.com> On Thu, Sep 1, 2011 at 12:29, Chris Fuller <cfuller084 at thinkingplanet.net> wrote: > *Ahem* > > def is_hashable(object): > ? try: > ? ? ? ?hash(object) > ? ?except TypeError: > ? ? ? ?return False > > ? ?return True Why is that preferred to def is_hashable(object): try: hash(object) return True except TypeError: return False ?? Dick From cfuller084 at thinkingplanet.net Fri Sep 2 00:42:02 2011 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Thu, 1 Sep 2011 17:42:02 -0500 Subject: [Tutor] Is there a test for hashability? In-Reply-To: <CALMxxx=wmT1fa2F1TOnKvCXQUHJtiCZt5xenbAeSzbbtPy=zVA@mail.gmail.com> References: <CALMxxxkHy9REFm-uACW9xnoBRTWpm4wQYvrzyA5VnSrUypUk6g@mail.gmail.com> <201109011429.16131.cfuller084@thinkingplanet.net> <CALMxxx=wmT1fa2F1TOnKvCXQUHJtiCZt5xenbAeSzbbtPy=zVA@mail.gmail.com> Message-ID: <201109011742.02542.cfuller084@thinkingplanet.net> On Thursday 01 September 2011, Richard D. Moores wrote: > On Thu, Sep 1, 2011 at 12:29, Chris Fuller > > <cfuller084 at thinkingplanet.net> wrote: > > *Ahem* > > > > def is_hashable(object): > > try: > > hash(object) > > except TypeError: > > return False > > > > return True > > Why is that preferred to > > def is_hashable(object): > try: > hash(object) > return True > except TypeError: > return False > > ?? > > Dick It's a style issue, really. Either would be fine, but I don't like mixing code-flow disrupting actions when it's easily avoided. Cheers From brown.helen at yahoo.com Fri Sep 2 02:55:04 2011 From: brown.helen at yahoo.com (Helen Brown) Date: Thu, 1 Sep 2011 17:55:04 -0700 (PDT) Subject: [Tutor] openpyxl Message-ID: <1314924904.68207.YahooMailNeo@web46311.mail.sp1.yahoo.com> Will someone share with me? a link where I can download subject in order for my script to run? Any assistance will help! Thanks, -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110901/4818adc1/attachment.html> From brown.helen at yahoo.com Fri Sep 2 03:03:58 2011 From: brown.helen at yahoo.com (Helen Brown) Date: Thu, 1 Sep 2011 18:03:58 -0700 (PDT) Subject: [Tutor] openpyxl Message-ID: <1314925438.67247.YahooMailNeo@web46302.mail.sp1.yahoo.com> Will someone share if there is a link where I can download to read a script with subject file? Thanks, -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110901/c1249c02/attachment.html> From rdmoores at gmail.com Fri Sep 2 03:04:47 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Thu, 1 Sep 2011 18:04:47 -0700 Subject: [Tutor] Is there a test for hashability? In-Reply-To: <201109011742.02542.cfuller084@thinkingplanet.net> References: <CALMxxxkHy9REFm-uACW9xnoBRTWpm4wQYvrzyA5VnSrUypUk6g@mail.gmail.com> <201109011429.16131.cfuller084@thinkingplanet.net> <CALMxxx=wmT1fa2F1TOnKvCXQUHJtiCZt5xenbAeSzbbtPy=zVA@mail.gmail.com> <201109011742.02542.cfuller084@thinkingplanet.net> Message-ID: <CALMxxxku5F_LieC0JMG6hW9uGUrnDPDuG7Tk95kdQwnjPxiiVw@mail.gmail.com> Ah. I'll follow you with that. Thanks, Dick On Thu, Sep 1, 2011 at 15:42, Chris Fuller <cfuller084 at thinkingplanet.net> wrote: > On Thursday 01 September 2011, Richard D. Moores wrote: >> On Thu, Sep 1, 2011 at 12:29, Chris Fuller >> >> <cfuller084 at thinkingplanet.net> wrote: >> > *Ahem* >> > >> > def is_hashable(object): >> > ? try: >> > ? ? ? ?hash(object) >> > ? ?except TypeError: >> > ? ? ? ?return False >> > >> > ? ?return True >> >> Why is that preferred to >> >> def is_hashable(object): >> ? ? try: >> ? ? ? ? hash(object) >> ? ? ? ? return True >> ? ? except TypeError: >> ? ? ? ? return False >> >> ?? >> >> Dick > > It's a style issue, really. ?Either would be fine, but I don't like mixing > code-flow disrupting actions when it's easily avoided. > > Cheers > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From steve at pearwood.info Fri Sep 2 03:08:41 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 02 Sep 2011 11:08:41 +1000 Subject: [Tutor] Is there a test for hashability? In-Reply-To: <CALMxxxkHy9REFm-uACW9xnoBRTWpm4wQYvrzyA5VnSrUypUk6g@mail.gmail.com> References: <CALMxxxkHy9REFm-uACW9xnoBRTWpm4wQYvrzyA5VnSrUypUk6g@mail.gmail.com> Message-ID: <4E602C99.4040309@pearwood.info> Richard D. Moores wrote: > I'm trying to write a general test for hashability. How can I test if > an object has both a __hash__() method and an __eq__() method? Just because an object has a __hash__ method doesn't mean it is guaranteed to be hashable. The method might (deliberately, or accidentally) fail and raise an exception. >>> t = (1, 2, 3) >>> t.__hash__ <method-wrapper '__hash__' of tuple object at 0xb7f09fcc> >>> hash(t) -378539185 But: >>> t = (1, 2, [3]) >>> t.__hash__ <method-wrapper '__hash__' of tuple object at 0xb7f0c6e4> >>> hash(t) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: list objects are unhashable The only effective way to find out if an object is hashable is to try it and see. Even more effective is to avoid trying to find out whether it is hashable, and just use it, as required, and deal with the error if it isn't. This is the "Easy to get forgiveness than to ask permission" model of error handling, as opposed to "Look before you leap". For various reasons, LBYL can be risky... like in Quantum Mechanics, the very act of *looking* at an object might change its behaviour. (Methods can have side-effects.) So, even if is_hashable(obj) returns True, you can't *quite* be 100% certain that mydict[obj] will succeed until you try it. -- Steven From steve at pearwood.info Fri Sep 2 04:17:48 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 02 Sep 2011 12:17:48 +1000 Subject: [Tutor] Is there a test for hashability? In-Reply-To: <CALMxxxnkC0+Q5ezTvf1m_LCTQ4cDAu2XjG2whYnutpyUv=sztA@mail.gmail.com> References: <CALMxxxkHy9REFm-uACW9xnoBRTWpm4wQYvrzyA5VnSrUypUk6g@mail.gmail.com> <CAE0jAbqGvVxXzQgk6tDQF5Kt-6xOx7jmTF9zJ17_BtGw1b4XSA@mail.gmail.com> <CALMxxxnkC0+Q5ezTvf1m_LCTQ4cDAu2XjG2whYnutpyUv=sztA@mail.gmail.com> Message-ID: <4E603CCC.7090908@pearwood.info> Richard D. Moores wrote: > Thanks, James, from your ideas I've come up with this function as a > general test for hashibility of any object: > > def is_hashable(object): > try: > if hash(object): > return True > except TypeError: > return False No need for the "if hash" test, just try hash: def is_hashable(obj): try: hash(object) return True except TypeError: return False -- Steven From steve at pearwood.info Fri Sep 2 04:57:16 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 2 Sep 2011 12:57:16 +1000 Subject: [Tutor] Is there a test for hashability? In-Reply-To: <4E603CCC.7090908@pearwood.info> References: <CALMxxxkHy9REFm-uACW9xnoBRTWpm4wQYvrzyA5VnSrUypUk6g@mail.gmail.com> <CAE0jAbqGvVxXzQgk6tDQF5Kt-6xOx7jmTF9zJ17_BtGw1b4XSA@mail.gmail.com> <CALMxxxnkC0+Q5ezTvf1m_LCTQ4cDAu2XjG2whYnutpyUv=sztA@mail.gmail.com> <4E603CCC.7090908@pearwood.info> Message-ID: <20110902025716.GA31597@sylar> On Fri, Sep 02, 2011 at 12:17:48PM +1000, Steven D'Aprano wrote: > Richard D. Moores wrote: > >Thanks, James, from your ideas I've come up with this function as a > >general test for hashibility of any object: > > > >def is_hashable(object): > > try: > > if hash(object): > > return True > > except TypeError: > > return False > > No need for the "if hash" test, just try hash: Er, except this was already discussed :) Sorry for the noise. -- Steven From steve at pearwood.info Fri Sep 2 05:10:15 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 2 Sep 2011 13:10:15 +1000 Subject: [Tutor] openpyxl In-Reply-To: <1314924904.68207.YahooMailNeo@web46311.mail.sp1.yahoo.com> References: <1314924904.68207.YahooMailNeo@web46311.mail.sp1.yahoo.com> Message-ID: <20110902031015.GB31597@sylar> On Thu, Sep 01, 2011 at 05:55:04PM -0700, Helen Brown wrote: > Will someone share with me? a link where I can download subject in order for my script to run? Any assistance will help! Did you try googling for it? http://duckduckgo.com/?q=openpyxl http://www.bing.com/search?q=openpyxl http://au.search.yahoo.com/search?p=openpyxl http://www.dogpile.com/info.dogpl/search/web?q=openpyxl Even Google can find it :) http://www.google.com/search?q=openpyxl These days, I recommend using Duck Duck Go because, unlike Google, it doesn't track or bubble your searches: http://donttrack.us/ http://dontbubble.us/ -- Steven From jjhartley at gmail.com Fri Sep 2 06:48:41 2011 From: jjhartley at gmail.com (James Hartley) Date: Thu, 1 Sep 2011 21:48:41 -0700 Subject: [Tutor] use of logging module is shared by all? Message-ID: <CAKeNXXs-P1CdFJ40-LEtLyEamNdZxZTcgmFNSQgYzfCAqSEBgw@mail.gmail.com> I'm just needing to verify some behavior. Functionality within the logging module is exercised by calling functions defined within the module itself. I am using SQLAlchemy for database access, but it can be configured to dump out intermediate access information & queries to the logging module -- which is great. It really helps in debugging. However, if I want to write to a log which is separate from what SQLAlchemy is doing, am I correct stating that I will not be able to do so through the logging module? Thanks for any insight which can be shared. Jim -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110901/f426537a/attachment.html> From rdmoores at gmail.com Fri Sep 2 06:53:00 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Thu, 1 Sep 2011 21:53:00 -0700 Subject: [Tutor] Is there a test for hashability? In-Reply-To: <4E602C99.4040309@pearwood.info> References: <CALMxxxkHy9REFm-uACW9xnoBRTWpm4wQYvrzyA5VnSrUypUk6g@mail.gmail.com> <4E602C99.4040309@pearwood.info> Message-ID: <CALMxxxkY+05e+YWE1=5R3jzYLA0q5nsrdBzkuwJhgbD5bpp12Q@mail.gmail.com> On Thu, Sep 1, 2011 at 18:08, Steven D'Aprano <steve at pearwood.info> wrote: > Richard D. Moores wrote: >> >> I'm trying to write a general test for hashability. How can I test if >> an object has both a ?__hash__() method and an __eq__() method? > > > Just because an object has a __hash__ method doesn't mean it is guaranteed > to be hashable. The method might (deliberately, or accidentally) fail and > raise an exception. > >>>> t = (1, 2, 3) >>>> t.__hash__ > <method-wrapper '__hash__' of tuple object at 0xb7f09fcc> >>>> hash(t) > -378539185 > > But: > >>>> t = (1, 2, [3]) >>>> t.__hash__ > <method-wrapper '__hash__' of tuple object at 0xb7f0c6e4> >>>> hash(t) > Traceback (most recent call last): > ?File "<stdin>", line 1, in <module> > TypeError: list objects are unhashable > > > The only effective way to find out if an object is hashable is to try it and > see. > > Even more effective is to avoid trying to find out whether it is hashable, > and just use it, as required, and deal with the error if it isn't. This is > the "Easy to get forgiveness than to ask permission" model of error > handling, as opposed to "Look before you leap". > > For various reasons, LBYL can be risky... like in Quantum Mechanics, the > very act of *looking* at an object might change its behaviour. (Methods can > have side-effects.) So, even if is_hashable(obj) returns True, you can't > *quite* be 100% certain that mydict[obj] will succeed until you try it. Steven, Do you have an actual example of an actual object for which "my" is_hashable(object) function would return the wrong answer? >>> def is_hashable(object): ... try: ... hash(object) ... except TypeError: ... return False ... return True ... >>> is_hashable((1, 2, [3])) False >>> Is that one? Dick From __peter__ at web.de Fri Sep 2 07:53:25 2011 From: __peter__ at web.de (Peter Otten) Date: Fri, 02 Sep 2011 07:53:25 +0200 Subject: [Tutor] use of logging module is shared by all? References: <CAKeNXXs-P1CdFJ40-LEtLyEamNdZxZTcgmFNSQgYzfCAqSEBgw@mail.gmail.com> Message-ID: <j3pqvg$hid$1@dough.gmane.org> James Hartley wrote: > I'm just needing to verify some behavior. > > Functionality within the logging module is exercised by calling functions > defined within the module itself. I am using SQLAlchemy for database > access, but it can be configured to dump out intermediate access > information > & queries to the logging module -- which is great. It really helps in > debugging. > > However, if I want to write to a log which is separate from what > SQLAlchemy is doing, am I correct stating that I will not be able to do so > through the logging module? > > Thanks for any insight which can be shared. Loggers are typically organized in a tree; sqlalchemy will probably log to logging.getLogger("sqlalchemy").warn("whatever") or something like logging.getLogger("sqlalchemy.some.sublogger").critical("test") You can prevent the rootlogger from seeing these messages with sq = logging.getLogger("sqlalchemy") sq.propagate = False If for example you want to see messages in stdout by default, but write SQLAlchemy's messages to a file you'd do (untested) import logging import sys logging.basicConfig(stream=sys.stdout) sq = logging.getLogger("sqalchemy") sqhandler = logging.FileHandler("alchemy.log") sqformatter = logging.Formatter(logging.BASIC_FORMAT) sqhandler.setFormatter(sqformatter) sq.addHandler(sqhandler) sq.propagate = False sq.critical("alchemy") # goes to file alchemy.log logging.getLogger("mine").critical("mine") # goes to stdout From jjhartley at gmail.com Fri Sep 2 08:16:09 2011 From: jjhartley at gmail.com (James Hartley) Date: Thu, 1 Sep 2011 23:16:09 -0700 Subject: [Tutor] use of logging module is shared by all? In-Reply-To: <j3pqvg$hid$1@dough.gmane.org> References: <CAKeNXXs-P1CdFJ40-LEtLyEamNdZxZTcgmFNSQgYzfCAqSEBgw@mail.gmail.com> <j3pqvg$hid$1@dough.gmane.org> Message-ID: <CAKeNXXtnbYz_pfq=wcGD9wKp3UHQe-T0wke5Zai8twpbdRNzNg@mail.gmail.com> Thanks, Peter for taking the time to respond. I need to study the reference further, & your comments pointed out some of my misconceptions. Thank you for clearing up some of my half-researched understanding. Jim On Thu, Sep 1, 2011 at 10:53 PM, Peter Otten <__peter__ at web.de> wrote: > James Hartley wrote: > > > I'm just needing to verify some behavior. > > > > Functionality within the logging module is exercised by calling functions > > defined within the module itself. I am using SQLAlchemy for database > > access, but it can be configured to dump out intermediate access > > information > > & queries to the logging module -- which is great. It really helps in > > debugging. > > > > However, if I want to write to a log which is separate from what > > SQLAlchemy is doing, am I correct stating that I will not be able to do > so > > through the logging module? > > > > Thanks for any insight which can be shared. > > Loggers are typically organized in a tree; sqlalchemy will probably log to > > logging.getLogger("sqlalchemy").warn("whatever") > > or something like > > logging.getLogger("sqlalchemy.some.sublogger").critical("test") > > You can prevent the rootlogger from seeing these messages with > > sq = logging.getLogger("sqlalchemy") > sq.propagate = False > > If for example you want to see messages in stdout by default, but write > SQLAlchemy's messages to a file you'd do (untested) > > import logging > import sys > logging.basicConfig(stream=sys.stdout) > > sq = logging.getLogger("sqalchemy") > sqhandler = logging.FileHandler("alchemy.log") > sqformatter = logging.Formatter(logging.BASIC_FORMAT) > sqhandler.setFormatter(sqformatter) > sq.addHandler(sqhandler) > sq.propagate = False > > sq.critical("alchemy") # goes to file alchemy.log > logging.getLogger("mine").critical("mine") # goes to stdout > > > _______________________________________________ > 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: <http://mail.python.org/pipermail/tutor/attachments/20110901/021c7066/attachment.html> From g.nius.ck at gmail.com Fri Sep 2 15:18:01 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Fri, 2 Sep 2011 09:18:01 -0400 Subject: [Tutor] [Python-ideas] Terminology for "earthshattering" [was: Add from __experimental__ import bla] In-Reply-To: <87mxeok5z0.fsf@uwakimon.sk.tsukuba.ac.jp> References: <CAMPUAFOFTjjxytsc=QJ0Eo6kV3KA1x917Kx+MC9tNeeCrDoy_Q@mail.gmail.com> <CAP7+vJLGCLkQV5MW9x8zznbh-L530ZtBoAwdBc4gP9qqW7jwgQ@mail.gmail.com> <CABicbJK8dTVgHFakCXcgf8HrB4Cmxb2KFRX5e=bAFCM2TEoSOA@mail.gmail.com> <CADiSq7fdVdOJBE0oPYnaY47dsmOHWzKi-R0khyq6Cxfia_EjJQ@mail.gmail.com> <CAP7+vJLp2pwPuAshAyhFxQA5vPw7VpRxJu1mCKyXZnwWbYK2Dg@mail.gmail.com> <1314569103.4640.19.camel@Gutsy> <CADiSq7fFqhWjbGuaheT7Cdo8N7ix0jZshr+j0Sw9gKwJOi1oaw@mail.gmail.com> <CAGu0AnvNvixsBnhXMyK=gG4ByK+Q-4tbXJpsGF7f5R92YP=ChQ@mail.gmail.com> <CADiSq7eLG1=U_4qJ2dgPiEGsjrtrVv3Qc4xmt3d3R3GgfsSY-A@mail.gmail.com> <CAB4yi1Pr5fuaR1uW8wY6k7MtxWP--tQ_XqW2YYyAGDCv=kh49Q@mail.gmail.com> <58780826-87be-436f-b777-937e41691e90@m35g2000prl.googlegroups.com> <871uw2l0vs.fsf@uwakimon.sk.tsukuba.ac.jp> <CAP7+vJKS9xQA2t6Ee=WN+Z0zRtf15qC=a+yHsMhYZy_jN3pRDw@mail.gmail.com> <20110831111946.22bac764@resist.wooz.org> <CAP7+vJL3Z0Lr3+a3m-qYW76+cmR7YWajCw9OU8U2oDdvSbOZCQ@mail.gmail.com> <20110831185635.744c9624@pitrou.net> <CAP7+vJJoLeF9-G7WLmb4bWSum-E6=fH8nge-Hmr--o-wp17e3Q@mail.gmail.com> <87mxeok5z0.fsf@uwakimon.sk.tsukuba.ac.jp> Message-ID: <CAKBg9Z2r1oV5+ie4eD8OWEfBvkdLuwqKXxkrmyWAPYFqBFZfEw@mail.gmail.com> How about double dot, dot, and no dot releases, (for the number of decimals in it.) I do believe having terminology for this would be good and cool. *+ 0.5* -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110902/371cda26/attachment.html> From g.nius.ck at gmail.com Fri Sep 2 15:19:55 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Fri, 2 Sep 2011 09:19:55 -0400 Subject: [Tutor] [Python-ideas] Terminology for "earthshattering" [was: Add from __experimental__ import bla] In-Reply-To: <87mxeok5z0.fsf@uwakimon.sk.tsukuba.ac.jp> References: <CAMPUAFOFTjjxytsc=QJ0Eo6kV3KA1x917Kx+MC9tNeeCrDoy_Q@mail.gmail.com> <CAP7+vJLGCLkQV5MW9x8zznbh-L530ZtBoAwdBc4gP9qqW7jwgQ@mail.gmail.com> <CABicbJK8dTVgHFakCXcgf8HrB4Cmxb2KFRX5e=bAFCM2TEoSOA@mail.gmail.com> <CADiSq7fdVdOJBE0oPYnaY47dsmOHWzKi-R0khyq6Cxfia_EjJQ@mail.gmail.com> <CAP7+vJLp2pwPuAshAyhFxQA5vPw7VpRxJu1mCKyXZnwWbYK2Dg@mail.gmail.com> <1314569103.4640.19.camel@Gutsy> <CADiSq7fFqhWjbGuaheT7Cdo8N7ix0jZshr+j0Sw9gKwJOi1oaw@mail.gmail.com> <CAGu0AnvNvixsBnhXMyK=gG4ByK+Q-4tbXJpsGF7f5R92YP=ChQ@mail.gmail.com> <CADiSq7eLG1=U_4qJ2dgPiEGsjrtrVv3Qc4xmt3d3R3GgfsSY-A@mail.gmail.com> <CAB4yi1Pr5fuaR1uW8wY6k7MtxWP--tQ_XqW2YYyAGDCv=kh49Q@mail.gmail.com> <58780826-87be-436f-b777-937e41691e90@m35g2000prl.googlegroups.com> <871uw2l0vs.fsf@uwakimon.sk.tsukuba.ac.jp> <CAP7+vJKS9xQA2t6Ee=WN+Z0zRtf15qC=a+yHsMhYZy_jN3pRDw@mail.gmail.com> <20110831111946.22bac764@resist.wooz.org> <CAP7+vJL3Z0Lr3+a3m-qYW76+cmR7YWajCw9OU8U2oDdvSbOZCQ@mail.gmail.com> <20110831185635.744c9624@pitrou.net> <CAP7+vJJoLeF9-G7WLmb4bWSum-E6=fH8nge-Hmr--o-wp17e3Q@mail.gmail.com> <87mxeok5z0.fsf@uwakimon.sk.tsukuba.ac.jp> Message-ID: <CAKBg9Z2xa22BiMO3hoxKVmtyi_RW9Bzk=Aj39iB65Ou0sq=kfg@mail.gmail.com> What about alpha-omega release, since its the end of many old programs, the beginning of many new, and it just sounds awesome. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110902/028c47e3/attachment.html> From lisi.reisz at gmail.com Fri Sep 2 16:11:26 2011 From: lisi.reisz at gmail.com (Lisi) Date: Fri, 2 Sep 2011 15:11:26 +0100 Subject: [Tutor] [Python-ideas] Terminology for "earthshattering" [was: Add from __experimental__ import bla] In-Reply-To: <CAKBg9Z2xa22BiMO3hoxKVmtyi_RW9Bzk=Aj39iB65Ou0sq=kfg@mail.gmail.com> References: <CAMPUAFOFTjjxytsc=QJ0Eo6kV3KA1x917Kx+MC9tNeeCrDoy_Q@mail.gmail.com> <87mxeok5z0.fsf@uwakimon.sk.tsukuba.ac.jp> <CAKBg9Z2xa22BiMO3hoxKVmtyi_RW9Bzk=Aj39iB65Ou0sq=kfg@mail.gmail.com> Message-ID: <201109021511.26196.lisi.reisz@gmail.com> On Friday 02 September 2011 14:19:55 Christopher King wrote: > it just sounds awesome. ??? To me it sounds like alphabet soup! Which is, of course, what, I would argue, it is. ;-) Lisi From alan.gauld at btinternet.com Fri Sep 2 16:55:57 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 02 Sep 2011 15:55:57 +0100 Subject: [Tutor] [Python-ideas] Terminology for "earthshattering" [was: Add from __experimental__ import bla] In-Reply-To: <CAKBg9Z2xa22BiMO3hoxKVmtyi_RW9Bzk=Aj39iB65Ou0sq=kfg@mail.gmail.com> References: <CAMPUAFOFTjjxytsc=QJ0Eo6kV3KA1x917Kx+MC9tNeeCrDoy_Q@mail.gmail.com> <CAP7+vJLp2pwPuAshAyhFxQA5vPw7VpRxJu1mCKyXZnwWbYK2Dg@mail.gmail.com> <1314569103.4640.19.camel@Gutsy> <CADiSq7fFqhWjbGuaheT7Cdo8N7ix0jZshr+j0Sw9gKwJOi1oaw@mail.gmail.com> <CAGu0AnvNvixsBnhXMyK=gG4ByK+Q-4tbXJpsGF7f5R92YP=ChQ@mail.gmail.com> <CADiSq7eLG1=U_4qJ2dgPiEGsjrtrVv3Qc4xmt3d3R3GgfsSY-A@mail.gmail.com> <CAB4yi1Pr5fuaR1uW8wY6k7MtxWP--tQ_XqW2YYyAGDCv=kh49Q@mail.gmail.com> <58780826-87be-436f-b777-937e41691e90@m35g2000prl.googlegroups.com> <871uw2l0vs.fsf@uwakimon.sk.tsukuba.ac.jp> <CAP7+vJKS9xQA2t6Ee=WN+Z0zRtf15qC=a+yHsMhYZy_jN3pRDw@mail.gmail.com> <20110831111946.22bac764@resist.wooz.org> <CAP7+vJL3Z0Lr3+a3m-qYW76+cmR7YWajCw9OU8U2oDdvSbOZCQ@mail.gmail.com> <20110831185635.744c9624@pitrou.net> <CAP7+vJJoLeF9-G7WLmb4bWSum-E6=fH8nge-Hmr--o-wp17e3Q@mail.gmail.com> <87mxeok5z0.fsf@uwakimon.sk.tsukuba.ac.jp> <CAKBg9Z2xa22BiMO3hoxKVmtyi_RW9Bzk=Aj39iB65Ou0sq=kfg@mail.gmail.com> Message-ID: <j3qqpt$7ea$1@dough.gmane.org> On 02/09/11 14:19, Christopher King wrote: > What about alpha-omega release, since its the end of many old programs, > the beginning of many new, and it just sounds awesome. Are you sure you meant to send this to the Python tutor group? It does not appear to be relevant unless I'm missing something? -- Alan G Tutor List moderator From questions.anon at gmail.com Sat Sep 3 00:27:34 2011 From: questions.anon at gmail.com (questions anon) Date: Sat, 3 Sep 2011 08:27:34 +1000 Subject: [Tutor] reclassify values in an array In-Reply-To: <j3ng0b$2jr$1@dough.gmane.org> References: <CAN_=ogvJ36sGArRQa-CEek_pZo35gaPnWtLE3E-koA+ujvf5Ew@mail.gmail.com> <j3ng0b$2jr$1@dough.gmane.org> Message-ID: <CAN_=ogucFYJhdy+O15UsGRsTPuiqtWTh7p2iJ5O=vkjFvC8QWA@mail.gmail.com> thank you for all of the resonses, I have attempted all of the suggestions. It is a numpy array so I can try another list if you would prefer but I thought I would show the error anyway. the error I am receiving is ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() on this code big_array=N.ma.concatenate(all_FFDI) for i, value in enumerate(big_array): if value==100: big_array[i]=0 elif value>=100: big_array[i]=1 print big_array On Thu, Sep 1, 2011 at 6:33 PM, Peter Otten <__peter__ at web.de> wrote: > questions anon wrote: > > > I have been going round in circles trying to solve something that sounds > > simple. I have a huge array and I would like to reclassify the values. > > Firstly just make them zeros and ones, for example if the values in the > > array are less than 100 make them 0 and if greater than 100 make them 1. > > And then finally sum them together. > > I have attempted a few methods, see code below. Any feedback will be > > greatly appreciated. > > >>> import numpy > >>> all_FFDI = numpy.arange(60).reshape((3,4,5)) > >>> all_FFDI > array([[[ 0, 1, 2, 3, 4], > [ 5, 6, 7, 8, 9], > [10, 11, 12, 13, 14], > [15, 16, 17, 18, 19]], > > [[20, 21, 22, 23, 24], > [25, 26, 27, 28, 29], > [30, 31, 32, 33, 34], > [35, 36, 37, 38, 39]], > > [[40, 41, 42, 43, 44], > [45, 46, 47, 48, 49], > [50, 51, 52, 53, 54], > [55, 56, 57, 58, 59]]]) > >>> all_FFDI >= 25 > array([[[False, False, False, False, False], > [False, False, False, False, False], > [False, False, False, False, False], > [False, False, False, False, False]], > > [[False, False, False, False, False], > [ True, True, True, True, True], > [ True, True, True, True, True], > [ True, True, True, True, True]], > > [[ True, True, True, True, True], > [ True, True, True, True, True], > [ True, True, True, True, True], > [ True, True, True, True, True]]], dtype=bool) > >>> (all_FFDI >= 25).sum() > 35 > > > _______________________________________________ > 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: <http://mail.python.org/pipermail/tutor/attachments/20110903/97d2bbe5/attachment.html> From walksloud at gmail.com Sat Sep 3 00:55:07 2011 From: walksloud at gmail.com (Andre' Walker-Loud) Date: Fri, 2 Sep 2011 15:55:07 -0700 Subject: [Tutor] reclassify values in an array In-Reply-To: <CAN_=ogucFYJhdy+O15UsGRsTPuiqtWTh7p2iJ5O=vkjFvC8QWA@mail.gmail.com> References: <CAN_=ogvJ36sGArRQa-CEek_pZo35gaPnWtLE3E-koA+ujvf5Ew@mail.gmail.com> <j3ng0b$2jr$1@dough.gmane.org> <CAN_=ogucFYJhdy+O15UsGRsTPuiqtWTh7p2iJ5O=vkjFvC8QWA@mail.gmail.com> Message-ID: <7962A53A-A8BF-416F-8D58-CBD71D0A5DEE@gmail.com> > thank you for all of the resonses, I have attempted all of the suggestions. It is a numpy array so I can try another list if you would prefer but I thought I would show the error anyway. > the error I am receiving is > ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() this is telling you that "value" is not a scalar element, but it has multiple dimensions. do the following: >>> big_array=N.ma.concatenate(all_FFDI) >>> print big_array.shape >>> print big_array[0].shape the first print will report the dimensionality of your big_array. The second print statement will tell you the dimensionality of the 0th element of big_array. This is the first value of "value" in your for loop. Only if the shape is given as "( )", a single (scalar) element, can you compare it to an integer or float. example >>> a = N.zeros([3]) #this builds a one-dimensional array with 3 elements and puts zeros for each value >>> a array([ 0., 0., 0.]) >>> a.shape (3,) >>> a[0].shape ( ) >>> a[0] 0. imagine you have a 2-dimensional array >>> b = N.zeros([3,3]) # a 3 by 3 array of zeros >>> b.shape (3, 3) >>> b[0] array([ 0., 0., 0.]) >>> for i,value in enumerate(b): ... print value [ 0., 0., 0.] [ 0., 0., 0.] [ 0., 0., 0.] you are trying to compare the "value" [ 0., 0., 0.], to an integer. This is why your code fails - your big_array is a multi-dimensional array. The above example is what I mean by "you should play around with the python interpreter". By doing these things (above) you will begin to learn the structure of these objects (defined in this case with numpy). Regards, Andre From questions.anon at gmail.com Mon Sep 5 06:21:31 2011 From: questions.anon at gmail.com (questions anon) Date: Mon, 5 Sep 2011 14:21:31 +1000 Subject: [Tutor] reclassify values in an array In-Reply-To: <7962A53A-A8BF-416F-8D58-CBD71D0A5DEE@gmail.com> References: <CAN_=ogvJ36sGArRQa-CEek_pZo35gaPnWtLE3E-koA+ujvf5Ew@mail.gmail.com> <j3ng0b$2jr$1@dough.gmane.org> <CAN_=ogucFYJhdy+O15UsGRsTPuiqtWTh7p2iJ5O=vkjFvC8QWA@mail.gmail.com> <7962A53A-A8BF-416F-8D58-CBD71D0A5DEE@gmail.com> Message-ID: <CAN_=ogsvS323+Nyp0bq9CoVeRLfZghem5c90yyUobU_Xx8_S9w@mail.gmail.com> Thanks all, that helped me work out that I needed to try something else. If anyone else needs to know what method worked: big_array=N.ma.concatenate(all_FFDI) for x in N.nditer(big_array, op_flags=['readwrite']): if x<100: x[...]=x=0 elif x>=100: x[...]=x=1 sum=big_array.sum(axis=0) On Sat, Sep 3, 2011 at 8:55 AM, Andre' Walker-Loud <walksloud at gmail.com>wrote: > > thank you for all of the resonses, I have attempted all of the > suggestions. It is a numpy array so I can try another list if you would > prefer but I thought I would show the error anyway. > > the error I am receiving is > > ValueError: The truth value of an array with more than one element is > ambiguous. Use a.any() or a.all() > > this is telling you that "value" is not a scalar element, but it has > multiple dimensions. > > do the following: > > >>> big_array=N.ma.concatenate(all_FFDI) > >>> print big_array.shape > > >>> print big_array[0].shape > > > the first print will report the dimensionality of your big_array. The > second print statement will tell you the dimensionality of the 0th element > of big_array. This is the first value of "value" in your for loop. > > Only if the shape is given as "( )", a single (scalar) element, can you > compare it to an integer or float. example > > >>> a = N.zeros([3]) #this builds a one-dimensional array with 3 elements > and puts zeros for each value > >>> a > array([ 0., 0., 0.]) > >>> a.shape > (3,) > >>> a[0].shape > ( ) > >>> a[0] > 0. > > imagine you have a 2-dimensional array > > >>> b = N.zeros([3,3]) # a 3 by 3 array of zeros > >>> b.shape > (3, 3) > >>> b[0] > array([ 0., 0., 0.]) > >>> for i,value in enumerate(b): > ... print value > [ 0., 0., 0.] > [ 0., 0., 0.] > [ 0., 0., 0.] > > you are trying to compare the "value" [ 0., 0., 0.], to an integer. This > is why your code fails - your big_array is a multi-dimensional array. > > The above example is what I mean by "you should play around with the python > interpreter". By doing these things (above) you will begin to learn the > structure of these objects (defined in this case with numpy). > > > Regards, > > Andre > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110905/cd0df9e3/attachment.html> From susana.delgado_s at utzmg.edu.mx Mon Sep 5 16:26:14 2011 From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez) Date: Mon, 5 Sep 2011 09:26:14 -0500 Subject: [Tutor] Getting values from different functions (def's) In-Reply-To: <j3ls5v$9um$1@dough.gmane.org> References: <CAFEP6Htz+p=3LgoE8j2iPjvEfHssV=rNA0a1T-p0ER3XWbrGMA@mail.gmail.com> <j3ls5v$9um$1@dough.gmane.org> Message-ID: <CAFEP6HtjVD6qwYdLJx82JQXg6oCLtrHg7D2gkkXkTeR+vjaZxA@mail.gmail.com> Hello Alan!! It is exactly what I need to complete my task :D Than you so much 2011/8/31 Alan Gauld <alan.gauld at btinternet.com> > On 31/08/11 18:17, Susana Iraiis Delgado Rodriguez wrote: > >> Hello list !! >> I'm developing a Python GUI application. I alreday developed a very >> simple window with buttons, each button will do a different task, but >> the most important button will need to get information gotten in >> previous python's functions. Let's say I have four functions but at the >> end I want to collet all the information gotten. >> > > Instead of (or as well as) printing the data you will need to store it in > variables. Then you can use those variables in the other function. > > > > from Tkinter import * >> import tkSimpleDialog >> import tkMessageBox >> import tkFileDialog >> > > # define storage variables > dir = "" > extn = "" > csv_name = "" > > def directorio(): >> > global dir # need to specify the global one > > > print 'Seleccione directorio donde empezar' >> dirname = > tkFileDialog.askdirectory(**parent=root, >> > initialdir="/", > title='Selecciona > la ruta a escanear') > >> if len(dirname ) > 0: >> print "You chose %s" % dirname >> > > dir = dirname # store the value > > def extension(): >> > global extn > > print "Escribe la extension que necesitas buscar" >> ext=tkSimpleDialog.askstring('**Extension a buscar:','') >> print 'Buscando archivos: ',ext >> > extn = ext > > def csv(): >> > global csv_name > > print "Nombre del csv a crear" >> inv=tkSimpleDialog.askstring('**Nombre de .csv:','') >> print 'Archivo de salida: ',inv >> > csv_name = inv > > > def boton4(): >> #In this button I want to make a bigger process, but I need the root >> selected and the two strings the user types. >> print csv.inv #Obviously this throws an error >> > > print dir,csv_name,extn > > But course in a GUI you would normally not use print but instead populate > the text field of a label or Text widget or some such > device. > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor> > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110905/3b9d409d/attachment.html> From susana.delgado_s at utzmg.edu.mx Mon Sep 5 18:08:24 2011 From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez) Date: Mon, 5 Sep 2011 11:08:24 -0500 Subject: [Tutor] 'function' object has no attribute 'writer' Message-ID: <CAFEP6HuXZJoKXhdnFjqfjZyQ4s_b_+czCKrpigjf6hfWVKdiDQ@mail.gmail.com> I want to write a csv file, but I need the final user to give me some values to open and update the file. My code is: from Tkinter import * #Llamo las librerias graficas de Tk import tkSimpleDialog #Libreria de almacenamiento de dialogos import tkMessageBox #Libreria de mensajes import tkFileDialog import sys, os, csv, time, socket, stat from osgeo import ogr,gdal,osr from osgeo.gdalconst import * from PIL import Image dir = "" extn = "" csv_name = "" def directorio(): global dir print 'Seleccione directorio donde empezar' dirname = tkFileDialog.askdirectory(parent=root,initialdir="/",title='Selecciona la ruta a escanear') if len(dirname ) > 0: print "You chose %s" % dirname dir = dirname def extension(): global extn print "Escribe la extension que necesitas buscar" ext=tkSimpleDialog.askstring('Extension a buscar:','') print 'Buscando archivos: ',ext extn = ext def csv(): global csv_name print "Nombre del csv a crear" inv=tkSimpleDialog.askstring('Nombre de .csv:','') print 'Archivo de salidad: ',inv csv_name = inv def boton4(): print 'Iniciando...' gdal.AllRegister() file_list = [] folders = None for root, folders, files in os.walk(dir): file_list.extend(os.path.join(root,fi) for fi in files if fi.endswith(extn)) f = open(csv_name, 'wb') log = open ('log_errores.txt','w') writer = csv.writer(f) ....... more code But when I run it,console shows: Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 b win32 Type "help", "copyright", "credits" or "license" for more informa >>> import win >>> Seleccione directorio donde empezar You chose C:/ Escribe la extension que necesitas buscar Buscando archivos: .shp Nombre del csv a crear Archivo de salidad: gui.csv Iniciando... Exception in Tkinter callback Traceback (most recent call last): File "C:\Python26\lib\lib-tk\Tkinter.py", line 1410, in __call_ return self.func(*args) File "win.py", line 43, in boton4 writer = csv.writer(open(csv_name, 'w')) AttributeError: 'function' object has no attribute 'writer' I read a tutorial and csv has a writer function, I'm lost -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110905/951083f8/attachment.html> From eire1130 at gmail.com Mon Sep 5 18:21:21 2011 From: eire1130 at gmail.com (James Reynolds) Date: Mon, 5 Sep 2011 12:21:21 -0400 Subject: [Tutor] 'function' object has no attribute 'writer' In-Reply-To: <CAFEP6HuXZJoKXhdnFjqfjZyQ4s_b_+czCKrpigjf6hfWVKdiDQ@mail.gmail.com> References: <CAFEP6HuXZJoKXhdnFjqfjZyQ4s_b_+czCKrpigjf6hfWVKdiDQ@mail.gmail.com> Message-ID: <CAE0jAbq+gCLo41a==9fdzszqB8Fn3t7inM0hOr_csTnopmw_WQ@mail.gmail.com> On Mon, Sep 5, 2011 at 12:08 PM, Susana Iraiis Delgado Rodriguez < susana.delgado_s at utzmg.edu.mx> wrote: > I want to write a csv file, but I need the final user to give me some > values to open and update the file. My code is: > from Tkinter import * #Llamo las librerias graficas de Tk > import tkSimpleDialog #Libreria de almacenamiento de dialogos > import tkMessageBox #Libreria de mensajes > import tkFileDialog > import sys, os, csv, time, socket, stat > from osgeo import ogr,gdal,osr > from osgeo.gdalconst import * > from PIL import Image > dir = "" > extn = "" > csv_name = "" > def directorio(): > global dir > print 'Seleccione directorio donde empezar' > dirname = > tkFileDialog.askdirectory(parent=root,initialdir="/",title='Selecciona la > ruta a escanear') > if len(dirname ) > 0: > print "You chose %s" % dirname > dir = dirname > def extension(): > global extn > print "Escribe la extension que necesitas buscar" > ext=tkSimpleDialog.askstring('Extension a buscar:','') > print 'Buscando archivos: ',ext > extn = ext > def csv(): > global csv_name > print "Nombre del csv a crear" > inv=tkSimpleDialog.askstring('Nombre de .csv:','') > print 'Archivo de salidad: ',inv > csv_name = inv > def boton4(): > print 'Iniciando...' > gdal.AllRegister() > file_list = [] > folders = None > for root, folders, files in os.walk(dir): > file_list.extend(os.path.join(root,fi) for fi in files if > fi.endswith(extn)) > f = open(csv_name, 'wb') > log = open ('log_errores.txt','w') > writer = csv.writer(f) > ....... more code > But when I run it,console shows: > Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 b > win32 > Type "help", "copyright", "credits" or "license" for more informa > >>> import win > >>> Seleccione directorio donde empezar > You chose C:/ > Escribe la extension que necesitas buscar > Buscando archivos: .shp > Nombre del csv a crear > Archivo de salidad: gui.csv > Iniciando... > Exception in Tkinter callback > Traceback (most recent call last): > File "C:\Python26\lib\lib-tk\Tkinter.py", line 1410, in __call_ > return self.func(*args) > File "win.py", line 43, in boton4 > writer = csv.writer(open(csv_name, 'w')) > AttributeError: 'function' object has no attribute 'writer' > I read a tutorial and csv has a writer function, I'm lost > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > You have a function called "csv()" in your code. So when you go csv.blahbittyblob, you've overriden your imported module called "csv" with the function called "csv", python then tries to look up the attribute blahbittyblob and can't find it. it then throws an error. Change your csv function to be csvx() or _csv or something other than csv -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110905/e739e004/attachment-0001.html> From wprins at gmail.com Mon Sep 5 18:21:33 2011 From: wprins at gmail.com (Walter Prins) Date: Mon, 5 Sep 2011 17:21:33 +0100 Subject: [Tutor] 'function' object has no attribute 'writer' In-Reply-To: <CAFEP6HuXZJoKXhdnFjqfjZyQ4s_b_+czCKrpigjf6hfWVKdiDQ@mail.gmail.com> References: <CAFEP6HuXZJoKXhdnFjqfjZyQ4s_b_+czCKrpigjf6hfWVKdiDQ@mail.gmail.com> Message-ID: <CANLXbfDEofhvg6Lc3Wh6vTHn9WHTrzGNAVPW65rZOkspTCK+tQ@mail.gmail.com> Hi Susana, On 5 September 2011 17:08, Susana Iraiis Delgado Rodriguez < susana.delgado_s at utzmg.edu.mx> wrote: > File "win.py", line 43, in boton4 > writer = csv.writer(open(csv_name, 'w')) > AttributeError: 'function' object has no attribute 'writer' > I read a tutorial and csv has a writer function, I'm lost > > Yes, the csv module has a writer function. But read carefully! The error message isn't saying that the csv module doesn't have a writer function -- it says **function object** has no attribute 'writer'. So... somehow Python thinks that the name 'csv' refers to a function at the point in the code where the error is thrown. So how can this be? You should be asking yourself this question -- could it be that you've (for example) defined a *function* called 'csv', thereby effectively effectively hiding the *module* csv? ;) Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110905/a49ec34a/attachment.html> From susana.delgado_s at utzmg.edu.mx Mon Sep 5 18:53:12 2011 From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez) Date: Mon, 5 Sep 2011 11:53:12 -0500 Subject: [Tutor] 'function' object has no attribute 'writer' In-Reply-To: <CAE0jAbq+gCLo41a==9fdzszqB8Fn3t7inM0hOr_csTnopmw_WQ@mail.gmail.com> References: <CAFEP6HuXZJoKXhdnFjqfjZyQ4s_b_+czCKrpigjf6hfWVKdiDQ@mail.gmail.com> <CAE0jAbq+gCLo41a==9fdzszqB8Fn3t7inM0hOr_csTnopmw_WQ@mail.gmail.com> Message-ID: <CAFEP6Hv=Y5nJxcow8e2kGeON+_g_X2g89sTDR=fCO2=23up5Wg@mail.gmail.com> Hello guys!!! Shame on me, you're rigth I missunderstood the function and the module. I change the name of my function and that part of my code worked. But now I get a differente error, this script is going to collect information from shapefiles, I asked the user where to start the search, the file extension, and the csv name. Now I get: >>> import win >>> Seleccione directorio donde empezar You chose C:/ Escribe la extension que necesitas buscar Buscando archivos: .shp Nombre del csv a crear Archivo de salidad: gui.csv Iniciando... Exception in Tkinter callback Traceback (most recent call last): File "C:\Python26\lib\lib-tk\Tkinter.py", line 1410, in __call__ return self.func(*args) File "win.py", line 65, in boton4 shapeData = ogr.Open(filepath) File "C:\Python26\lib\site-packages\osgeo\ogr.py", line 4033, in Open return _ogr.Open(*args, **kwargs) TypeError: in method 'Open', argument 1 of type 'char const *' The other part of the code is: from Tkinter import * #Llamo las librerias graficas de Tk import tkSimpleDialog #Libreria de almacenamiento de dialogos import tkMessageBox #Libreria de mensajes import tkFileDialog import sys, os, csv, time, socket, stat from osgeo import ogr,gdal,osr from osgeo.gdalconst import * from PIL import Image dir = "" extn = "" csv_name = "" def directorio(): global dir print 'Seleccione directorio donde empezar' dirname = tkFileDialog.askdirectory(parent=root,initialdir="/",title='Selecciona la ruta a escanear') if len(dirname ) > 0: print "You chose %s" % dirname dir = dirname def extension(): global extn print "Escribe la extension que necesitas buscar" ext=tkSimpleDialog.askstring('Extension a buscar:','') print 'Buscando archivos: ',ext extn = ext def csv_w(): global csv_name print "Nombre del csv a crear" inv=tkSimpleDialog.askstring('Nombre de .csv:','') print 'Archivo de salidad: ',inv csv_name = inv def boton4(): print 'Iniciando...' gdal.AllRegister() file_list = [] folders = None for root, folders, files in os.walk(dir): file_list.extend(os.path.join(root,fi) for fi in files if fi.endswith(extn)) f = open(csv_name, 'wb') log = open ('log_errores.txt','w') writer = csv.writer(f) ruta = 'Ruta' archivo = 'archivo' x_min = 'x_min' x_max = 'x_max' y_min = 'y_min' y_max = 'y_max' geometria = 'geometria' num_elem = 'num_elem' prj = '.prj' proyeccion = 'proyeccion' fecha = 'fecha_modificacion' creacion = 'fecha_creacion' ultimo = 'ultimo_acceso' tamanio = 'tamanio_aprox' maq = 'maquina_host' usu = 'usuario' campos = [ruta,archivo,x_min,x_max,y_min,y_max,geometria,num_elem,prj,proyeccion,creacion,fecha,ultimo,tamanio,maq,usu] writer.writerow(campos) for row, filepath in enumerate(file_list, start=1): directorio = os.path.dirname(filepath) filename = os.path.basename(filepath) shapeData = ogr.Open(filepath) shp = 'Error al abrir el archivo' +filepath if shapeData is None: print shp log.write(shp+"\n") 2011/9/5 James Reynolds <eire1130 at gmail.com> > > > On Mon, Sep 5, 2011 at 12:08 PM, Susana Iraiis Delgado Rodriguez < > susana.delgado_s at utzmg.edu.mx> wrote: > >> I want to write a csv file, but I need the final user to give me some >> values to open and update the file. My code is: >> from Tkinter import * #Llamo las librerias graficas de Tk >> import tkSimpleDialog #Libreria de almacenamiento de dialogos >> import tkMessageBox #Libreria de mensajes >> import tkFileDialog >> import sys, os, csv, time, socket, stat >> from osgeo import ogr,gdal,osr >> from osgeo.gdalconst import * >> from PIL import Image >> dir = "" >> extn = "" >> csv_name = "" >> def directorio(): >> global dir >> print 'Seleccione directorio donde empezar' >> dirname = >> tkFileDialog.askdirectory(parent=root,initialdir="/",title='Selecciona la >> ruta a escanear') >> if len(dirname ) > 0: >> print "You chose %s" % dirname >> dir = dirname >> def extension(): >> global extn >> print "Escribe la extension que necesitas buscar" >> ext=tkSimpleDialog.askstring('Extension a buscar:','') >> print 'Buscando archivos: ',ext >> extn = ext >> def csv(): >> global csv_name >> print "Nombre del csv a crear" >> inv=tkSimpleDialog.askstring('Nombre de .csv:','') >> print 'Archivo de salidad: ',inv >> csv_name = inv >> def boton4(): >> print 'Iniciando...' >> gdal.AllRegister() >> file_list = [] >> folders = None >> for root, folders, files in os.walk(dir): >> file_list.extend(os.path.join(root,fi) for fi in files if >> fi.endswith(extn)) >> f = open(csv_name, 'wb') >> log = open ('log_errores.txt','w') >> writer = csv.writer(f) >> ....... more code >> But when I run it,console shows: >> Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 b >> win32 >> Type "help", "copyright", "credits" or "license" for more informa >> >>> import win >> >>> Seleccione directorio donde empezar >> You chose C:/ >> Escribe la extension que necesitas buscar >> Buscando archivos: .shp >> Nombre del csv a crear >> Archivo de salidad: gui.csv >> Iniciando... >> Exception in Tkinter callback >> Traceback (most recent call last): >> File "C:\Python26\lib\lib-tk\Tkinter.py", line 1410, in __call_ >> return self.func(*args) >> File "win.py", line 43, in boton4 >> writer = csv.writer(open(csv_name, 'w')) >> AttributeError: 'function' object has no attribute 'writer' >> I read a tutorial and csv has a writer function, I'm lost >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > > > You have a function called "csv()" in your code. > > So when you go csv.blahbittyblob, you've overriden your imported module > called "csv" with the function called "csv", python then tries to look up > the attribute blahbittyblob and can't find it. it then throws an error. > > Change your csv function to be csvx() or _csv or something other than csv > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110905/f2e01cd7/attachment.html> From __peter__ at web.de Mon Sep 5 21:09:56 2011 From: __peter__ at web.de (Peter Otten) Date: Mon, 05 Sep 2011 21:09:56 +0200 Subject: [Tutor] 'function' object has no attribute 'writer' References: <CAFEP6HuXZJoKXhdnFjqfjZyQ4s_b_+czCKrpigjf6hfWVKdiDQ@mail.gmail.com> <CAE0jAbq+gCLo41a==9fdzszqB8Fn3t7inM0hOr_csTnopmw_WQ@mail.gmail.com> <CAFEP6Hv=Y5nJxcow8e2kGeON+_g_X2g89sTDR=fCO2=23up5Wg@mail.gmail.com> Message-ID: <j436pu$mnc$1@dough.gmane.org> Susana Iraiis Delgado Rodriguez wrote: Susana, please use 4-space indents for your code samples. I've said it before, but I think it's worthwhile repeating because it makes it much easier to grasp the structure of a script at first sight. > But now I get a differente error, this script is going to collect > information from shapefiles, I asked the user where to start the search, > the file extension, and the csv name. Now I get: >>>> import win >>>> Seleccione directorio donde empezar > You chose C:/ > Escribe la extension que necesitas buscar > Buscando archivos: .shp > Nombre del csv a crear > Archivo de salidad: gui.csv > Iniciando... > Exception in Tkinter callback > Traceback (most recent call last): > File "C:\Python26\lib\lib-tk\Tkinter.py", line 1410, in __call__ > return self.func(*args) > File "win.py", line 65, in boton4 > shapeData = ogr.Open(filepath) > File "C:\Python26\lib\site-packages\osgeo\ogr.py", line 4033, in Open > return _ogr.Open(*args, **kwargs) > TypeError: in method 'Open', argument 1 of type 'char const *' > > The other part of the code is: > from osgeo import ogr,gdal,osr > shapeData = ogr.Open(filepath) filepath is a unicode string, your library seems to expect byte strings. Try converting it like so: import sys filesystemencoding = sys.getfilesystemencoding() #... shapeData = ogr.Open(filepath.encode(filesystemencoding)) From clsdaniel at gmail.com Tue Sep 6 00:32:35 2011 From: clsdaniel at gmail.com (Carlos Daniel Ruvalcaba Valenzuela) Date: Mon, 5 Sep 2011 15:32:35 -0700 Subject: [Tutor] Application packaging Message-ID: <CAEF3qbk83G7Lm84625EYz3WGnNXPDRQi81p4UDHmLsRww0_KOA@mail.gmail.com> Hello list, Lately I have been working on a windows desktop application for a client, using python and pyside, everything working fine, but I'm getting a bit stuck when trying to distribute the application to the client. Currently I'm using a combination of py2exe and clickonce, what are your experiences on distributing this kind of applications on a windows environment? Personally I have tried py2exe, pyinstaller, cx_freeze, only py2exe got me a working bundle but a ugly one full of unordered files, I wrapped all this on a ClickOnce installer so the user just sees an icon in their desktop. The problem with this approach is that it results in a huge bundle, updates are a pain too. Any ideas or experience with this (not precisely this combo but the packaging in general)? Regards, Carlos Ruvalcaba PD: I'm looking for the actual state of things right now as I'm sure this questing has been asked in the past. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110905/1367f1d6/attachment-0001.html> From susana.delgado_s at utzmg.edu.mx Tue Sep 6 17:47:49 2011 From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez) Date: Tue, 6 Sep 2011 10:47:49 -0500 Subject: [Tutor] 'function' object has no attribute 'writer' In-Reply-To: <j436pu$mnc$1@dough.gmane.org> References: <CAFEP6HuXZJoKXhdnFjqfjZyQ4s_b_+czCKrpigjf6hfWVKdiDQ@mail.gmail.com> <CAE0jAbq+gCLo41a==9fdzszqB8Fn3t7inM0hOr_csTnopmw_WQ@mail.gmail.com> <CAFEP6Hv=Y5nJxcow8e2kGeON+_g_X2g89sTDR=fCO2=23up5Wg@mail.gmail.com> <j436pu$mnc$1@dough.gmane.org> Message-ID: <CAFEP6HvLiZLs_1EOv1Zx4gyJpK7=BTdhpf1dt+q-CtC8RMhZXQ@mail.gmail.com> Hello Petter!! Thank you for answer to my question. I apologize for the writing of my code, won't happen again. I added the lines you suggested me, and the script work fine. Than you!! Here's the code corrected and indented. from Tkinter import * #Llamo las librerias graficas de Tk import tkSimpleDialog #Libreria de almacenamiento de dialogos import tkMessageBox #Libreria de mensajes import tkFileDialog import sys, os, csv, time, socket, stat from osgeo import ogr,gdal,osr from osgeo.gdalconst import * from PIL import Image dir = "" extn = "" csv_name = "" filesystemencoding = sys.getfilesystemencoding() def directorio(): global dir print 'Seleccione directorio donde empezar' dirname = tkFileDialog.askdirectory(parent=root,initialdir="/",title='Selecciona la ruta a escanear') if len(dirname ) > 0: print "You chose %s" % dirname dir = dirname def extension(): global extn print "Escribe la extension que necesitas buscar" ext=tkSimpleDialog.askstring('Extension a buscar:','') print 'Buscando archivos: ',ext extn = ext def csv_w(): global csv_name print "Nombre del csv a crear" inv=tkSimpleDialog.askstring('Nombre de .csv:','') print 'Archivo de salidad: ',inv csv_name = inv def boton4(): print 'Iniciando...' gdal.AllRegister() file_list = [] folders = None for root, folders, files in os.walk(dir): file_list.extend(os.path.join(root,fi) for fi in files if fi.endswith(extn)) f = open(csv_name, 'wb') log = open ('log_errores.txt','w') writer = csv.writer(f) ruta = 'Ruta' archivo = 'archivo' x_min = 'x_min' x_max = 'x_max' y_min = 'y_min' y_max = 'y_max' geometria = 'geometria' num_elem = 'num_elem' prj = '.prj' proyeccion = 'proyeccion' fecha = 'fecha_modificacion' creacion = 'fecha_creacion' ultimo = 'ultimo_acceso' tamanio = 'tamanio_aprox' maq = 'maquina_host' usu = 'usuario' campos = [ruta,archivo,x_min,x_max,y_min,y_max,geometria,num_elem,prj,proyeccion,creacion,fecha,ultimo,tamanio,maq,usu] writer.writerow(campos) for row, filepath in enumerate(file_list, start=1): directorio = os.path.dirname(filepath) filename = os.path.basename(filepath) shapeData = ogr.Open(filepath.encode(filesystemencoding)) shp = 'Error al abrir el archivo' +filepath ...... 2011/9/5 Peter Otten <__peter__ at web.de> > Susana Iraiis Delgado Rodriguez wrote: > > Susana, please use 4-space indents for your code samples. I've said it > before, but I think it's worthwhile repeating because it makes it much > easier to grasp the structure of a script at first sight. > > > But now I get a differente error, this script is going to collect > > information from shapefiles, I asked the user where to start the search, > > the file extension, and the csv name. Now I get: > >>>> import win > >>>> Seleccione directorio donde empezar > > You chose C:/ > > Escribe la extension que necesitas buscar > > Buscando archivos: .shp > > Nombre del csv a crear > > Archivo de salidad: gui.csv > > Iniciando... > > Exception in Tkinter callback > > Traceback (most recent call last): > > File "C:\Python26\lib\lib-tk\Tkinter.py", line 1410, in __call__ > > return self.func(*args) > > File "win.py", line 65, in boton4 > > shapeData = ogr.Open(filepath) > > File "C:\Python26\lib\site-packages\osgeo\ogr.py", line 4033, in Open > > return _ogr.Open(*args, **kwargs) > > TypeError: in method 'Open', argument 1 of type 'char const *' > > > > The other part of the code is: > > > from osgeo import ogr,gdal,osr > > > shapeData = ogr.Open(filepath) > > filepath is a unicode string, your library seems to expect byte strings. > Try converting it like so: > > import sys > filesystemencoding = sys.getfilesystemencoding() > #... > shapeData = ogr.Open(filepath.encode(filesystemencoding)) > > _______________________________________________ > 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: <http://mail.python.org/pipermail/tutor/attachments/20110906/ad6a16b8/attachment.html> From lina.lastname at gmail.com Wed Sep 7 06:46:37 2011 From: lina.lastname at gmail.com (lina) Date: Wed, 7 Sep 2011 12:46:37 +0800 Subject: [Tutor] how to sort the file out Message-ID: <CAG9cJmkEd_D7xkHnLSBcBjarzT0vuVUTUWp3ViP0yYoGuTS29g@mail.gmail.com> HI, I have two files, one is reference file, another is waiting for adjust one, File 1: 1 C1 2 O1 3 C2 4 C3 5 H3 6 C7 7 O2 8 H22 9 C6 10 H61 11 C5 12 H5 13 C4 14 C8 15 C9 16 C10 17 O3 18 C11 19 C12 20 O4 21 C13 22 C14 23 C15 24 C20 25 H20 26 C16 27 H16 28 C17 29 H17 30 C18 31 O6 32 H62 33 C19 34 O5 35 C21 File 2: 3 H16 4 H5 6 H61 7 H17 9 H20 12 H3 13 C1 14 O1 15 C2 16 C3 17 C4 18 C5 19 C6 20 C7 21 C8 22 C9 23 C10 24 O3 25 C11 26 C12 27 O4 28 C13 29 C14 30 C15 31 C20 32 C19 33 C18 34 C17 35 C16 36 O5 37 C21 38 O6 39 H62 40 O2 41 H22 I wish the field 2 from file 2 arranged the same sequence as the field 2 of file 1. Thanks for any suggestions, I drove my minds into nuts already, three hours passed and I still failed to achieve this. -- Best Regards, lina From wolfrage8765 at gmail.com Wed Sep 7 07:14:55 2011 From: wolfrage8765 at gmail.com (Jordan) Date: Tue, 06 Sep 2011 22:14:55 -0700 Subject: [Tutor] how to sort the file out In-Reply-To: <CAG9cJmkEd_D7xkHnLSBcBjarzT0vuVUTUWp3ViP0yYoGuTS29g@mail.gmail.com> References: <CAG9cJmkEd_D7xkHnLSBcBjarzT0vuVUTUWp3ViP0yYoGuTS29g@mail.gmail.com> Message-ID: <4E66FDCF.7090509@gmail.com> Perhaps a little more information on what is going on and what the expected outcome is. In order for the tutors to be able to better help you as I am not sure what you expect to get from these two lists. IE there is no field 2 in file 2, so what should it be? Also what should happen to the rest of the file if I make field 2 of file 2 equal "01"? -- Jordan On 09/06/2011 09:46 PM, lina wrote: > HI, I have two files, one is reference file, another is waiting for adjust one, > > File 1: > > 1 C1 > 2 O1 > 3 C2 > 4 C3 > 5 H3 > 6 C7 > 7 O2 > 8 H22 > 9 C6 > 10 H61 > 11 C5 > 12 H5 > 13 C4 > 14 C8 > 15 C9 > 16 C10 > 17 O3 > 18 C11 > 19 C12 > 20 O4 > 21 C13 > 22 C14 > 23 C15 > 24 C20 > 25 H20 > 26 C16 > 27 H16 > 28 C17 > 29 H17 > 30 C18 > 31 O6 > 32 H62 > 33 C19 > 34 O5 > 35 C21 > > File 2: > 3 H16 > 4 H5 > 6 H61 > 7 H17 > 9 H20 > 12 H3 > 13 C1 > 14 O1 > 15 C2 > 16 C3 > 17 C4 > 18 C5 > 19 C6 > 20 C7 > 21 C8 > 22 C9 > 23 C10 > 24 O3 > 25 C11 > 26 C12 > 27 O4 > 28 C13 > 29 C14 > 30 C15 > 31 C20 > 32 C19 > 33 C18 > 34 C17 > 35 C16 > 36 O5 > 37 C21 > 38 O6 > 39 H62 > 40 O2 > 41 H22 > > I wish the field 2 from file 2 arranged the same sequence as the field > 2 of file 1. > > Thanks for any suggestions, > > I drove my minds into nuts already, three hours passed and I still > failed to achieve this. > From hugo.yoshi at gmail.com Wed Sep 7 07:28:18 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Wed, 7 Sep 2011 07:28:18 +0200 Subject: [Tutor] how to sort the file out In-Reply-To: <4E66FDCF.7090509@gmail.com> References: <CAG9cJmkEd_D7xkHnLSBcBjarzT0vuVUTUWp3ViP0yYoGuTS29g@mail.gmail.com> <4E66FDCF.7090509@gmail.com> Message-ID: <CAJmBOfnsjGpS_C42XSrnQenkgU9ezV0krBX6jU76F1gM2fhYNA@mail.gmail.com> I was assuming that the numbers were field 1, and the letter/number combinations were field 2. If I understand him correctly, he wants the lines in file 2 to be arranged such that the order of field two is the same as it is in file 1. In that case, you can do it with one sexy sort() call (and a little preprocessing to load the files), but I don't want to get all into explain and then realize he wants something totally different. So please show us with some smaller files (5 lines is fine) what exactly you want the result to be. Hugo On Wed, Sep 7, 2011 at 7:14 AM, Jordan <wolfrage8765 at gmail.com> wrote: > Perhaps a little more information on what is going on and what the > expected outcome is. In order for the tutors to be able to better help > you as I am not sure what you expect to get from these two lists. IE > there is no field 2 in file 2, so what should it be? Also what should > happen to the rest of the file if I make field 2 of file 2 equal "01"? > -- > Jordan > > On 09/06/2011 09:46 PM, lina wrote: >> HI, I have two files, one is reference file, another is waiting for adjust one, >> >> File 1: >> >> 1 C1 >> 2 O1 >> 3 C2 >> 4 C3 >> 5 H3 >> 6 C7 >> 7 O2 >> 8 H22 >> 9 C6 >> 10 H61 >> 11 C5 >> 12 H5 >> 13 C4 >> 14 C8 >> 15 C9 >> 16 C10 >> 17 O3 >> 18 C11 >> 19 C12 >> 20 O4 >> 21 C13 >> 22 C14 >> 23 C15 >> 24 C20 >> 25 H20 >> 26 C16 >> 27 H16 >> 28 C17 >> 29 H17 >> 30 C18 >> 31 O6 >> 32 H62 >> 33 C19 >> 34 O5 >> 35 C21 >> >> File 2: >> 3 H16 >> 4 H5 >> 6 H61 >> 7 H17 >> 9 H20 >> 12 H3 >> 13 C1 >> 14 O1 >> 15 C2 >> 16 C3 >> 17 C4 >> 18 C5 >> 19 C6 >> 20 C7 >> 21 C8 >> 22 C9 >> 23 C10 >> 24 O3 >> 25 C11 >> 26 C12 >> 27 O4 >> 28 C13 >> 29 C14 >> 30 C15 >> 31 C20 >> 32 C19 >> 33 C18 >> 34 C17 >> 35 C16 >> 36 O5 >> 37 C21 >> 38 O6 >> 39 H62 >> 40 O2 >> 41 H22 >> >> I wish the field 2 from file 2 arranged the same sequence as the field >> 2 of file 1. >> >> Thanks for any suggestions, >> >> I drove my minds into nuts already, three ?hours passed and I still >> failed to achieve this. >> > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From bodsda at googlemail.com Wed Sep 7 07:52:16 2011 From: bodsda at googlemail.com (bodsda at googlemail.com) Date: Wed, 7 Sep 2011 05:52:16 +0000 Subject: [Tutor] how to sort the file out In-Reply-To: <CAG9cJmkEd_D7xkHnLSBcBjarzT0vuVUTUWp3ViP0yYoGuTS29g@mail.gmail.com> References: <CAG9cJmkEd_D7xkHnLSBcBjarzT0vuVUTUWp3ViP0yYoGuTS29g@mail.gmail.com> Message-ID: <212055530-1315374736-cardhu_decombobulator_blackberry.rim.net-1032708278-@b28.c12.bise7.blackberry> I'm also slightly confused. Why does file one start at 1, but file 2 starts at 3. Why not just duplicate file2? Bodsda Sent from my BlackBerry? wireless device -----Original Message----- From: lina <lina.lastname at gmail.com> Sender: tutor-bounces+bodsda=googlemail.com at python.org Date: Wed, 7 Sep 2011 12:46:37 To: tutor<Tutor at python.org> Subject: [Tutor] how to sort the file out HI, I have two files, one is reference file, another is waiting for adjust one, File 1: 1 C1 2 O1 3 C2 4 C3 5 H3 6 C7 7 O2 8 H22 9 C6 10 H61 11 C5 12 H5 13 C4 14 C8 15 C9 16 C10 17 O3 18 C11 19 C12 20 O4 21 C13 22 C14 23 C15 24 C20 25 H20 26 C16 27 H16 28 C17 29 H17 30 C18 31 O6 32 H62 33 C19 34 O5 35 C21 File 2: 3 H16 4 H5 6 H61 7 H17 9 H20 12 H3 13 C1 14 O1 15 C2 16 C3 17 C4 18 C5 19 C6 20 C7 21 C8 22 C9 23 C10 24 O3 25 C11 26 C12 27 O4 28 C13 29 C14 30 C15 31 C20 32 C19 33 C18 34 C17 35 C16 36 O5 37 C21 38 O6 39 H62 40 O2 41 H22 I wish the field 2 from file 2 arranged the same sequence as the field 2 of file 1. Thanks for any suggestions, I drove my minds into nuts already, three hours passed and I still failed to achieve this. -- Best Regards, lina _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From lina.lastname at gmail.com Wed Sep 7 08:13:05 2011 From: lina.lastname at gmail.com (lina) Date: Wed, 7 Sep 2011 14:13:05 +0800 Subject: [Tutor] how to sort the file out In-Reply-To: <212055530-1315374736-cardhu_decombobulator_blackberry.rim.net-1032708278-@b28.c12.bise7.blackberry> References: <CAG9cJmkEd_D7xkHnLSBcBjarzT0vuVUTUWp3ViP0yYoGuTS29g@mail.gmail.com> <212055530-1315374736-cardhu_decombobulator_blackberry.rim.net-1032708278-@b28.c12.bise7.blackberry> Message-ID: <CAG9cJmnh=o6FZvxAT+Z6qaXbGHdodHQfsQ1mfqhgJA0rMoUgAA@mail.gmail.com> For file 1, 1 C1 2 O1 3 C2 4 C3 5 H3 This one is much more like dictionary, ; nr atom cgnr charge mass 1 C1 1 0.062 15.0350 2 O1 1 -0.139 15.9994 3 C2 1 0.064 12.0110 4 C3 1 -0.001 12.0110 5 H3 1 0.014 1.0080 which was from field one and filed 2, namely the atom column, while for file 2: 12 H3 13 C1 14 O1 15 C2 16 C3 I want to be arranged like: 13 C1 14 O1 15 C2 16 C3 12 H3 only sort field 2 based on the dictionary, to match the sequence of C1, O1, C2, C3, H3. Thanks again, I want to arranged the field 3 according to match the dictionary (file 1) sequence. On Wed, Sep 7, 2011 at 1:52 PM, <bodsda at googlemail.com> wrote: > I'm also slightly confused. Why does file one start at 1, but file 2 starts at 3. Why not just duplicate file2? > > Bodsda > Sent from my BlackBerry? wireless device > > -----Original Message----- > From: lina <lina.lastname at gmail.com> > Sender: tutor-bounces+bodsda=googlemail.com at python.org > Date: Wed, 7 Sep 2011 12:46:37 > To: tutor<Tutor at python.org> > Subject: [Tutor] how to sort the file out > > HI, I have two files, one is reference file, another is waiting for adjust one, > > File 1: > > 1 C1 > 2 O1 > 3 C2 > 4 C3 > 5 H3 > 6 C7 > 7 O2 > 8 H22 > 9 C6 > 10 H61 > 11 C5 > 12 H5 > 13 C4 > 14 C8 > 15 C9 > 16 C10 > 17 O3 > 18 C11 > 19 C12 > 20 O4 > 21 C13 > 22 C14 > 23 C15 > 24 C20 > 25 H20 > 26 C16 > 27 H16 > 28 C17 > 29 H17 > 30 C18 > 31 O6 > 32 H62 > 33 C19 > 34 O5 > 35 C21 > > File 2: > 3 H16 > 4 H5 > 6 H61 > 7 H17 > 9 H20 > 12 H3 > 13 C1 > 14 O1 > 15 C2 > 16 C3 > 17 C4 > 18 C5 > 19 C6 > 20 C7 > 21 C8 > 22 C9 > 23 C10 > 24 O3 > 25 C11 > 26 C12 > 27 O4 > 28 C13 > 29 C14 > 30 C15 > 31 C20 > 32 C19 > 33 C18 > 34 C17 > 35 C16 > 36 O5 > 37 C21 > 38 O6 > 39 H62 > 40 O2 > 41 H22 > > I wish the field 2 from file 2 arranged the same sequence as the field > 2 of file 1. > > Thanks for any suggestions, > > I drove my minds into nuts already, three ?hours passed and I still > failed to achieve this. > > -- > Best Regards, > > lina > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Best Regards, lina From hugo.yoshi at gmail.com Wed Sep 7 08:25:07 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Wed, 7 Sep 2011 08:25:07 +0200 Subject: [Tutor] Fwd: how to sort the file out In-Reply-To: <CAJmBOfmLNx_0vBz5qvnNc9c-HXZXWpOHwVYR6BGij+hZu1KKeg@mail.gmail.com> References: <CAG9cJmkEd_D7xkHnLSBcBjarzT0vuVUTUWp3ViP0yYoGuTS29g@mail.gmail.com> <4E66FDCF.7090509@gmail.com> <CAJmBOfnsjGpS_C42XSrnQenkgU9ezV0krBX6jU76F1gM2fhYNA@mail.gmail.com> <CAG9cJmkgReeyiW8Cnrp=stQysxK8VGc=D93KuvxtQEbWQpG83Q@mail.gmail.com> <CAJmBOfmLNx_0vBz5qvnNc9c-HXZXWpOHwVYR6BGij+hZu1KKeg@mail.gmail.com> Message-ID: <CAJmBOfmTxdLx4AeaPNyW3nei6Qthrmp0WJ018565-Uag7tMDAw@mail.gmail.com> forgot to forward this to list, sorry. ---------- Forwarded message ---------- From: Hugo Arts <hugo.yoshi at gmail.com> Date: Wed, Sep 7, 2011 at 8:24 AM Subject: Re: [Tutor] how to sort the file out To: lina <lina.lastname at gmail.com> On Wed, Sep 7, 2011 at 8:16 AM, lina <lina.lastname at gmail.com> wrote: > On Wed, Sep 7, 2011 at 1:28 PM, Hugo Arts <hugo.yoshi at gmail.com> wrote: >> I was assuming that the numbers were field 1, and the letter/number >> combinations were field 2. If I understand him correctly, he wants the > > Yes. > >> lines in file 2 to be arranged such that the order of field two is the >> same as it is in file 1. In that case, you can do it with one sexy >> sort() call (and a little preprocessing to load the files), but I >> don't want to get all into explain and then realize he wants something >> totally different. > You understand right. > Well, it is fairly simple. You grab field2 from file1, and put all the items into a list (should be easy right? open(), readlines(), split(), grab second item). Then, you grab file2 as a list of tuples (same procedure as the first file, but you just put the results of split() right into the list. Then you sort with a key like so: list2.sort(key=lambda x: list1.index(x[1])) You see? For each item in the second list, we grab field 2, and look up what index it has in list1. Then we use that index as the sort key. That way they'll be sorted like file1 is. After that it's just a matter of writing back to the file, easy peasy. HTH, Hugo From lina.lastname at gmail.com Wed Sep 7 08:57:44 2011 From: lina.lastname at gmail.com (lina) Date: Wed, 7 Sep 2011 14:57:44 +0800 Subject: [Tutor] Fwd: how to sort the file out In-Reply-To: <CAJmBOfmTxdLx4AeaPNyW3nei6Qthrmp0WJ018565-Uag7tMDAw@mail.gmail.com> References: <CAG9cJmkEd_D7xkHnLSBcBjarzT0vuVUTUWp3ViP0yYoGuTS29g@mail.gmail.com> <4E66FDCF.7090509@gmail.com> <CAJmBOfnsjGpS_C42XSrnQenkgU9ezV0krBX6jU76F1gM2fhYNA@mail.gmail.com> <CAG9cJmkgReeyiW8Cnrp=stQysxK8VGc=D93KuvxtQEbWQpG83Q@mail.gmail.com> <CAJmBOfmLNx_0vBz5qvnNc9c-HXZXWpOHwVYR6BGij+hZu1KKeg@mail.gmail.com> <CAJmBOfmTxdLx4AeaPNyW3nei6Qthrmp0WJ018565-Uag7tMDAw@mail.gmail.com> Message-ID: <CAG9cJmnvby_7gU0tKs7GAnGFUiSZXTLA=wXGF-cC+BG6V8G0+w@mail.gmail.com> On Wed, Sep 7, 2011 at 2:25 PM, Hugo Arts <hugo.yoshi at gmail.com> wrote: > forgot to forward this to list, sorry. > > > ---------- Forwarded message ---------- > From: Hugo Arts <hugo.yoshi at gmail.com> > Date: Wed, Sep 7, 2011 at 8:24 AM > Subject: Re: [Tutor] how to sort the file out > To: lina <lina.lastname at gmail.com> > > > On Wed, Sep 7, 2011 at 8:16 AM, lina <lina.lastname at gmail.com> wrote: >> On Wed, Sep 7, 2011 at 1:28 PM, Hugo Arts <hugo.yoshi at gmail.com> wrote: >>> I was assuming that the numbers were field 1, and the letter/number >>> combinations were field 2. If I understand him correctly, he wants the >> >> Yes. >> >>> lines in file 2 to be arranged such that the order of field two is the >>> same as it is in file 1. In that case, you can do it with one sexy >>> sort() call (and a little preprocessing to load the files), but I >>> don't want to get all into explain and then realize he wants something >>> totally different. >> You understand right. >> > > Well, it is fairly simple. You grab field2 from file1, and put all the > items into a list (should be easy right? open(), readlines(), split(), > grab second item). Then, you grab file2 as a list of tuples (same > procedure as the first file, but you just put the results of split() > right into the list. Then you sort with a key like so: > > list2.sort(key=lambda x: list1.index(x[1])) > > You see? For each item in the second list, we grab field 2, and look > up what index it has in list1. Then we use that index as the sort key. > That way they'll be sorted like file1 is. not easy to me. Sign ... I may do it by hand, cut and pasta following the orders. > > After that it's just a matter of writing back to the file, easy peasy. > > HTH, > Hugo > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Best Regards, lina From lina.lastname at gmail.com Wed Sep 7 10:50:31 2011 From: lina.lastname at gmail.com (lina) Date: Wed, 7 Sep 2011 16:50:31 +0800 Subject: [Tutor] Fwd: how to sort the file out In-Reply-To: <CAG9cJmnvby_7gU0tKs7GAnGFUiSZXTLA=wXGF-cC+BG6V8G0+w@mail.gmail.com> References: <CAG9cJmkEd_D7xkHnLSBcBjarzT0vuVUTUWp3ViP0yYoGuTS29g@mail.gmail.com> <4E66FDCF.7090509@gmail.com> <CAJmBOfnsjGpS_C42XSrnQenkgU9ezV0krBX6jU76F1gM2fhYNA@mail.gmail.com> <CAG9cJmkgReeyiW8Cnrp=stQysxK8VGc=D93KuvxtQEbWQpG83Q@mail.gmail.com> <CAJmBOfmLNx_0vBz5qvnNc9c-HXZXWpOHwVYR6BGij+hZu1KKeg@mail.gmail.com> <CAJmBOfmTxdLx4AeaPNyW3nei6Qthrmp0WJ018565-Uag7tMDAw@mail.gmail.com> <CAG9cJmnvby_7gU0tKs7GAnGFUiSZXTLA=wXGF-cC+BG6V8G0+w@mail.gmail.com> Message-ID: <CAG9cJmmqdS0=conNu422BWTQAaacLgnR=1WhvQ8K3TW-6nCHkQ@mail.gmail.com> On Wed, Sep 7, 2011 at 2:57 PM, lina <lina.lastname at gmail.com> wrote: > On Wed, Sep 7, 2011 at 2:25 PM, Hugo Arts <hugo.yoshi at gmail.com> wrote: >> forgot to forward this to list, sorry. >> >> >> ---------- Forwarded message ---------- >> From: Hugo Arts <hugo.yoshi at gmail.com> >> Date: Wed, Sep 7, 2011 at 8:24 AM >> Subject: Re: [Tutor] how to sort the file out >> To: lina <lina.lastname at gmail.com> >> >> >> On Wed, Sep 7, 2011 at 8:16 AM, lina <lina.lastname at gmail.com> wrote: >>> On Wed, Sep 7, 2011 at 1:28 PM, Hugo Arts <hugo.yoshi at gmail.com> wrote: >>>> I was assuming that the numbers were field 1, and the letter/number >>>> combinations were field 2. If I understand him correctly, he wants the >>> >>> Yes. >>> >>>> lines in file 2 to be arranged such that the order of field two is the >>>> same as it is in file 1. In that case, you can do it with one sexy >>>> sort() call (and a little preprocessing to load the files), but I >>>> don't want to get all into explain and then realize he wants something >>>> totally different. >>> You understand right. >>> >> >> Well, it is fairly simple. You grab field2 from file1, and put all the >> items into a list (should be easy right? open(), readlines(), split(), >> grab second item). Then, you grab file2 as a list of tuples (same >> procedure as the first file, but you just put the results of split() >> right into the list. Then you sort with a key like so: >> >> list2.sort(key=lambda x: list1.index(x[1])) >> >> You see? For each item in the second list, we grab field 2, and look >> up what index it has in list1. Then we use that index as the sort key. >> That way they'll be sorted like file1 is. > > not easy to me. > > Sign ... I may do it by hand, cut and pasta following the orders. After overcoming the nearly-give-up frustration, I finally see the deadly-beautiful results. It's so BEAUTIFUL. amazing ... >> >> After that it's just a matter of writing back to the file, easy peasy. >> >> HTH, >> Hugo >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > > > -- > Best Regards, > > lina > -- Best Regards, lina From __peter__ at web.de Wed Sep 7 10:52:03 2011 From: __peter__ at web.de (Peter Otten) Date: Wed, 07 Sep 2011 10:52:03 +0200 Subject: [Tutor] how to sort the file out References: <CAG9cJmkEd_D7xkHnLSBcBjarzT0vuVUTUWp3ViP0yYoGuTS29g@mail.gmail.com> Message-ID: <j47bbk$3uo$1@dough.gmane.org> lina wrote: > HI, I have two files, one is reference file, another is waiting for adjust > one, > > File 1: > > 1 C1 > 2 O1 [...] > 33 C19 > 34 O5 > 35 C21 > > File 2: > 3 H16 > 4 H5 [...] > 39 H62 > 40 O2 > 41 H22 > > I wish the field 2 from file 2 arranged the same sequence as the field > 2 of file 1. > > Thanks for any suggestions, > > I drove my minds into nuts already, three hours passed and I still > failed to achieve this. You could have written the above after three minutes. To get the most out of this mailing list you should give some details of what you tried and how it failed. This gives us valuable information about your level of knowledge and confidence that you are trying to learn rather than get solutions on the cheap. However, I'm in the mood for some spoonfeeding: indexfile = "tmp_index.txt" datafile = "tmp_data.txt" sorteddatafile = "tmp_output.txt" def make_lookup(lines): r"""Build a dictionary that maps the second column to the line number. >>> make_lookup(["aaa bbb\n", "ccc ddd\n"]) == {'bbb': 0, 'ddd': 1} True """ position_lookup = {} for lineno, line in enumerate(lines): second_field = line.split()[1] position_lookup[second_field] = lineno return position_lookup with open(indexfile) as f: position_lookup = make_lookup(f) # With your sample data the global position_lookup dict looks like this now: # {'C1': 0, 'O1': 1, 'C2': 2,... , 'O5': 33, 'C21': 34} def get_position(line): r"""Extract the second field from the line and look up the associated line number in the global position_lookup dictionary. Example: get_position("15 C2\n") The line is split into ["15", "C2"] The second field is "C2" Its associated line number in position_lookup: 2 --> the function returns 2 """ second_field = line.split()[1] return position_lookup[second_field] with open(datafile) as f: # sort the lines in the data file using the line number in the index # file as the sort key lines = sorted(f, key=get_position) with open(sorteddatafile, "w") as f: f.writelines(lines) From lina.lastname at gmail.com Wed Sep 7 12:04:30 2011 From: lina.lastname at gmail.com (lina) Date: Wed, 7 Sep 2011 18:04:30 +0800 Subject: [Tutor] how to sort the file out In-Reply-To: <j47bbk$3uo$1@dough.gmane.org> References: <CAG9cJmkEd_D7xkHnLSBcBjarzT0vuVUTUWp3ViP0yYoGuTS29g@mail.gmail.com> <j47bbk$3uo$1@dough.gmane.org> Message-ID: <CAG9cJm=dJM7Sk4L8-zyntdLyF1PDtgu46iyzPX+mGqMSGAcGdg@mail.gmail.com> On Wed, Sep 7, 2011 at 4:52 PM, Peter Otten <__peter__ at web.de> wrote: > lina wrote: > >> HI, I have two files, one is reference file, another is waiting for adjust >> one, >> >> File 1: >> >> 1 C1 >> 2 O1 > [...] >> 33 C19 >> 34 O5 >> 35 C21 >> >> File 2: >> 3 H16 >> 4 H5 > [...] >> 39 H62 >> 40 O2 >> 41 H22 >> >> I wish the field 2 from file 2 arranged the same sequence as the field >> 2 of file 1. >> >> Thanks for any suggestions, >> >> I drove my minds into nuts already, three ?hours passed and I still >> failed to achieve this. > > You could have written the above after three minutes. To get the most out of > this mailing list you should give some details of what you tried and how it > failed. This gives us valuable information about your level of knowledge and > confidence that you are trying to learn rather than get solutions on the > cheap. > > However, I'm in the mood for some spoonfeeding: LOL ... thanks. I am very very low leavel in python, many times I just gave up due to frustration in using it. and escape back to bash, awk. > > indexfile = "tmp_index.txt" > datafile = "tmp_data.txt" > sorteddatafile = "tmp_output.txt" > > def make_lookup(lines): > ? ?r"""Build a dictionary that maps the second column to the line number. > > ? ?>>> make_lookup(["aaa bbb\n", "ccc ddd\n"]) == {'bbb': 0, 'ddd': 1} > ? ?True > ? ?""" > ? ?position_lookup = {} > ? ?for lineno, line in enumerate(lines): > ? ? ? ?second_field = line.split()[1] > ? ? ? ?position_lookup[second_field] = lineno > ? ?return position_lookup > > with open(indexfile) as f: > ? ?position_lookup = make_lookup(f) > > # With your sample data the global position_lookup dict looks like this now: > # {'C1': 0, 'O1': 1, 'C2': 2,... , 'O5': 33, 'C21': 34} > > def get_position(line): > ? ?r"""Extract the second field from the line and look up the > ? ?associated line number in the global position_lookup dictionary. > > ? ?Example: > ? ?get_position("15 C2\n") > ? ?The line is split into ["15", "C2"] > ? ?The second field is "C2" > ? ?Its associated line number in position_lookup: 2 > ? ?--> the function returns 2 > ? ?""" > ? ?second_field = line.split()[1] > ? ?return position_lookup[second_field] > > with open(datafile) as f: > ? ?# sort the lines in the data file using the line number in the index > ? ?# file as the sort key > ? ?lines = sorted(f, key=get_position) > > with open(sorteddatafile, "w") as f: > ? ?f.writelines(lines) > It's an amazing opportunity to learn. I will try it now. > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Best Regards, lina From illusiontechniques at gmail.com Thu Sep 8 05:26:34 2011 From: illusiontechniques at gmail.com (c smith) Date: Wed, 7 Sep 2011 23:26:34 -0400 Subject: [Tutor] how obsolete is 2.2? Message-ID: <CAL2Y8-SqwPGVpfQBHb0G1DKdavBOr5MR6q3K7upCQStLhK6eoQ@mail.gmail.com> I found a book at the local library that covers python but it's 2.2. I already have been using 2.7 for basic stuff and would like to know if it's worth my time to read this book. Are there any glaring differences that would be easy to point out, or is it too convoluted? Also, am I correct in thinking that 3.0 will always be called 3.0 but will change over time and will always include experimental features, while 2.x will gradually increase the 'x' and the highest 'x' will indicate the most current, stable release? oh, and a question on 'pickle': can pickle deserialize things that were not serialized by python? can it convert data into a python data type regardless of it was originally a 'c array' or something else that python doesn't support? -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110907/531f510e/attachment.html> From illusiontechniques at gmail.com Thu Sep 8 05:48:46 2011 From: illusiontechniques at gmail.com (c smith) Date: Wed, 7 Sep 2011 23:48:46 -0400 Subject: [Tutor] how obsolete is 2.2, and a pickle question Message-ID: <CAL2Y8-QYCWQff=VgxTyW4SXSp7Fc8s8exrzBRNtFhg2VfseL3g@mail.gmail.com> I found a book at the local library that covers python but it's 2.2. I already have been using 2.7 for basic stuff and would like to know if it's worth my time to read this book. Are there any glaring differences that would be easy to point out, or is it too convoluted? Also, am I correct in thinking that 3.0 will always be called 3.0 but will change over time and will always include experimental features, while 2.x will gradually increase the 'x' and the highest 'x' will indicate the most current, stable release? oh, and a question on 'pickle': can pickle deserialize things that were not serialized by python? can it convert data into a python data type regardless of it was originally a 'c array' or something else that python doesn't support? -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110907/0a480dbe/attachment.html> From stefan_ml at behnel.de Thu Sep 8 07:36:24 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 08 Sep 2011 07:36:24 +0200 Subject: [Tutor] how obsolete is 2.2? In-Reply-To: <CAL2Y8-SqwPGVpfQBHb0G1DKdavBOr5MR6q3K7upCQStLhK6eoQ@mail.gmail.com> References: <CAL2Y8-SqwPGVpfQBHb0G1DKdavBOr5MR6q3K7upCQStLhK6eoQ@mail.gmail.com> Message-ID: <j49k8p$ifg$1@dough.gmane.org> Hi, please don't repost your question before waiting at least a little for an answer. c smith, 08.09.2011 05:26: > I found a book at the local library that covers python but it's 2.2. That's way old then. It won't teach you anything about the really interesting and helpful things in Python, such as generators, itertools or the "with" statement, extended APIs and stdlib modules, and loads of other goodies and enhanced features, such as metaclasses and interpreter configuration stuff. > I already have been using 2.7 for basic stuff and would like to know if it's > worth my time to read this book. Likely not. Better read a recent tutorial or spend your time getting used to the official Python documentation. > Are there any glaring differences that would be easy to point out, or is it > too convoluted? Tons of them, too many to even get started. You might want to take a look at the "what's new" pages in the Python documentation. That will give you a pretty good idea of major advances. > Also, am I correct in thinking that 3.0 will always be called 3.0 No. It's called Python 3 (sometimes historically named Python 3k or Python 3000), with released versions being 3.0, 3.1.x and 3.2.x and the upcoming release being 3.3. > but will change over time and will always include experimental features Well, it's the place where all current development happens, be it experimental or not. > while 2.x will gradually increase the 'x' Nope. 'x' is fixed at 7, Py2.7 is the officially last release series of Python 2, although with an extended maintenance time frame of several years. > and the highest 'x' will indicate the most current, stable release? That's right, both for the Py2.x and Py3.x releases. > oh, and a question on 'pickle': Let's keep that in your other post, to let it serve a purpose. Stefan From __peter__ at web.de Thu Sep 8 10:15:19 2011 From: __peter__ at web.de (Peter Otten) Date: Thu, 08 Sep 2011 10:15:19 +0200 Subject: [Tutor] how obsolete is 2.2, and a pickle question References: <CAL2Y8-QYCWQff=VgxTyW4SXSp7Fc8s8exrzBRNtFhg2VfseL3g@mail.gmail.com> Message-ID: <j49tii$ac4$1@dough.gmane.org> c smith wrote: > oh, and a question on 'pickle': > can pickle deserialize things that were not serialized by python? > can it convert data into a python data type regardless of it was > originally a 'c array' or something else that python doesn't support? As long as the file written by C is a valid pickle file and all classes used are available to the Python interpreter you are fine: $ cat pickledemo_struct.c #include <stdio.h> typedef struct NAMEDPAIR { char name[10]; int x; int y; } namedpair; main() { FILE *f = fopen("tmp_struct.pickle", "wb"); int i; namedpair *p, data[] = {{"Cube", 10, 20}, {"Pyramid", 30, 40}}; fprintf(f, "(lp0\n"); for (i = 0, p = data; i != 2; i++, p++) { fprintf(f, "(S'%s'\nI%d\nI%d\ntp%d\na", p->name, p->x, p->y, i+1); } fprintf(f, "."); } $ gcc pickledemo_struct.c $ ./a.out $ python -c 'import pickle; print pickle.load(open("tmp_struct.pickle"))' [('Cube', 10, 20), ('Pyramid', 30, 40)] But remember that in C the information whether you have a 32 bit integer or four characters is in the code, not in the data; if you just dump that data to a file Python can still read it, but has no way of knowing what it's meant to be. From alan.gauld at btinternet.com Thu Sep 8 10:25:25 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 08 Sep 2011 09:25:25 +0100 Subject: [Tutor] how obsolete is 2.2? In-Reply-To: <CAL2Y8-SqwPGVpfQBHb0G1DKdavBOr5MR6q3K7upCQStLhK6eoQ@mail.gmail.com> References: <CAL2Y8-SqwPGVpfQBHb0G1DKdavBOr5MR6q3K7upCQStLhK6eoQ@mail.gmail.com> Message-ID: <j49u2l$er0$1@dough.gmane.org> On 08/09/11 04:26, c smith wrote: > I found a book at the local library that covers python but it's 2.2. > I already have been using 2.7 for basic stuff and would like to know if > it's worth my time to read this book. That depends on your experience level and what you are looking to get out of it. The Python 2 series is very backwards compatible so virtually everything you read in the book will still work in Python 2.7. It's just that some new whizzy features have been added since 2.2 that it won't cover. But many of those features are not things the average programmer uses every day. The vast majority of the standard library modules haven't changed that much and any information about those will probably still be accurate. Given you get to read it for free from the library I'd say yes, its very worthwhile. But if you have been using Python for a while and want to dig deeper into its power features then it probably isn't worth reading because the changes in Python recently have focused on many of the more subtle things "under the covers" and 2.2 won't cover them, > can pickle deserialize things that were not serialized by python? Not unless the thing that serialised them was deliberately copying Pythons serialisation format. > can it convert data into a python data type regardless of it was > originally a 'c array' or something else that python doesn't support? No, the nearest thing to that is the struct module. But there you have to know what you are reading and construct a format specifier to match. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From washakie at gmail.com Thu Sep 8 12:10:48 2011 From: washakie at gmail.com (John) Date: Thu, 8 Sep 2011 12:10:48 +0200 Subject: [Tutor] understanding **kwargs syntax In-Reply-To: <j3522j$5or$1@dough.gmane.org> References: <CAFPhvcpP8qFS1wxZGXBPx68pPFR-K9Z3mnyV2pfbv622O76cRA@mail.gmail.com> <j3522j$5or$1@dough.gmane.org> Message-ID: <CAFPhvcqZD5Po33-2H-r02z1r5xDcfzsA-RKii9qxsE-q5SHP_g@mail.gmail.com> Following up on this... Why does pylint seem to think it is a bad idea? Description Resource Path Location Type ID:W0142 plot_ts_array_split_x: Used * or ** magic tsplot.py /research.plot line 299 PyLint Problem Thanks, john On Thu, Aug 25, 2011 at 10:44 AM, Alan Gauld <alan.gauld at btinternet.com> wrote: > On 25/08/11 09:27, John wrote: >> >> Just a quick question, >> >> is it wrong to use the *args and **kwargs ( the latter in particular) >> when DEFINING a function? > > No, in fact it's essential if you don't know in advance what arguments are > going to be passed to the function. This is very common if you are wrapping > another function that itself takes variable arguments. > >> def fest(**kwargs): >> ? ? """ a function test """ >> ? ? keys = sorted(kwargs.keys()) >> >> ? ? print("You provided {0} keywords::\n".format(len(keys))) >> ? ? for kw in keys: >> ? ? ? ? print("{0} => ?{1}".format(kw, kwargs[kw])) >> >> Are there some good examples of when this would be a good idea to >> implement? > > GUI frameworks like Tkinter often take variable numbers of configuration > values. If you want to wrap that with a > function of your own you can do something like(pseudocode): > > def myfunc(**kwargs): > ? if some interesting arg exists > ? ? ? ?do something with it > ? return wrappedFunc(kwargs) > > There are plenty other cases, try grepping the standard library code > for lines with def and **kwargs for some examples... > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Configuration `````````````````````````` Plone 2.5.3-final, CMF-1.6.4, Zope (Zope 2.9.7-final, python 2.4.4, linux2), Python 2.6 PIL 1.1.6 Mailman 2.1.9 Postfix 2.4.5 Procmail v3.22 2001/09/10 Basemap: 1.0 Matplotlib: 1.0.0 From rdmoores at gmail.com Thu Sep 8 12:58:37 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Thu, 8 Sep 2011 03:58:37 -0700 Subject: [Tutor] need advice about a dictionary ({}) Message-ID: <CALMxxxm2fA_Yo4bQMRHznYXBFZwD03ze-mXo1WeY7VkfM+1J9w@mail.gmail.com> I've succeeded in writing a dictionary ({}) that I can use as a small personal phone book. The dictionary (very shortened and simplified) looks like this in the script; p = {} p['bp1'] = 'xxx' p['bp2'] = 'ooo' p['ch'] = 'zzz' p['me'] = 'aaa' p['mg'] = 'vvv' p['pu1'] = 'bbb' p['pu2'] = 'ccc' p['pw'] = 'kkk' I have a function that enables the user to enter 'bp', for example, and return both 'xxx' and 'ooo'. (The keys are initials; I've disguised the values, each of which of course are name, home number, mobile number, speed dial number, etc.) But I'd like to put the lines of the dictionary in a text file so that I can add key/value items to it by writing to it with another script. I think I can do that, but I need some hints about how to get the script to access the text file in a way that lets the user look up a phone number. I'm thinking that the script needs to recreate the dictionary each time it's called, but I don't know how to do that. Thanks, Dick Moores From __peter__ at web.de Thu Sep 8 13:23:30 2011 From: __peter__ at web.de (Peter Otten) Date: Thu, 08 Sep 2011 13:23:30 +0200 Subject: [Tutor] understanding **kwargs syntax References: <CAFPhvcpP8qFS1wxZGXBPx68pPFR-K9Z3mnyV2pfbv622O76cRA@mail.gmail.com> <j3522j$5or$1@dough.gmane.org> <CAFPhvcqZD5Po33-2H-r02z1r5xDcfzsA-RKii9qxsE-q5SHP_g@mail.gmail.com> Message-ID: <j4a8je$num$1@dough.gmane.org> John wrote: > Following up on this... > > Why does pylint seem to think it is a bad idea? > > Description Resource Path Location Type > ID:W0142 plot_ts_array_split_x: Used * or ** > magic tsplot.py /research.plot line 299 PyLint Problem I would guess it's a readability concern. Consider a simple function def f(x, y=0): print x + y for a in [1], "ab", "abc": f(*a) Can you tell what will be printed immediately? For me f(1) f("a", "b") f("a", "b", "c") is much easier to predict. That said, there are valid usecases for * and ** "magic", and of course pylint cannot take the tradeoffs into account. Therefore don't take pylint's warnings as gospel. PS: the exception is intentional From cwitts at compuscan.co.za Thu Sep 8 13:36:46 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Thu, 08 Sep 2011 13:36:46 +0200 Subject: [Tutor] need advice about a dictionary ({}) In-Reply-To: <CALMxxxm2fA_Yo4bQMRHznYXBFZwD03ze-mXo1WeY7VkfM+1J9w@mail.gmail.com> References: <CALMxxxm2fA_Yo4bQMRHznYXBFZwD03ze-mXo1WeY7VkfM+1J9w@mail.gmail.com> Message-ID: <4E68A8CE.6030307@compuscan.co.za> On 2011/09/08 12:58 PM, Richard D. Moores wrote: > I've succeeded in writing a dictionary ({}) that I can use as a small > personal phone book. The dictionary (very shortened and simplified) > looks like this in the script; > > p = {} > > p['bp1'] = 'xxx' > p['bp2'] = 'ooo' > p['ch'] = 'zzz' > p['me'] = 'aaa' > p['mg'] = 'vvv' > p['pu1'] = 'bbb' > p['pu2'] = 'ccc' > p['pw'] = 'kkk' > > I have a function that enables the user to enter 'bp', for example, > and return both 'xxx' and 'ooo'. > > (The keys are initials; I've disguised the values, each of which of > course are name, home number, mobile number, speed dial number, > etc.) > > But I'd like to put the lines of the dictionary in a text file so that > I can add key/value items to it by writing to it with another script. > I think I can do that, but I need some hints about how to get the > script to access the text file in a way that lets the user look up a > phone number. I'm thinking that the script needs to recreate the > dictionary each time it's called, but I don't know how to do that. > > Thanks, > > Dick Moores > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > You could pickle your dictionary object which will give you the persistence and then when your script starts up you can unpickle the file if it exists else create a new one. Of course if you make any changes to your object you'll need to pickle it once your app finishes otherwise new changes won't be written out. With just a plain text file you can also just grep the info out $ cat test.file bp1:xxx|yyy bp2:ooo|ppp ch:zzz|asf me:agkjh|agjh $ grep -i ^bp* test.file bp1:xxx|yyy bp2:ooo|ppp $ grep -i ^BP* test.file bp1:xxx|yyy bp2:ooo|ppp -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110908/8f16555e/attachment.html> From rdmoores at gmail.com Thu Sep 8 13:41:18 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Thu, 8 Sep 2011 04:41:18 -0700 Subject: [Tutor] need advice about a dictionary ({}) In-Reply-To: <4E68A8CE.6030307@compuscan.co.za> References: <CALMxxxm2fA_Yo4bQMRHznYXBFZwD03ze-mXo1WeY7VkfM+1J9w@mail.gmail.com> <4E68A8CE.6030307@compuscan.co.za> Message-ID: <CALMxxx=-mZnnaAfRQqTwEZtZrdA_T+GKpWYN3YXedgquvwV74Q@mail.gmail.com> On Thu, Sep 8, 2011 at 04:36, Christian Witts <cwitts at compuscan.co.za> wrote: > On 2011/09/08 12:58 PM, Richard D. Moores wrote: > > I've succeeded in writing a dictionary ({}) that I can use as a small > personal phone book. The dictionary (very shortened and simplified) > looks like this in the script; > > p = {} > > p['bp1'] = 'xxx' > p['bp2'] = 'ooo' > p['ch'] = 'zzz' > p['me'] = 'aaa' > p['mg'] = 'vvv' > p['pu1'] = 'bbb' > p['pu2'] = 'ccc' > p['pw'] = 'kkk' > > I have a function that enables the user to enter 'bp', for example, > and return both 'xxx' and 'ooo'. > > (The keys are initials; I've disguised the values, each of which of > course are name, home number, mobile number, speed dial number, > etc.) > > But I'd like to put the lines of the dictionary in a text file so that > I can add key/value items to it by writing to it with another script. > I think I can do that, but I need some hints about how to get the > script to access the text file in a way that lets the user look up a > phone number. I'm thinking that the script needs to recreate the > dictionary each time it's called, but I don't know how to do that. > > Thanks, > > Dick Moores > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > > You could pickle your dictionary object which will give you the persistence > and then when your script starts up you can unpickle the file if it exists > else create a new one. Of course if you make any changes to your object > you'll need to pickle it once your app finishes otherwise new changes won't > be written out. > > With just a plain text file you can also just grep the info out > $ cat test.file > bp1:xxx|yyy > bp2:ooo|ppp > ch:zzz|asf > me:agkjh|agjh > $ grep -i ^bp* test.file > bp1:xxx|yyy > bp2:ooo|ppp > $ grep -i ^BP* test.file > bp1:xxx|yyy > bp2:ooo|ppp I should have stated that I'm using Win 7, Python 3.2.1. No Unix. Dick From __peter__ at web.de Thu Sep 8 13:43:34 2011 From: __peter__ at web.de (Peter Otten) Date: Thu, 08 Sep 2011 13:43:34 +0200 Subject: [Tutor] need advice about a dictionary ({}) References: <CALMxxxm2fA_Yo4bQMRHznYXBFZwD03ze-mXo1WeY7VkfM+1J9w@mail.gmail.com> Message-ID: <j4a9p1$a4$1@dough.gmane.org> Richard D. Moores wrote: > I've succeeded in writing a dictionary ({}) that I can use as a small > personal phone book. The dictionary (very shortened and simplified) > looks like this in the script; > > p = {} > > p['bp1'] = 'xxx' > p['bp2'] = 'ooo' > p['ch'] = 'zzz' > p['me'] = 'aaa' > p['mg'] = 'vvv' > p['pu1'] = 'bbb' > p['pu2'] = 'ccc' > p['pw'] = 'kkk' > > I have a function that enables the user to enter 'bp', for example, > and return both 'xxx' and 'ooo'. > > (The keys are initials; I've disguised the values, each of which of > course are name, home number, mobile number, speed dial number, > etc.) > > But I'd like to put the lines of the dictionary in a text file so that > I can add key/value items to it by writing to it with another script. > I think I can do that, but I need some hints about how to get the > script to access the text file in a way that lets the user look up a > phone number. I'm thinking that the script needs to recreate the > dictionary each time it's called, but I don't know how to do that. Start with a simple file format. If you don't allow "=" in the key and "\n" in either key or value bp1=xxx bp2=ooo ... pw=kkk should do. I suppose you know how to read a file one line at a time? Before you add the line into the dictionary you have to separate key and value (str.partition() may help with that) and remove the trailing newline from the value. If you need more flexibility look into the json module. This makes reading and writing the file even easier, and while the format is a bit more complex than key=value >>> print json.dumps(p, indent=2) { "me": "aaa", "mg": "vvv", "ch": "zzz", "pw": "kkk", "bp1": "xxx", "bp2": "ooo", "pu1": "bbb", "pu2": "ccc" } it can still be edited by a human. From steve at pearwood.info Thu Sep 8 14:51:00 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 08 Sep 2011 22:51:00 +1000 Subject: [Tutor] how obsolete is 2.2? In-Reply-To: <CAL2Y8-SqwPGVpfQBHb0G1DKdavBOr5MR6q3K7upCQStLhK6eoQ@mail.gmail.com> References: <CAL2Y8-SqwPGVpfQBHb0G1DKdavBOr5MR6q3K7upCQStLhK6eoQ@mail.gmail.com> Message-ID: <4E68BA34.6080800@pearwood.info> c smith wrote: > Also, am I correct in thinking that 3.0 will always be called 3.0 but will > change over time and will always include experimental features, while 2.x > will gradually increase the 'x' and the highest 'x' will indicate the most > current, stable release? No, I'm afraid you are wrong. Python 2.7 is the last version in the 2.x series. It will continue to get bug fixes and security updates for the next few years, but no new features. 2.7 and 3.2 are the most up to date versions. As I said, 2.7 is the last of the 2.x line. 3.x is the future of Python, although 2.7 will be supported for quite some time. But all new features will be going into 3.x and 2.7 will only get bug fixes. Python 3.0 is no longer supported: to be frank, it was released too early, and it has too many bugs and is painfully slow. If you are using 3.0, you should update to 3.1 or 3.2, they are much, much better. -- Steven From lina.lastname at gmail.com Thu Sep 8 14:59:21 2011 From: lina.lastname at gmail.com (lina) Date: Thu, 8 Sep 2011 20:59:21 +0800 Subject: [Tutor] a quick Q: built-in method pop of list object at 0x7f8221a22cb0> Message-ID: <CAG9cJmkY6AbnpFkVhxJZUW61jKovNo2B5R72J_uKAq6UV5Cc6A@mail.gmail.com> Hi, <built-in method pop of list object at 0x7f8221a22cb0> what does the 0x7f8221a22cb0 mean here? the computer physical address. Thanks, -- Best Regards, lina From lina.lastname at gmail.com Thu Sep 8 15:02:45 2011 From: lina.lastname at gmail.com (lina) Date: Thu, 8 Sep 2011 21:02:45 +0800 Subject: [Tutor] a quick Q: what does the "collapse" mean? Message-ID: <CAG9cJmkunPcvCE5quzpoSVdjA1TEw=cTD_oM14znbLC58Br1hQ@mail.gmail.com> Hi, I failed to understand the "collpase" meaning in a string. can someone give me a simple example? Sorry, -- Best Regards, lina From steve at pearwood.info Thu Sep 8 15:03:23 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 08 Sep 2011 23:03:23 +1000 Subject: [Tutor] need advice about a dictionary ({}) In-Reply-To: <CALMxxxm2fA_Yo4bQMRHznYXBFZwD03ze-mXo1WeY7VkfM+1J9w@mail.gmail.com> References: <CALMxxxm2fA_Yo4bQMRHznYXBFZwD03ze-mXo1WeY7VkfM+1J9w@mail.gmail.com> Message-ID: <4E68BD1B.6070509@pearwood.info> Richard D. Moores wrote: > But I'd like to put the lines of the dictionary in a text file so that > I can add key/value items to it by writing to it with another script. If you expect human beings (yourself, or possibly even the user) to edit the text file, then you should look at a human-writable format like these: Good ol' fashioned Windows INI files: import configparser JSON: import json PLIST: import plistlib YAML: download from http://pyyaml.org/wiki/PyYAML If the ability to edit the files isn't important, then I suggest using the pickle module instead. -- Steven From rdmoores at gmail.com Thu Sep 8 15:40:24 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Thu, 8 Sep 2011 06:40:24 -0700 Subject: [Tutor] need advice about a dictionary ({}) In-Reply-To: <j4a9p1$a4$1@dough.gmane.org> References: <CALMxxxm2fA_Yo4bQMRHznYXBFZwD03ze-mXo1WeY7VkfM+1J9w@mail.gmail.com> <j4a9p1$a4$1@dough.gmane.org> Message-ID: <CALMxxxmYnzRxSbrgY3hdu-fkpAHGzEgpYTGDjsNPN=c4XqEZyw@mail.gmail.com> On Thu, Sep 8, 2011 at 04:43, Peter Otten <__peter__ at web.de> wrote: > Richard D. Moores wrote: > >> I've succeeded in writing a dictionary ({}) that I can use as a small >> personal phone book. The dictionary (very shortened and simplified) >> looks like this in the script; >> >> p = {} >> >> p['bp1'] = 'xxx' >> p['bp2'] = 'ooo' >> p['ch'] = 'zzz' >> p['me'] = 'aaa' >> p['mg'] = 'vvv' >> p['pu1'] = 'bbb' >> p['pu2'] = 'ccc' >> p['pw'] = 'kkk' >> >> I have a function that enables the user to enter 'bp', for example, >> and return both 'xxx' and 'ooo'. >> >> (The keys are initials; I've disguised the values, each of which of >> course are ? name, home number, mobile number, speed dial number, >> etc.) >> >> But I'd like to put the lines of the dictionary in a text file so that >> I can add key/value items to it by writing to it with another script. >> I think I can do that, but I need some hints about how to get ?the >> script to access the text file in a way that lets the user look up a >> phone number. I'm thinking that the script needs to recreate the >> dictionary each time it's called, but I don't know how to do that. > > Start with a simple file format. If you don't allow "=" in the key and "\n" > in either key or value > > bp1=xxx > bp2=ooo > ... > pw=kkk > > should do. I suppose you know how to read a file one line at a time? Before > you add the line into the dictionary you have to separate key and value > (str.partition() may help with that) and remove the trailing newline from > the value. If you need more flexibility look into the json module. This > makes reading and writing the file even easier, and while the format is a > bit more complex than key=value > >>>> print json.dumps(p, indent=2) > { > ?"me": "aaa", > ?"mg": "vvv", > ?"ch": "zzz", > ?"pw": "kkk", > ?"bp1": "xxx", > ?"bp2": "ooo", > ?"pu1": "bbb", > ?"pu2": "ccc" > } > > it can still be edited by a human. Thanks Peter! You made it a lot easier than I thought it would be. Please see <http://pastebin.com/NbzBNMDW> for the script's current incarnation. The text of the demo data file is quoted in the script, lines 6-13. It doesn't seem I need to use the json module, though I want to learn it eventually. The data file very easily edited. However, as the number of lines gets large (maybe 100?) I'll need a way to determine if the new key is already in the file. So I'll be working on a script that I can use to safely add lines to the the file, by keeping all the keys unique. Dick From alan.gauld at btinternet.com Thu Sep 8 15:53:19 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 08 Sep 2011 14:53:19 +0100 Subject: [Tutor] understanding **kwargs syntax In-Reply-To: <CAFPhvcqZD5Po33-2H-r02z1r5xDcfzsA-RKii9qxsE-q5SHP_g@mail.gmail.com> References: <CAFPhvcpP8qFS1wxZGXBPx68pPFR-K9Z3mnyV2pfbv622O76cRA@mail.gmail.com> <j3522j$5or$1@dough.gmane.org> <CAFPhvcqZD5Po33-2H-r02z1r5xDcfzsA-RKii9qxsE-q5SHP_g@mail.gmail.com> Message-ID: <j4ah9a$p0p$1@dough.gmane.org> On 08/09/11 11:10, John wrote: > Following up on this... > > Why does pylint seem to think it is a bad idea? > > Description Resource Path Location Type > ID:W0142 plot_ts_array_split_x: Used * or ** > magic tsplot.py /research.plot line 299 PyLint Problem I assume because it is a bad idea in most cases. If you know what the arguments are going to be then specify them. Otherwise you can get all sorts of rubbish being passed in that you have to figure out how to deal with. That's never a good place to be. But occasionally you have to do things that are less than ideal. And *args/**kwargs are useful in those situations, just don't use them unless you have to. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From rdmoores at gmail.com Thu Sep 8 15:52:25 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Thu, 8 Sep 2011 06:52:25 -0700 Subject: [Tutor] need advice about a dictionary ({}) In-Reply-To: <j4a9p1$a4$1@dough.gmane.org> References: <CALMxxxm2fA_Yo4bQMRHznYXBFZwD03ze-mXo1WeY7VkfM+1J9w@mail.gmail.com> <j4a9p1$a4$1@dough.gmane.org> Message-ID: <CALMxxxkuFf31H-8dRMe+fjX+SVH4RO8q+JKBU7FQOnh7ih_psg@mail.gmail.com> On Thu, Sep 8, 2011 at 04:43, Peter Otten <__peter__ at web.de> wrote: > Richard D. Moores wrote: > >> I've succeeded in writing a dictionary ({}) that I can use as a small >> personal phone book. The dictionary (very shortened and simplified) >> looks like this in the script; >> >> p = {} >> >> p['bp1'] = 'xxx' >> p['bp2'] = 'ooo' >> p['ch'] = 'zzz' >> p['me'] = 'aaa' >> p['mg'] = 'vvv' >> p['pu1'] = 'bbb' >> p['pu2'] = 'ccc' >> p['pw'] = 'kkk' >> >> I have a function that enables the user to enter 'bp', for example, >> and return both 'xxx' and 'ooo'. >> >> (The keys are initials; I've disguised the values, each of which of >> course are ? name, home number, mobile number, speed dial number, >> etc.) >> >> But I'd like to put the lines of the dictionary in a text file so that >> I can add key/value items to it by writing to it with another script. >> I think I can do that, but I need some hints about how to get ?the >> script to access the text file in a way that lets the user look up a >> phone number. I'm thinking that the script needs to recreate the >> dictionary each time it's called, but I don't know how to do that. > > Start with a simple file format. If you don't allow "=" in the key and "\n" > in either key or value > > bp1=xxx > bp2=ooo > ... > pw=kkk > > should do. I suppose you know how to read a file one line at a time? Before > you add the line into the dictionary you have to separate key and value > (str.partition() may help with that) and remove the trailing newline from > the value. If you need more flexibility look into the json module. This > makes reading and writing the file even easier, and while the format is a > bit more complex than key=value > >>>> print json.dumps(p, indent=2) > { > ?"me": "aaa", > ?"mg": "vvv", > ?"ch": "zzz", > ?"pw": "kkk", > ?"bp1": "xxx", > ?"bp2": "ooo", > ?"pu1": "bbb", > ?"pu2": "ccc" > } > > it can still be edited by a human. Thanks Peter! You made it a lot easier than I thought it would be. Please see <http://pastebin.com/NbzBNMDW> for the script's current incarnation. The text of the demo data file is quoted in the script, lines 6-13. It doesn't seem I need to use the json module, though I want to learn it eventually. The data file very easily edited. However, as the number of lines gets large (maybe 100?) I'll need a way to determine if the new key is already in the file. So I'll be working on a script that I can use to safely add lines to the the file, by keeping all the keys unique. Dick From steve at pearwood.info Thu Sep 8 15:56:27 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 08 Sep 2011 23:56:27 +1000 Subject: [Tutor] a quick Q: built-in method pop of list object at 0x7f8221a22cb0> In-Reply-To: <CAG9cJmkY6AbnpFkVhxJZUW61jKovNo2B5R72J_uKAq6UV5Cc6A@mail.gmail.com> References: <CAG9cJmkY6AbnpFkVhxJZUW61jKovNo2B5R72J_uKAq6UV5Cc6A@mail.gmail.com> Message-ID: <4E68C98B.5010106@pearwood.info> lina wrote: > Hi, > > > <built-in method pop of list object at 0x7f8221a22cb0> > > > what does the 0x7f8221a22cb0 mean here? the computer physical address. That's the ID of the list object, converted to hexadecimal. Every object in Python gets a unique (for the life of the object) ID. In CPython, the version you are using, that ID happens to be the memory address, and can be reused. For Jython and IronPython, the ID is an auto-incrementing counter, and will never be re-used: first object created gets ID 1 second object gets ID 2 third object gets ID 3 ... etc. -- Steven From steve at pearwood.info Thu Sep 8 15:58:21 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 08 Sep 2011 23:58:21 +1000 Subject: [Tutor] a quick Q: what does the "collapse" mean? In-Reply-To: <CAG9cJmkunPcvCE5quzpoSVdjA1TEw=cTD_oM14znbLC58Br1hQ@mail.gmail.com> References: <CAG9cJmkunPcvCE5quzpoSVdjA1TEw=cTD_oM14znbLC58Br1hQ@mail.gmail.com> Message-ID: <4E68C9FD.6060106@pearwood.info> lina wrote: > Hi, > > I failed to understand the "collpase" meaning in a string. > > can someone give me a simple example? > > Sorry, I don't understand what you mean. Can you give context? -- Steven From alan.gauld at btinternet.com Thu Sep 8 15:59:59 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 08 Sep 2011 14:59:59 +0100 Subject: [Tutor] a quick Q: what does the "collapse" mean? In-Reply-To: <CAG9cJmkunPcvCE5quzpoSVdjA1TEw=cTD_oM14znbLC58Br1hQ@mail.gmail.com> References: <CAG9cJmkunPcvCE5quzpoSVdjA1TEw=cTD_oM14znbLC58Br1hQ@mail.gmail.com> Message-ID: <j4ahlq$p0p$3@dough.gmane.org> On 08/09/11 14:02, lina wrote: > Hi, > > I failed to understand the "collpase" meaning in a string. > > can someone give me a simple example? Can you give us some context? Its not a method of a string object so far as I can tell? Where did you read about it? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Sep 8 15:58:06 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 08 Sep 2011 14:58:06 +0100 Subject: [Tutor] a quick Q: built-in method pop of list object at 0x7f8221a22cb0> In-Reply-To: <CAG9cJmkY6AbnpFkVhxJZUW61jKovNo2B5R72J_uKAq6UV5Cc6A@mail.gmail.com> References: <CAG9cJmkY6AbnpFkVhxJZUW61jKovNo2B5R72J_uKAq6UV5Cc6A@mail.gmail.com> Message-ID: <j4ahi8$p0p$2@dough.gmane.org> On 08/09/11 13:59, lina wrote: > <built-in method pop of list object at 0x7f8221a22cb0> > > what does the 0x7f8221a22cb0 mean here? the computer physical address. It's a unique identifier for the object which is implementation dependant. In practice you can consider it the memory address. But I wouldn't try using it as an address by passing it into a C function say. That's not guaranteed to work at all! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Sep 8 16:03:33 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 08 Sep 2011 15:03:33 +0100 Subject: [Tutor] need advice about a dictionary ({}) In-Reply-To: <CALMxxxm2fA_Yo4bQMRHznYXBFZwD03ze-mXo1WeY7VkfM+1J9w@mail.gmail.com> References: <CALMxxxm2fA_Yo4bQMRHznYXBFZwD03ze-mXo1WeY7VkfM+1J9w@mail.gmail.com> Message-ID: <j4ahsh$tso$1@dough.gmane.org> On 08/09/11 11:58, Richard D. Moores wrote: > I've succeeded in writing a dictionary ({}) that I can use as a small > personal phone book. The dictionary (very shortened and simplified) > looks like this in the script; > > p = {} > > p['bp1'] = 'xxx' > p['bp2'] = 'ooo' > p['ch'] = 'zzz' > p['me'] = 'aaa' > p['mg'] = 'vvv' > p['pu1'] = 'bbb' > p['pu2'] = 'ccc' > p['pw'] = 'kkk' > You could have done that in one line if you preferred: > p = { 'bp1':'xxx', 'bp2':'ooo' etc/... 'pw':'kkk' } > But I'd like to put the lines of the dictionary in a text file so that > I can add key/value items to it by writing to it with another script. Consider using a shelve (See the shelve module) It is basically a file that you can treat as a dictionary... Try: >>> import shelve >>> help(shelve) For examples and info. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From jjhartley at gmail.com Thu Sep 8 16:08:07 2011 From: jjhartley at gmail.com (James Hartley) Date: Thu, 8 Sep 2011 07:08:07 -0700 Subject: [Tutor] throwing exception across modules? Message-ID: <CAKeNXXsb3rw2XdLCq4B46HoURUE-1swG6Varvw2ucTK4+6nCcw@mail.gmail.com> This is more a design question. One lesson C++ programmers might learn is that throwing exceptions from within library code is fraught with problems because the internals of exception handling were spelled out in the C++ standard. This manifests itself as problems when the library was compiled with one vendor's compiler, but the user of the library is using another compiler. While I understand that Python doesn't suffer from this exact problem, are there other reasons that raising exceptions in a module only be caught by consumers of the module a bad idea? Any insight which can be shared would be most appreciated. Thanks. Jim -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110908/f238cd8a/attachment.html> From lina.lastname at gmail.com Thu Sep 8 16:11:37 2011 From: lina.lastname at gmail.com (lina) Date: Thu, 8 Sep 2011 22:11:37 +0800 Subject: [Tutor] a quick Q: built-in method pop of list object at 0x7f8221a22cb0> In-Reply-To: <j4ahi8$p0p$2@dough.gmane.org> References: <CAG9cJmkY6AbnpFkVhxJZUW61jKovNo2B5R72J_uKAq6UV5Cc6A@mail.gmail.com> <j4ahi8$p0p$2@dough.gmane.org> Message-ID: <CAG9cJmm4XgvbPrhe75LEUkqyBgUVi0y1oqpZnnPP4bW3x6i8uQ@mail.gmail.com> Thanks, this is very informative. open some windows for me. On Thu, Sep 8, 2011 at 9:58 PM, Alan Gauld <alan.gauld at btinternet.com> wrote: > On 08/09/11 13:59, lina wrote: >> >> <built-in method pop of list object at 0x7f8221a22cb0> >> >> what does the 0x7f8221a22cb0 mean here? the computer physical address. > > It's a unique identifier for the object which is implementation dependant. > In practice you can consider it the memory address. > > But I wouldn't try using it as an address by passing it into a > C function say. That's not guaranteed to work at all! > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Best Regards, lina From lina.lastname at gmail.com Thu Sep 8 16:16:53 2011 From: lina.lastname at gmail.com (lina) Date: Thu, 8 Sep 2011 22:16:53 +0800 Subject: [Tutor] a quick Q: what does the "collapse" mean? In-Reply-To: <j4ahlq$p0p$3@dough.gmane.org> References: <CAG9cJmkunPcvCE5quzpoSVdjA1TEw=cTD_oM14znbLC58Br1hQ@mail.gmail.com> <j4ahlq$p0p$3@dough.gmane.org> Message-ID: <CAG9cJmk98VD0G_YOBm7AfxVTKvM-exKyy8Qd2AunQ3suqbW_aA@mail.gmail.com> On Thu, Sep 8, 2011 at 9:59 PM, Alan Gauld <alan.gauld at btinternet.com> wrote: > On 08/09/11 14:02, lina wrote: >> >> Hi, >> >> I failed to understand the "collpase" meaning in a string. >> >> can someone give me a simple example? > > Can you give us some context? > Its not a method of a string object so far as I can tell? > Where did you read about it? >From "dive into python", http://diveintopython.org/ one example: def info(object, spacing=10, collapse=1): """Print methods and docs strings. Take modules, class, list, dictionary, or strong.""" methodList = [e for e in dir(object) if callable(getattr(object, e))] processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s) print "\n".join(["%s %s" % (method.ljust(spacing), processFunc(str(getattr(object, method).__doc__))) for method in methodList]) if __name__ == "__main__": print info.__doc__ I felt so hard to understand the collapse, Please don't discourage me telling me it's an old book, To me I started reading till 42 pages. let me finish it. I used to study python on and off, sometimes give a whole week, but due to not using it, so it's frustrating that when I really needed it, I barely could complete one. > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Best Regards, lina From steve at pearwood.info Thu Sep 8 16:34:29 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 09 Sep 2011 00:34:29 +1000 Subject: [Tutor] throwing exception across modules? In-Reply-To: <CAKeNXXsb3rw2XdLCq4B46HoURUE-1swG6Varvw2ucTK4+6nCcw@mail.gmail.com> References: <CAKeNXXsb3rw2XdLCq4B46HoURUE-1swG6Varvw2ucTK4+6nCcw@mail.gmail.com> Message-ID: <4E68D275.4090205@pearwood.info> James Hartley wrote: > This is more a design question. > > One lesson C++ programmers might learn is that throwing exceptions from > within library code is fraught with problems because the internals of > exception handling were spelled out in the C++ standard. This manifests Do you mean "weren't spelled out"? > itself as problems when the library was compiled with one vendor's compiler, > but the user of the library is using another compiler. > > While I understand that Python doesn't suffer from this exact problem, are > there other reasons that raising exceptions in a module only be caught by > consumers of the module a bad idea? Not at all. Python is designed to use exceptions as the primary error mechanism. Nearly every module and function you will use in Python will use exceptions to signal errors. A few will also use exceptions to signal non-error exceptional cases, e.g. StopIteration is used by iterators when they run out of items. Exceptions in Python aren't bolted on the top, they are fundamental to the way the language works. Even things like for loops work by catching exceptions. > Any insight which can be shared would be most appreciated. The only thing which sometimes catches out beginners is that they forget to use fully-qualified names for exceptions. E.g. you may need to do this: import socket try: ... except socket.error: ... instead of just "except error". If possible, document which exceptions your code might throw. At least, document which exceptions you expect to throw under normal circumstances. An exception in the top level of your module will be treated as fatal: it will prevent the module from being imported. (When I say fatal, I mean fatal for your module, not the caller: the caller can always catch the exception and skip the import.) Think carefully about what exceptions you should use. Try to integrate with the standard Python exception hierarchy. See the docs for further details. It's a matter of opinion whether you should use built-in exceptions as-is, or whether you subclass them. Subclassing can be as simple as: class StatsError(ValueError): pass or as complicated as you want. But in general, keep exceptions simple. Try not to raise private exceptions where the caller will see them. In other words, if you define a private exception type by flagging the name with a leading single underscore: class _InternalUseOnly(TypeError): # single underscore means "private" pass then never raise it unless you also catch it. -- Steven From andreengels at gmail.com Thu Sep 8 16:36:13 2011 From: andreengels at gmail.com (Andre Engels) Date: Thu, 8 Sep 2011 16:36:13 +0200 Subject: [Tutor] a quick Q: what does the "collapse" mean? In-Reply-To: <CAG9cJmk98VD0G_YOBm7AfxVTKvM-exKyy8Qd2AunQ3suqbW_aA@mail.gmail.com> References: <CAG9cJmkunPcvCE5quzpoSVdjA1TEw=cTD_oM14znbLC58Br1hQ@mail.gmail.com> <j4ahlq$p0p$3@dough.gmane.org> <CAG9cJmk98VD0G_YOBm7AfxVTKvM-exKyy8Qd2AunQ3suqbW_aA@mail.gmail.com> Message-ID: <CAGzCZ0rzDMZ0jZaYkCMVEekN98pkUc56WxAs4o3_a_5s5exXtw@mail.gmail.com> On Thu, Sep 8, 2011 at 4:16 PM, lina <lina.lastname at gmail.com> wrote: > On Thu, Sep 8, 2011 at 9:59 PM, Alan Gauld <alan.gauld at btinternet.com> > wrote: > > On 08/09/11 14:02, lina wrote: > >> > >> Hi, > >> > >> I failed to understand the "collpase" meaning in a string. > >> > >> can someone give me a simple example? > > > > Can you give us some context? > > Its not a method of a string object so far as I can tell? > > Where did you read about it? > > >From "dive into python", > > http://diveintopython.org/ > > one example: > > def info(object, spacing=10, collapse=1): > """Print methods and docs strings. > > Take modules, class, list, dictionary, or strong.""" > methodList = [e for e in dir(object) if callable(getattr(object, e))] > processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: > s) > print "\n".join(["%s %s" % > (method.ljust(spacing), > processFunc(str(getattr(object, method).__doc__))) > for method in methodList]) > > if __name__ == "__main__": > print info.__doc__ > > I felt so hard to understand the collapse, > > Please don't discourage me telling me it's an old book, > To me I started reading till 42 pages. let me finish it. > > I used to study python on and off, > sometimes give a whole week, but due to not using it, > so > it's frustrating that when I really needed it, I barely could complete one. > Reading this, it seems that 'collapse' is a variable defined somewhere else in the code. -- Andr? Engels, andreengels at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110908/3e09f203/attachment.html> From joel.goldstick at gmail.com Thu Sep 8 16:48:07 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 8 Sep 2011 10:48:07 -0400 Subject: [Tutor] a quick Q: what does the "collapse" mean? In-Reply-To: <CAGzCZ0rzDMZ0jZaYkCMVEekN98pkUc56WxAs4o3_a_5s5exXtw@mail.gmail.com> References: <CAG9cJmkunPcvCE5quzpoSVdjA1TEw=cTD_oM14znbLC58Br1hQ@mail.gmail.com> <j4ahlq$p0p$3@dough.gmane.org> <CAG9cJmk98VD0G_YOBm7AfxVTKvM-exKyy8Qd2AunQ3suqbW_aA@mail.gmail.com> <CAGzCZ0rzDMZ0jZaYkCMVEekN98pkUc56WxAs4o3_a_5s5exXtw@mail.gmail.com> Message-ID: <CAPM-O+wW=L5235UYLhgf82LPRhx-87BEXGSL-eDoVwzKJCD-kg@mail.gmail.com> On Thu, Sep 8, 2011 at 10:36 AM, Andre Engels <andreengels at gmail.com> wrote: > On Thu, Sep 8, 2011 at 4:16 PM, lina <lina.lastname at gmail.com> wrote: > >> On Thu, Sep 8, 2011 at 9:59 PM, Alan Gauld <alan.gauld at btinternet.com> >> wrote: >> > On 08/09/11 14:02, lina wrote: >> >> >> >> Hi, >> >> >> >> I failed to understand the "collpase" meaning in a string. >> >> >> >> can someone give me a simple example? >> > >> > Can you give us some context? >> > Its not a method of a string object so far as I can tell? >> > Where did you read about it? >> >> >From "dive into python", >> >> http://diveintopython.org/ >> >> one example: >> >> def info(object, spacing=10, collapse=1): >> """Print methods and docs strings. >> >> Take modules, class, list, dictionary, or strong.""" >> methodList = [e for e in dir(object) if callable(getattr(object, e))] >> processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda >> s: s) >> print "\n".join(["%s %s" % >> (method.ljust(spacing), >> processFunc(str(getattr(object, method).__doc__))) >> for method in methodList]) >> >> if __name__ == "__main__": >> print info.__doc__ >> >> I felt so hard to understand the collapse, >> >> Please don't discourage me telling me it's an old book, >> To me I started reading till 42 pages. let me finish it. >> >> I used to study python on and off, >> sometimes give a whole week, but due to not using it, >> so >> it's frustrating that when I really needed it, I barely could complete >> one. >> > > Reading this, it seems that 'collapse' is a variable defined somewhere else > in the code. > > -- > 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 > > collapse is a function that Mark must have described earlier in the chapter you are working on. Are you using the online version? which chapter -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110908/53ff69fe/attachment.html> From joel.goldstick at gmail.com Thu Sep 8 16:50:09 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 8 Sep 2011 10:50:09 -0400 Subject: [Tutor] a quick Q: what does the "collapse" mean? In-Reply-To: <CAPM-O+wW=L5235UYLhgf82LPRhx-87BEXGSL-eDoVwzKJCD-kg@mail.gmail.com> References: <CAG9cJmkunPcvCE5quzpoSVdjA1TEw=cTD_oM14znbLC58Br1hQ@mail.gmail.com> <j4ahlq$p0p$3@dough.gmane.org> <CAG9cJmk98VD0G_YOBm7AfxVTKvM-exKyy8Qd2AunQ3suqbW_aA@mail.gmail.com> <CAGzCZ0rzDMZ0jZaYkCMVEekN98pkUc56WxAs4o3_a_5s5exXtw@mail.gmail.com> <CAPM-O+wW=L5235UYLhgf82LPRhx-87BEXGSL-eDoVwzKJCD-kg@mail.gmail.com> Message-ID: <CAPM-O+xo2x19TzhHoDO_8rsVB-aTswX3e2ABPsvKZSTzskCRgA@mail.gmail.com> On Thu, Sep 8, 2011 at 10:48 AM, Joel Goldstick <joel.goldstick at gmail.com>wrote: > > On Thu, Sep 8, 2011 at 10:36 AM, Andre Engels <andreengels at gmail.com>wrote: > >> On Thu, Sep 8, 2011 at 4:16 PM, lina <lina.lastname at gmail.com> wrote: >> >>> On Thu, Sep 8, 2011 at 9:59 PM, Alan Gauld <alan.gauld at btinternet.com> >>> wrote: >>> > On 08/09/11 14:02, lina wrote: >>> >> >>> >> Hi, >>> >> >>> >> I failed to understand the "collpase" meaning in a string. >>> >> >>> >> can someone give me a simple example? >>> > >>> > Can you give us some context? >>> > Its not a method of a string object so far as I can tell? >>> > Where did you read about it? >>> >>> >From "dive into python", >>> >>> http://diveintopython.org/ >>> >>> one example: >>> >>> def info(object, spacing=10, collapse=1): >>> """Print methods and docs strings. >>> >>> Take modules, class, list, dictionary, or strong.""" >>> methodList = [e for e in dir(object) if callable(getattr(object, e))] >>> processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda >>> s: s) >>> print "\n".join(["%s %s" % >>> (method.ljust(spacing), >>> processFunc(str(getattr(object, method).__doc__))) >>> for method in methodList]) >>> >>> if __name__ == "__main__": >>> print info.__doc__ >>> >>> I felt so hard to understand the collapse, >>> >>> Please don't discourage me telling me it's an old book, >>> To me I started reading till 42 pages. let me finish it. >>> >>> I used to study python on and off, >>> sometimes give a whole week, but due to not using it, >>> so >>> it's frustrating that when I really needed it, I barely could complete >>> one. >>> >> >> Reading this, it seems that 'collapse' is a variable defined somewhere >> else in the code. >> >> -- >> 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 >> >> collapse is a function that Mark must have described earlier in the > chapter you are working on. Are you using the online version? which chapter > > I spoke too soon. collapse is a boolean variable that you set if you want > to have the code in the lamda function collapse the text. If it is False > then the statement returns false instead of whatever is going on in the > Lambda > -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110908/02a05bda/attachment-0001.html> From steve at pearwood.info Thu Sep 8 16:56:54 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 09 Sep 2011 00:56:54 +1000 Subject: [Tutor] a quick Q: what does the "collapse" mean? In-Reply-To: <CAG9cJmk98VD0G_YOBm7AfxVTKvM-exKyy8Qd2AunQ3suqbW_aA@mail.gmail.com> References: <CAG9cJmkunPcvCE5quzpoSVdjA1TEw=cTD_oM14znbLC58Br1hQ@mail.gmail.com> <j4ahlq$p0p$3@dough.gmane.org> <CAG9cJmk98VD0G_YOBm7AfxVTKvM-exKyy8Qd2AunQ3suqbW_aA@mail.gmail.com> Message-ID: <4E68D7B6.1050705@pearwood.info> lina wrote: > one example: > > def info(object, spacing=10, collapse=1): > """Print methods and docs strings. > > Take modules, class, list, dictionary, or strong.""" > methodList = [e for e in dir(object) if callable(getattr(object, e))] > processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s) > print "\n".join(["%s %s" % > (method.ljust(spacing), > processFunc(str(getattr(object, method).__doc__))) > for method in methodList]) In this example, "collapse" is used as the name of an argument which takes a true/false flag. If collapse is true, runs of whitespace is collapsed into a single space: "hello world" => "hello world" The above function would be much easier to understand if it was written like this: def info(object, spacing=10, collapse=1): """Print methods and docs strings. Take modules, class, list, dictionary, or string. """ method_names = [] doc_strings = [] for name in dir(object): attribute = getattr(object, name) if callable(attribute): method_names.append(name.ljust(spacing)) doc_strings.append(str(attribute.__doc__)) if collapse: doc_strings = [" ".join(doc.split()) for doc in doc_strings] parts = ["%s %s" % (n, d) for n,d in zip(method_names, doc_strings)] print "\n".join(parts) Much longer, but easier to follow for a beginner. -- Steven From lina.lastname at gmail.com Thu Sep 8 16:59:12 2011 From: lina.lastname at gmail.com (lina) Date: Thu, 8 Sep 2011 22:59:12 +0800 Subject: [Tutor] a quick Q: what does the "collapse" mean? In-Reply-To: <CAPM-O+xo2x19TzhHoDO_8rsVB-aTswX3e2ABPsvKZSTzskCRgA@mail.gmail.com> References: <CAG9cJmkunPcvCE5quzpoSVdjA1TEw=cTD_oM14znbLC58Br1hQ@mail.gmail.com> <j4ahlq$p0p$3@dough.gmane.org> <CAG9cJmk98VD0G_YOBm7AfxVTKvM-exKyy8Qd2AunQ3suqbW_aA@mail.gmail.com> <CAGzCZ0rzDMZ0jZaYkCMVEekN98pkUc56WxAs4o3_a_5s5exXtw@mail.gmail.com> <CAPM-O+wW=L5235UYLhgf82LPRhx-87BEXGSL-eDoVwzKJCD-kg@mail.gmail.com> <CAPM-O+xo2x19TzhHoDO_8rsVB-aTswX3e2ABPsvKZSTzskCRgA@mail.gmail.com> Message-ID: <CAG9cJmmQU6mpZ_yZh9LufWWrNgaDXyWgyi=oHJ3WtR+Grhv_zA@mail.gmail.com> <... ... > >> collapse is a function that Mark must have described earlier in the >> chapter you are working on.? Are you using the online version? which chapter >> http://diveintopython.org/power_of_introspection/optional_arguments.html >> I spoke too soon.? collapse is a boolean variable that you set if you want >> to have the code in the lamda function collapse the text.? If it is False collapse the text means? destory the text? make it collapse? Thanks, >> then the statement returns false instead of whatever is going on in the >> Lambda > > > -- > Joel Goldstick > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Best Regards, lina From steve at pearwood.info Thu Sep 8 17:03:33 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 09 Sep 2011 01:03:33 +1000 Subject: [Tutor] a quick Q: what does the "collapse" mean? In-Reply-To: <CAG9cJmmQU6mpZ_yZh9LufWWrNgaDXyWgyi=oHJ3WtR+Grhv_zA@mail.gmail.com> References: <CAG9cJmkunPcvCE5quzpoSVdjA1TEw=cTD_oM14znbLC58Br1hQ@mail.gmail.com> <j4ahlq$p0p$3@dough.gmane.org> <CAG9cJmk98VD0G_YOBm7AfxVTKvM-exKyy8Qd2AunQ3suqbW_aA@mail.gmail.com> <CAGzCZ0rzDMZ0jZaYkCMVEekN98pkUc56WxAs4o3_a_5s5exXtw@mail.gmail.com> <CAPM-O+wW=L5235UYLhgf82LPRhx-87BEXGSL-eDoVwzKJCD-kg@mail.gmail.com> <CAPM-O+xo2x19TzhHoDO_8rsVB-aTswX3e2ABPsvKZSTzskCRgA@mail.gmail.com> <CAG9cJmmQU6mpZ_yZh9LufWWrNgaDXyWgyi=oHJ3WtR+Grhv_zA@mail.gmail.com> Message-ID: <4E68D945.9010701@pearwood.info> lina wrote: > collapse the text means? destory the text? make it collapse? Collapse runs of spaces into a single space. -- Steven From lina.lastname at gmail.com Thu Sep 8 17:08:31 2011 From: lina.lastname at gmail.com (lina) Date: Thu, 8 Sep 2011 23:08:31 +0800 Subject: [Tutor] a quick Q: what does the "collapse" mean? In-Reply-To: <4E68D945.9010701@pearwood.info> References: <CAG9cJmkunPcvCE5quzpoSVdjA1TEw=cTD_oM14znbLC58Br1hQ@mail.gmail.com> <j4ahlq$p0p$3@dough.gmane.org> <CAG9cJmk98VD0G_YOBm7AfxVTKvM-exKyy8Qd2AunQ3suqbW_aA@mail.gmail.com> <CAGzCZ0rzDMZ0jZaYkCMVEekN98pkUc56WxAs4o3_a_5s5exXtw@mail.gmail.com> <CAPM-O+wW=L5235UYLhgf82LPRhx-87BEXGSL-eDoVwzKJCD-kg@mail.gmail.com> <CAPM-O+xo2x19TzhHoDO_8rsVB-aTswX3e2ABPsvKZSTzskCRgA@mail.gmail.com> <CAG9cJmmQU6mpZ_yZh9LufWWrNgaDXyWgyi=oHJ3WtR+Grhv_zA@mail.gmail.com> <4E68D945.9010701@pearwood.info> Message-ID: <CAG9cJm=w8V_b=1XboebJZaat9R6LmJ5O2ibBqfNz9enbeYXJZw@mail.gmail.com> On Thu, Sep 8, 2011 at 11:03 PM, Steven D'Aprano <steve at pearwood.info> wrote: > lina wrote: > >> collapse the text means? destory the text? make it collapse? > > Collapse runs of spaces into a single space. That's what I want, thanks. ^_^ > > > > -- > Steven > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Best Regards, lina From marc.tompkins at gmail.com Thu Sep 8 17:17:05 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Thu, 8 Sep 2011 08:17:05 -0700 Subject: [Tutor] a quick Q: what does the "collapse" mean? In-Reply-To: <CAG9cJm=w8V_b=1XboebJZaat9R6LmJ5O2ibBqfNz9enbeYXJZw@mail.gmail.com> References: <CAG9cJmkunPcvCE5quzpoSVdjA1TEw=cTD_oM14znbLC58Br1hQ@mail.gmail.com> <j4ahlq$p0p$3@dough.gmane.org> <CAG9cJmk98VD0G_YOBm7AfxVTKvM-exKyy8Qd2AunQ3suqbW_aA@mail.gmail.com> <CAGzCZ0rzDMZ0jZaYkCMVEekN98pkUc56WxAs4o3_a_5s5exXtw@mail.gmail.com> <CAPM-O+wW=L5235UYLhgf82LPRhx-87BEXGSL-eDoVwzKJCD-kg@mail.gmail.com> <CAPM-O+xo2x19TzhHoDO_8rsVB-aTswX3e2ABPsvKZSTzskCRgA@mail.gmail.com> <CAG9cJmmQU6mpZ_yZh9LufWWrNgaDXyWgyi=oHJ3WtR+Grhv_zA@mail.gmail.com> <4E68D945.9010701@pearwood.info> <CAG9cJm=w8V_b=1XboebJZaat9R6LmJ5O2ibBqfNz9enbeYXJZw@mail.gmail.com> Message-ID: <CAKK8jXZBV9ffo0jz4cJ1nu=sKr1+au3Y4ceOcDZP2uJj05weBw@mail.gmail.com> On Thu, Sep 8, 2011 at 8:08 AM, lina <lina.lastname at gmail.com> wrote: > On Thu, Sep 8, 2011 at 11:03 PM, Steven D'Aprano <steve at pearwood.info> > wrote: > > lina wrote: > > > >> collapse the text means? destory the text? make it collapse? > > > > Collapse runs of spaces into a single space. > > That's what I want, thanks. ^_^ > Be aware that that meaning of "collapse" is not a standard Python term - it's just the word that the author chose to describe this function. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110908/bed297b2/attachment.html> From lina.lastname at gmail.com Thu Sep 8 17:35:49 2011 From: lina.lastname at gmail.com (lina) Date: Thu, 8 Sep 2011 23:35:49 +0800 Subject: [Tutor] a quick Q: what does the "collapse" mean? In-Reply-To: <CAKK8jXZBV9ffo0jz4cJ1nu=sKr1+au3Y4ceOcDZP2uJj05weBw@mail.gmail.com> References: <CAG9cJmkunPcvCE5quzpoSVdjA1TEw=cTD_oM14znbLC58Br1hQ@mail.gmail.com> <j4ahlq$p0p$3@dough.gmane.org> <CAG9cJmk98VD0G_YOBm7AfxVTKvM-exKyy8Qd2AunQ3suqbW_aA@mail.gmail.com> <CAGzCZ0rzDMZ0jZaYkCMVEekN98pkUc56WxAs4o3_a_5s5exXtw@mail.gmail.com> <CAPM-O+wW=L5235UYLhgf82LPRhx-87BEXGSL-eDoVwzKJCD-kg@mail.gmail.com> <CAPM-O+xo2x19TzhHoDO_8rsVB-aTswX3e2ABPsvKZSTzskCRgA@mail.gmail.com> <CAG9cJmmQU6mpZ_yZh9LufWWrNgaDXyWgyi=oHJ3WtR+Grhv_zA@mail.gmail.com> <4E68D945.9010701@pearwood.info> <CAG9cJm=w8V_b=1XboebJZaat9R6LmJ5O2ibBqfNz9enbeYXJZw@mail.gmail.com> <CAKK8jXZBV9ffo0jz4cJ1nu=sKr1+au3Y4ceOcDZP2uJj05weBw@mail.gmail.com> Message-ID: <CAG9cJm=Awm2_T8ET6uqrEKZUSKngc+7ioiX_AgbyXDjVAfvodQ@mail.gmail.com> On Thu, Sep 8, 2011 at 11:17 PM, Marc Tompkins <marc.tompkins at gmail.com> wrote: > On Thu, Sep 8, 2011 at 8:08 AM, lina <lina.lastname at gmail.com> wrote: >> >> On Thu, Sep 8, 2011 at 11:03 PM, Steven D'Aprano <steve at pearwood.info> >> wrote: >> > lina wrote: >> > >> >> collapse the text means? destory the text? make it collapse? >> > >> > Collapse runs of spaces into a single space. >> >> That's what I want, thanks. ?^_^ > > Be aware that that meaning of "collapse" is not a standard Python term - > it's just the word that the author chose to describe this function. Thanks for reminding. Sometimes it's not so easy to realize which part I should focus to understand well. > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Best Regards, lina From __peter__ at web.de Thu Sep 8 17:51:58 2011 From: __peter__ at web.de (Peter Otten) Date: Thu, 08 Sep 2011 17:51:58 +0200 Subject: [Tutor] a quick Q: what does the "collapse" mean? References: <CAG9cJmkunPcvCE5quzpoSVdjA1TEw=cTD_oM14znbLC58Br1hQ@mail.gmail.com> <j4ahlq$p0p$3@dough.gmane.org> <CAG9cJmk98VD0G_YOBm7AfxVTKvM-exKyy8Qd2AunQ3suqbW_aA@mail.gmail.com> <4E68D7B6.1050705@pearwood.info> Message-ID: <j4aoaq$hoj$1@dough.gmane.org> Steven D'Aprano wrote: > lina wrote: > >> one example: >> >> def info(object, spacing=10, collapse=1): >> """Print methods and docs strings. >> >> Take modules, class, list, dictionary, or strong.""" >> methodList = [e for e in dir(object) if callable(getattr(object, e))] >> processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda >> s: s) print "\n".join(["%s %s" % >> (method.ljust(spacing), >> processFunc(str(getattr(object, method).__doc__))) >> for method in methodList]) > > > In this example, "collapse" is used as the name of an argument which > takes a true/false flag. If collapse is true, runs of whitespace is > collapsed into a single space: > > "hello world" => "hello world" > > The above function would be much easier to understand if it was written > like this: > > def info(object, spacing=10, collapse=1): > """Print methods and docs strings. > > Take modules, class, list, dictionary, or string. > """ > method_names = [] > doc_strings = [] > for name in dir(object): > attribute = getattr(object, name) > if callable(attribute): > method_names.append(name.ljust(spacing)) > doc_strings.append(str(attribute.__doc__)) > if collapse: > doc_strings = [" ".join(doc.split()) for doc in doc_strings] > parts = ["%s %s" % (n, d) for n,d in zip(method_names, doc_strings)] > print "\n".join(parts) > > > > Much longer, but easier to follow for a beginner. Or even def info(object, spacing=10, collapse=True): for name in dir(object): attribute = getattr(object, name) if callable(attribute): doc = str(attribute.__doc__) if collapse: doc = " ".join(doc.split()) print name.ljust(spacing), doc From eire1130 at gmail.com Thu Sep 8 18:17:25 2011 From: eire1130 at gmail.com (James Reynolds) Date: Thu, 8 Sep 2011 12:17:25 -0400 Subject: [Tutor] need advice about a dictionary ({}) In-Reply-To: <j4ahsh$tso$1@dough.gmane.org> References: <CALMxxxm2fA_Yo4bQMRHznYXBFZwD03ze-mXo1WeY7VkfM+1J9w@mail.gmail.com> <j4ahsh$tso$1@dough.gmane.org> Message-ID: <CAE0jAbrkEq_zFnfAPpH=DhPKuxEjgqJgewYSveweEJ1JF5YSFA@mail.gmail.com> On Thu, Sep 8, 2011 at 10:03 AM, Alan Gauld <alan.gauld at btinternet.com>wrote: > On 08/09/11 11:58, Richard D. Moores wrote: > >> I've succeeded in writing a dictionary ({}) that I can use as a small >> personal phone book. The dictionary (very shortened and simplified) >> looks like this in the script; >> >> p = {} >> >> p['bp1'] = 'xxx' >> p['bp2'] = 'ooo' >> p['ch'] = 'zzz' >> p['me'] = 'aaa' >> p['mg'] = 'vvv' >> p['pu1'] = 'bbb' >> p['pu2'] = 'ccc' >> p['pw'] = 'kkk' >> >> > You could have done that in one line if you preferred: > > > p = { > 'bp1':'xxx', > 'bp2':'ooo' > etc/... > 'pw':'kkk' > > } > > > But I'd like to put the lines of the dictionary in a text file so that >> I can add key/value items to it by writing to it with another script. >> > > Consider using a shelve (See the shelve module) > It is basically a file that you can treat as a dictionary... > > Try: > > >>> import shelve > >>> help(shelve) > > For examples and info. > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor> > Another option would be for you to use XML and base it off of a schema. There's a really nifty tool called generate DS (just google it) that will turn any valid schema into a python module. I pasted an example schema that you might use here: http://pastebin.com/AVgVGpgu Once you install generateds, just cd to where it is installed and type: python generateds.py -o pn.py PhoneNumber.xsd This assumes you named the above schema as PhoneNumber.xsd That will create a file called pn.py. For some reason it generated a bad line on line 452, which I just commented out. I then made a script in just a few lines to make a phonebook: http://pastebin.com/h4JB0MkZ This outputs XML that looks like this: <PhoneBook> > <Listing> > <PersonsName>aaa</PersonsName> > <Number Type="Mobile"> > <Number>1231231234</Number> > </Number> > </Listing> > <Listing> > <PersonsName>bbb</PersonsName> > <Number Type="Work"> > <Number>1231231234</Number> > </Number> > <Number Type="Home"> > <Number>6789231234</Number> > </Number> > </Listing> > <Listing> > <PersonsName>ccc</PersonsName> > <Number Type="Fax"> > <Number>1231231234</Number> > </Number> > </Listing> > <Listing> > <PersonsName>ddd</PersonsName> > <Number Type="Home"> > <Number>1231231234</Number> > </Number> > </Listing> > </PhoneBook> The advantage is, you can immediately grab the generated xml and create python instances using the build() method for further editing. You would of course need to create a schema that fits your needs. Mine was just a quick and dirty example of what you could do. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110908/074d1078/attachment.html> From thisisonlyatest at gmx.com Fri Sep 9 04:31:40 2011 From: thisisonlyatest at gmx.com (brandon w) Date: Thu, 08 Sep 2011 22:31:40 -0400 Subject: [Tutor] Tkinter Entry field text Message-ID: <4E697A8C.1030106@gmx.com> How do you display text in a Entry field and have it disappear when a person clicks in it? This is what I have so far: from Tkinter import * root = Tk() root.title("Password Changer") root.geometry("300x300+600+250") label1 = Label(root, text="Enter you password: ") label1.grid(sticky=W, row=0, column=0) enter_data1 = Entry(root, bg = "pale green") enter_data1.grid(row=0, column=1) enter_data1.insert(0, "password") root.mainloop() To get text into this box the person must first delete what is already in there. Python 2.6.6 From ryan.strunk at gmail.com Fri Sep 9 04:39:47 2011 From: ryan.strunk at gmail.com (Ryan Strunk) Date: Thu, 8 Sep 2011 21:39:47 -0500 Subject: [Tutor] Flat is better than Nested Message-ID: <001f01cc6e99$be38b1e0$3aaa15a0$@gmail.com> Hello everyone, I am still learning to program by writing this boxing game. I'm running into a problem with how to organize data. My current setup looks something like this: """This feels incredibly disgusting to me.""" self.behaviors = { 'offensive_combos': { 'combo1': { 1: { #time in seconds 'punch': { 'speed': 2, 'strength': 4, 'side': 'left'} } 1.5: { #time in seconds 'punch': { 'speed': 4, 'strength': 8, 'side': 'right'} } } } } By the time I write this all into a file, the end user will never even know this crazy hierarchy exists, but I will, and I don't like it. Do I just need to get over it and realize that sometimes nested is necessary, or is there a better way I might consider? Thanks for any help you can provide. Best, Ryan From steve at pearwood.info Fri Sep 9 06:28:46 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 09 Sep 2011 14:28:46 +1000 Subject: [Tutor] Flat is better than Nested In-Reply-To: <001f01cc6e99$be38b1e0$3aaa15a0$@gmail.com> References: <001f01cc6e99$be38b1e0$3aaa15a0$@gmail.com> Message-ID: <4E6995FE.1010009@pearwood.info> Ryan Strunk wrote: > Hello everyone, > I am still learning to program by writing this boxing game. I'm running into > a problem with how to organize data. My current setup looks something like > this: > """This feels incredibly disgusting to me.""" You might find it a little less disgusting with the application of some helper classes and a slightly different data format. Combos probably should be treated as a sequence of moves. For simplicity, I'm going to assume each move takes the same time, and once a combo is entered, the opponent can't interrupt it. You may want to make it more complicated/realistic. The hard part is deciding what fields you need. Here's my guess: class Move: def __init__(self, speed, strength, side, purpose, kind, foul=False): self.speed = speed self.strength = strength self.side = side self.purpose = purpose self.kind = kind self.foul = foul CENTRE = NEUTRAL = '' LEFT, RIGHT = 'left right'.split() ATTACK, DEFENSE = 'attack defense'.split() right_cross = Move(2, 3, RIGHT, ATTACK, 'punch') left_lead = Move(3, 4, LEFT, ATTACK, 'punch') left_jab = Move(1, 1, LEFT, ATTACK, 'punch') headbutt = Move(1, 3, CENTRE, ATTACK, 'headbutt', True) step_in = Move(2, 0, NEUTRAL, NEUTRAL, 'footwork') weave = Move(1, 0, NEUTRAL, DEFENSE, 'footwork') rabbit_punch = Move(1, 2, CENTRE, ATTACK, 'punch', True) class Combo: def __init__(self, *moves): self.moves = moves old_one_two = Combo(left_lead, right_cross) liverpool_kiss = Combo(step_in, headbutt) combos = { 1: old_one_two, 2: liverpool_kiss, 3: Combo(weave, weave, step_in, rabbit_punch), 4: Combo(left_jab, left_jab, left_jab, step_in, uppercut), } Does that help? -- Steven From quasipedia at gmail.com Fri Sep 9 09:08:23 2011 From: quasipedia at gmail.com (Mac Ryan) Date: Fri, 9 Sep 2011 09:08:23 +0200 Subject: [Tutor] Flat is better than Nested In-Reply-To: <001f01cc6e99$be38b1e0$3aaa15a0$@gmail.com> References: <001f01cc6e99$be38b1e0$3aaa15a0$@gmail.com> Message-ID: <20110909090823.5ebb7a16@jabbar> On Thu, 8 Sep 2011 21:39:47 -0500 "Ryan Strunk" <ryan.strunk at gmail.com> wrote: > By the time I write this all into a file, the end user will never > even know this crazy hierarchy exists, but I will, and I don't like > it. Do I just need to get over it and realize that sometimes nested > is necessary, or is there a better way I might consider? There are two different problem you should consider here. The first is the MODEL STRUCTURE of your player. A model is a representation of something, so you really can't change the model structure that much from reality, as what you want is truly the opposite: you want to have the model as close as possible to the "something" you are representing. The other element to consider is the way you MANIPULATE your model, and this is the level at which you can operate to make your life easier. An example might clarify: suppose you are writing a very detailed simulation of the universe, and in it you have to model a neutron in your right big toe: your model could be something huge in terms of nested levels: Universe --> Milky way --> Aplha quadrant --> Solar system --> Planet Earth --> Continent --> Country --> County --> City --> District --> Building --> Floor --> Flat --> Room --> Person --> Limb --> Toe --> Cell --> Molecule --> Atom --> Nucleus --> Neutron. Now, if your simulation needs to know about stellar systems, continents, and all the rest, you really WANT to maintain all the levels of the hierarchy, because putting neutrons "flat" together with galaxies would make truly hard to write sane code. What you have to ask yourself is how you are going to manipulate your data. For example: when you are considering your neutron collisions with nearby subatomic particles do you really need to know about what galaxy your neutron is in? Probably not: all you need to know is about the nucleus of your atom. And when you are calculating the time a planet takes to go around it's star, do you really need to know about people living on it? Again: probably not. The trick for you would be to break down your hierarchy in sensible chunks, attaching to each bit of it the parts of code that are relevant at that resolution. So you could have a class "Nucleus", that knows about its parent molecule and its children particles and have methods like "get_atomic_number()", "decay()" or "bond_with()". And another class called "StellarSystem" knowing about its galaxy quadrant, its star(s) and its planet(s), having methods like "calculate_revolution()", "collapse()", etc... This is really what OOP is all about: you creating semi-independent objects which include only the information and methods needed at the level you are using them. Incidentally this won't only make things EASIER, it will also make them more FLEXIBLE/EASY-TO-MAINTAIN. Still working with the universe example: say that at some point (after you already wrote the code for planet Earth) you realise that other planets indeed are not organised in countries/counties/cities... If whenever you referred to an element in your simulation you included its entire hierarchy, you will be in trouble: you will have to modify your code everywhere you referred to something smaller than a planet. If you contrarily broke down your hierarchy and discover that on Alpha Prime they don't have administrative regions but just cities, all you will have to to is creating a new sister class "PlanetNoBorders" for the one ("PlanetWithRegions") that you used for the Earth, then you will be able to attach to it instantiations of the same City() class that you already used for planet Earth. In OOP this is called "programming to an interface", meaning that your code should ignore the real STRUCTURE of your data (the MODEL) and contrarily only know on how to MANIPULATE that data. Still using the universe example: if you need to access the list of cities on planets, you should make sure a "list_cities()" method is available both in "PlanetOriginal()" and "PlanetNoAdminBorders()" classes, and that they return data in the same format. You can then safely ignore if that specifc planet has or doesn't have countries on it. HTH, /mac From 132zed at gmail.com Fri Sep 9 12:10:59 2011 From: 132zed at gmail.com (Stu Rocksan) Date: Fri, 9 Sep 2011 05:10:59 -0500 Subject: [Tutor] _init_() arguments Message-ID: <CAPOgpjAto9rtdBCBps+NAHNiYoz95zG3vLsaDcBpe+b+itCM3A@mail.gmail.com> I have a very basic question that I am sure has a simple answer. I would be very appreciative of anyone that would set me straight. Python 2.7.2 I am simply trying to pass arguments. Based on the documentation that I've read so far _init_() is called upon instance creation and the arguments are those passed to the class constructor expression. That all makes sense to me but the problem is when I try to actually pass the argument. I get an TypeError that states "This constructor takes no arguments." Even using code direct from the tutorials included in the documentation gives me the same error. I doubt that there would be bad code coming direct from the official website...right? So the problem must be me. Example: class Complex: def _init_(self, realpart, imagpart) self.r = realpart self.i = imagpart x = Complex(3.0, -4.5) x.r, x.i # theoretical output (3.0, -4.5) This is taken direct from the tutorial included in the documentation dated September 8, 2011. If you try to run this you will get a TypeError: this constructor takes no arguments. It even says in the explanation before this code: Of course, the __init__() method may have arguments for greater flexibility. In that case, arguments given to the class instantiation operator are passed on to __init__(). I've tried similar code from other beginner Python books and I get the exact same result. I am sure that I am missing something simple. Thanks in advance From cwitts at compuscan.co.za Fri Sep 9 12:26:30 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Fri, 09 Sep 2011 12:26:30 +0200 Subject: [Tutor] _init_() arguments In-Reply-To: <CAPOgpjAto9rtdBCBps+NAHNiYoz95zG3vLsaDcBpe+b+itCM3A@mail.gmail.com> References: <CAPOgpjAto9rtdBCBps+NAHNiYoz95zG3vLsaDcBpe+b+itCM3A@mail.gmail.com> Message-ID: <4E69E9D6.7050509@compuscan.co.za> On 2011/09/09 12:10 PM, Stu Rocksan wrote: > I have a very basic question that I am sure has a simple answer. I > would be very appreciative of anyone that would set me straight. > > Python 2.7.2 > > I am simply trying to pass arguments. Based on the documentation that > I've read so far _init_() is called upon instance creation and the > arguments are those passed to the class constructor expression. That > all makes sense to me but the problem is when I try to actually pass > the argument. I get an TypeError that states "This constructor takes > no arguments." > > Even using code direct from the tutorials included in the > documentation gives me the same error. I doubt that there would be > bad code coming direct from the official website...right? So the > problem must be me. > > Example: > > class Complex: > def _init_(self, realpart, imagpart) > self.r = realpart > self.i = imagpart > > x = Complex(3.0, -4.5) > x.r, x.i > # theoretical output > (3.0, -4.5) > > This is taken direct from the tutorial included in the documentation > dated September 8, 2011. If you try to run this you will get a > TypeError: this constructor takes no arguments. > > It even says in the explanation before this code: > Of course, the __init__() method may have arguments for greater > flexibility. In that case, arguments given to the class instantiation > operator are passed on to __init__(). > > I've tried similar code from other beginner Python books and I get the > exact same result. > > I am sure that I am missing something simple. Thanks in advance > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > __init__() has 2 underscores pre- and post-fixed. Your example will break because of that, and also you're missing a colon at the end of your `def` line. Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> class Complex: ... def __init__(self, realpart, imagpart): ... self.r = realpart ... self.i = imagpart ... >>> x = Complex(3.0, -4.5) >>> x.r, x.i (3.0, -4.5) >>> class Complex2: ... def _init_(self, realpart, imagpart): ... self.r = realpart ... self.i = imagpart ... >>> x= Complex2(3.0, -4.5) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: this constructor takes no arguments -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110909/5078a449/attachment.html> From kitty.a1000 at gmail.com Fri Sep 9 12:44:10 2011 From: kitty.a1000 at gmail.com (kitty) Date: Fri, 9 Sep 2011 11:44:10 +0100 Subject: [Tutor] Get a single random sample Message-ID: <CAO44UhXpmFACdXT3iTmqVfVWtuBMYL=iqG537pfSia7QJEZNvQ@mail.gmail.com> Hi, I'm new to python and I have read through the tutorial on: http://docs.python.org/tutorial/index.html which was really good, but I have been an R user for 7 years and and am finding it difficult to do even basic things in python, for example I want to import my data (a tab-delimited .txt file) so that I can index and select a random sample of one column based on another column. my data has 2 columns named 'area' and 'change.dens'. In R I would just data<-read.table("FILE PATH\\Road.density.municipio.all.txt", header=T) #header =T gives colums their headings so that I can call each individually names(data) attach(data) Then to Index I would simply: subset<-change.dens[area<2000&area>700] # so return change.dens values that have corresponding 'area's of between 700 and 2000 then to randomly sample a value from that I just need to random<-sample(subset,1) My question is how do I get python to do this??? Sorry I know it is very basic but I just cant seem to get going, Thank you K. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110909/d0a20884/attachment.html> From steve at pearwood.info Fri Sep 9 14:19:35 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 09 Sep 2011 22:19:35 +1000 Subject: [Tutor] _init_() arguments In-Reply-To: <CAPOgpjAto9rtdBCBps+NAHNiYoz95zG3vLsaDcBpe+b+itCM3A@mail.gmail.com> References: <CAPOgpjAto9rtdBCBps+NAHNiYoz95zG3vLsaDcBpe+b+itCM3A@mail.gmail.com> Message-ID: <4E6A0457.4060805@pearwood.info> Stu Rocksan wrote: > class Complex: > def _init_(self, realpart, imagpart) Special methods in Python have TWO underscores at the beginning and end. You need to call it __init__ rather than _init_. Also, are you aware that Python already includes a built-in complex type? >>> complex(1, 2) (1+2j) -- Steven From d at davea.name Fri Sep 9 14:24:01 2011 From: d at davea.name (Dave Angel) Date: Fri, 09 Sep 2011 08:24:01 -0400 Subject: [Tutor] Get a single random sample In-Reply-To: <CAO44UhXpmFACdXT3iTmqVfVWtuBMYL=iqG537pfSia7QJEZNvQ@mail.gmail.com> References: <CAO44UhXpmFACdXT3iTmqVfVWtuBMYL=iqG537pfSia7QJEZNvQ@mail.gmail.com> Message-ID: <4E6A0561.2090600@davea.name> On 09/09/2011 06:44 AM, kitty wrote: > Hi, > > I'm new to python and I have read through the tutorial on: > http://docs.python.org/tutorial/index.html > which was really good, but I have been an R user for 7 years and and am > finding it difficult to do even basic things in python, for example I want > to import my data (a tab-delimited .txt file) so that I can index and select > a random sample of one column based on another column. my data has > 2 columns named 'area' and 'change.dens'. > > In R I would just > > data<-read.table("FILE PATH\\Road.density.municipio.all.txt", header=T) > #header =T gives colums their headings so that I can call each individually > names(data) > attach(data) > > Then to Index I would simply: > subset<-change.dens[area<2000&area>700] # so return change.dens values that > have corresponding 'area's of between 700 and 2000 > > then to randomly sample a value from that I just need to > random<-sample(subset,1) > > > My question is how do I get python to do this??? > > Sorry I know it is very basic but I just cant seem to get going, > > Thank you > K. No, it's not basic. If that R fragment is self-contained, apparently R makes lots of assumptions about its enviroment. Python can handle all of this, but not so succinctly and not without libraries (modules). In particular, your problem would be addressed with the csv module and the random one. The following (untested) code might get you started. import csv, sys, os infilename = "path to file/Road.density.municipio.all.txt" infile = open(infilename, "r") incsv = csv.DictReader(infile, delimiter="\t") # \t is the tab character print incsv.fieldnames for index, item in enumerate(incsv): do-something-with-item item will be a dict representing one line of the file, each time through the loop. You can choose some of those with an if statement, and build a list of the dicts that are useful. You can combine some of these steps using things like list comprehensions, but it's easier to take it a step at a time and see what you've got. -- DaveA From steve at pearwood.info Fri Sep 9 14:44:43 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 09 Sep 2011 22:44:43 +1000 Subject: [Tutor] Get a single random sample In-Reply-To: <CAO44UhXpmFACdXT3iTmqVfVWtuBMYL=iqG537pfSia7QJEZNvQ@mail.gmail.com> References: <CAO44UhXpmFACdXT3iTmqVfVWtuBMYL=iqG537pfSia7QJEZNvQ@mail.gmail.com> Message-ID: <4E6A0A3B.6080203@pearwood.info> kitty wrote: > I'm new to python and I have read through the tutorial on: > http://docs.python.org/tutorial/index.html > which was really good, but I have been an R user for 7 years and and am > finding it difficult to do even basic things in python, for example I want > to import my data (a tab-delimited .txt file) so that I can index and select > a random sample of one column based on another column. my data has > 2 columns named 'area' and 'change.dens'. > > In R I would just > > data<-read.table("FILE PATH\\Road.density.municipio.all.txt", header=T) > #header =T gives colums their headings so that I can call each individually > names(data) > attach(data) > > Then to Index I would simply: > subset<-change.dens[area<2000&area>700] # so return change.dens values that > have corresponding 'area's of between 700 and 2000 > > then to randomly sample a value from that I just need to > random<-sample(subset,1) > > > My question is how do I get python to do this??? Good question! This does look like something where R is easier to use than Python, especially with the table() function doing most of the work for you. Here's one way to do it in Python. # Open the file and read two tab-delimited columns. # Note that there is minimal error checking here. f = open('Road.density.municipio.all.txt') data = [] for row in f: if not row.strip(): # Skip blank lines. continue area, dens = row.split('\t') # Split into two columns at tab pair = (float(area), float(dens)) data.append(pair) f.close() # Close the file when done. # Select items with specified areas. subset = [pair for pair in data if 700 < pair[0] < 2000] # Get a single random sample. import random sample = random.choice(subset) # Get ten random samples, sampling with replacement. samples = [random.choice(subset) for i in range(10)] # Get ten random samples, without replacement. copy = subset[:] random.shuffle(copy) samples = copy[:10] -- Steven From __peter__ at web.de Fri Sep 9 14:49:09 2011 From: __peter__ at web.de (Peter Otten) Date: Fri, 09 Sep 2011 14:49:09 +0200 Subject: [Tutor] Get a single random sample References: <CAO44UhXpmFACdXT3iTmqVfVWtuBMYL=iqG537pfSia7QJEZNvQ@mail.gmail.com> Message-ID: <j4d1vs$6rj$1@dough.gmane.org> kitty wrote: > Hi, > > I'm new to python and I have read through the tutorial on: > http://docs.python.org/tutorial/index.html > which was really good, but I have been an R user for 7 years and and am > finding it difficult to do even basic things in python, for example I want > to import my data (a tab-delimited .txt file) so that I can index and > select a random sample of one column based on another column. my data has > 2 columns named 'area' and 'change.dens'. > > In R I would just > > data<-read.table("FILE PATH\\Road.density.municipio.all.txt", header=T) > #header =T gives colums their headings so that I can call each > #individually > names(data) > attach(data) > > Then to Index I would simply: > subset<-change.dens[area<2000&area>700] # so return change.dens values > that have corresponding 'area's of between 700 and 2000 > > then to randomly sample a value from that I just need to > random<-sample(subset,1) > > > My question is how do I get python to do this??? I don't know R, but I believe the following does what you want: import csv import random import sys from collections import namedtuple filename = "FILE PATH\\Road.density.municipio.all.txt" with open(filename, "rb") as f: rows = csv.reader(f, delimiter="\t") headers = next(rows) rowtype = namedtuple("RT", [h.replace(".", "_") for h in headers]) data = [rowtype(*map(float, row)) for row in rows] print data subset = [row for row in data if 700 < row.area < 2000] print random.choice(subset).area As you can see Python with just the standard library requires a lot more legwork than R. You might have a look at scipy/numpy, perhaps they offer functions that simplify your task. Finally, there's also http://rpy.sourceforge.net/ , but I've never tried that. From __peter__ at web.de Fri Sep 9 14:54:03 2011 From: __peter__ at web.de (Peter Otten) Date: Fri, 09 Sep 2011 14:54:03 +0200 Subject: [Tutor] Get a single random sample References: <CAO44UhXpmFACdXT3iTmqVfVWtuBMYL=iqG537pfSia7QJEZNvQ@mail.gmail.com> <4E6A0A3B.6080203@pearwood.info> Message-ID: <j4d290$6rj$2@dough.gmane.org> Steven D'Aprano wrote: > # Get ten random samples, sampling with replacement. > samples = [random.choice(subset) for i in range(10)] That may include subset items more than once. Use the aptly named random.sample(subset, 10) to avoid that. From __peter__ at web.de Fri Sep 9 15:03:02 2011 From: __peter__ at web.de (Peter Otten) Date: Fri, 09 Sep 2011 15:03:02 +0200 Subject: [Tutor] Get a single random sample References: <CAO44UhXpmFACdXT3iTmqVfVWtuBMYL=iqG537pfSia7QJEZNvQ@mail.gmail.com> <4E6A0A3B.6080203@pearwood.info> <j4d290$6rj$2@dough.gmane.org> Message-ID: <j4d2ps$6rj$3@dough.gmane.org> Peter Otten wrote: > Steven D'Aprano wrote: > >> # Get ten random samples, sampling with replacement. I can quote. But not read ;( >> samples = [random.choice(subset) for i in range(10)] Sorry for the noise. From steve at pearwood.info Fri Sep 9 15:06:33 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 09 Sep 2011 23:06:33 +1000 Subject: [Tutor] Get a single random sample In-Reply-To: <j4d290$6rj$2@dough.gmane.org> References: <CAO44UhXpmFACdXT3iTmqVfVWtuBMYL=iqG537pfSia7QJEZNvQ@mail.gmail.com> <4E6A0A3B.6080203@pearwood.info> <j4d290$6rj$2@dough.gmane.org> Message-ID: <4E6A0F59.80500@pearwood.info> Peter Otten wrote: > Steven D'Aprano wrote: > >> # Get ten random samples, sampling with replacement. >> samples = [random.choice(subset) for i in range(10)] > > That may include subset items more than once. Hence the "sampling with replacement" comment. > Use the aptly named > > random.sample(subset, 10) > > to avoid that. Ah, I didn't know that one! Nice. -- Steven From alan.gauld at btinternet.com Fri Sep 9 20:04:04 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 09 Sep 2011 19:04:04 +0100 Subject: [Tutor] Get a single random sample In-Reply-To: <CAO44UhXpmFACdXT3iTmqVfVWtuBMYL=iqG537pfSia7QJEZNvQ@mail.gmail.com> References: <CAO44UhXpmFACdXT3iTmqVfVWtuBMYL=iqG537pfSia7QJEZNvQ@mail.gmail.com> Message-ID: <j4dkam$huf$1@dough.gmane.org> On 09/09/11 11:44, kitty wrote: > ...I have been an R user for 7 years and and am > finding it difficult to do even basic things in python, If you are trying to do the kinds of things that R is good at in Python you will find it involves a lot more work. That's because Python is a general purpose programming language and R is a special purpose one, optimised to its task. You can do most things in Python but it can never compete with a specialised language in that language's area. On the other hand if you try writing networking applications or GUIs in R you will likely find that's harder than using Python. Choosing the right tool for the job is always a choice between a specialist tool or a general purpose one. If you do a specialised job a specialised tool is probably a better choice. > In R I would just > > data<-read.table("FILE PATH\\Road.density.municipio.all.txt", header=T) > names(data) > attach(data) > subset<-change.dens[area<2000&area>700] > random<-sample(subset,1) > > > My question is how do I get python to do this??? > > Sorry I know it is very basic but I just cant seem to get going, And there's the rub, it may be very basic in R but its quite a challenge in Python, you need to get into a lot more detail. But the good news is that there is an interface between Python and R - called RPy - that you can use to get the best of both worlds. Use Python for the general stuff and use RPy for the analytical work... You can get RPy here: http://rpy.sourceforge.net/rpy2.html And there is a simple introduction and comparison of R and Python benefits here: http://www.bytemining.com/2010/10/accessing-r-from-python-using-rpy2/ HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From waynejwerner at gmail.com Sat Sep 10 16:16:20 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Sat, 10 Sep 2011 09:16:20 -0500 Subject: [Tutor] Tkinter Entry field text In-Reply-To: <4E697A8C.1030106@gmx.com> References: <4E697A8C.1030106@gmx.com> Message-ID: <CAPM86Nf0-qkNMbg4U7WUC3sBX74UCj_bTjTLqPZASQXNMbEEag@mail.gmail.com> On Thu, Sep 8, 2011 at 9:31 PM, brandon w <thisisonlyatest at gmx.com> wrote: > How do you display text in a Entry field and have it disappear when a > person clicks in it? > <snip some code> To get text into this box the person must first delete > what is already in there. > > Python 2.6.6 > Think about the process. You're already mostly there: you're displaying data already, and you know what you want to do. You'll want to take a look at binding events, and if you Google for "tkinter events" (http://www.google.com/search?q=tkinter+events) then your first result takes you here: http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm To point you in the right direction, you want to take a look at the <FocusIn> event. If you're not familiar with what a callback is, you should also read this page: http://effbot.org/zone/tkinter-callbacks.htm If you still have problems after that, show us what else you've tried and we'll be happy to give you more pointers in the right direction. Of course, while this answers your questions, I would be remiss if I didn't suggest a few more things about your program in general. > label1 = Label(root, text="Enter you password: ") label1 isn't a terribly descriptive name. That's fine if you don't intend to actually do anything with the label. However, you can make this even more explicit by chaining the commands together. Since Label() returns a label, you can add a dot to the end and treat it just like you would the variable: Label(root, text="Enter you password: ").grid(sticky=W, row=0, column=0) That will create your label and stick it in the grid in one step, and makes it clear to anyone reading your code (including yourself down the road!) that you don't care to do anything with that label. Next: > enter_data1 = Entry(root, bg = "pale green") enter_data1 also suffers from the same naming problem. It doesn't describe what the variable is or does very well, aside from entering data. You could change it to something like "password_entry" - which tells anyone reading your program that the variable should contain something that lets you do some password entry. Just naming it password would also be better than enter_data1. One other issue that you should consider - with the options you have set, anyone could see what you typed in as your password. If you're just using this as a testing program to play around with, that's probably OK, but what's even better is to change what's shown in the box. You can do this by setting the "show" option, either in the constructor or somewhere later: from Tkinter import * root = Tk() entry = Entry(root) entry.pack() entry.insert(0, "My Cool Password") entry.config(show="*") root.mainloop() The nice thing about the config() method is that it allows you to change config attributes later. You can combine this knowledge with some of what I mentioned earlier to show 'password' until they navigate to the field, and then just show asterisks. For bonus points, if they leave the password field without typing a password, can you make it show 'password' again? HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110910/d41c801b/attachment.html> From rdmoores at gmail.com Sat Sep 10 20:08:18 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Sat, 10 Sep 2011 11:08:18 -0700 Subject: [Tutor] need advice about a dictionary ({}) In-Reply-To: <CALMxxxmYnzRxSbrgY3hdu-fkpAHGzEgpYTGDjsNPN=c4XqEZyw@mail.gmail.com> References: <CALMxxxm2fA_Yo4bQMRHznYXBFZwD03ze-mXo1WeY7VkfM+1J9w@mail.gmail.com> <j4a9p1$a4$1@dough.gmane.org> <CALMxxxmYnzRxSbrgY3hdu-fkpAHGzEgpYTGDjsNPN=c4XqEZyw@mail.gmail.com> Message-ID: <CALMxxxmfW=vX8Of551_vpNT9HVYjg7x=CSj3EDpJ=D85NjxPnw@mail.gmail.com> So I've done quite a bit more work. With phone_book.py the user can not only access phone numbers by the person's initials, but can add items to the data file. I've also solved the problem of adding a person who's initials have already been used in a key. I've pasted phone_book_for_pasting.py at <http://pastebin.com/2wm4Vf1P>. I'd appreciate any comments, instructive criticism, etc. Some have suggested using the shelve module. I looked at it but couldn't see in detail how to use it. If someone could write a short demo script, or send me to one that pretty much does what my phone_book.py does, that would be terrific. Dick Moores From walksloud at gmail.com Sat Sep 10 21:39:15 2011 From: walksloud at gmail.com (Andre' Walker-Loud) Date: Sat, 10 Sep 2011 12:39:15 -0700 Subject: [Tutor] databases Message-ID: <EAEC297C-9B97-4AB6-AB5C-64ADEC022F77@gmail.com> Hi All, I am completely new to databases as well as using python to access/create databases. I started googling about it and found so much info, I wasn't sure where to begin to answer my first question. So I thought I would query this group by asking a question I am sure has been asked before - but you all are so friendly, I thought I would give it a try. I have databases (many of them) which I want to manipulate, averaging data, merging databases, etc. Do I need to install separate modules to access the databases? Do I need to know the specific style the databases were created in to open manipulate them with python (2.7)? I ask this because with xml files, I was able to just use from xml.dom import minidom and then by trial and error in an interactive session, I could figure out how to walk through the xml file to find what I wanted. I am wondering if I can do something similar with a database, or if there are more pre-defined formats. I do not actually know what format my databases are in (someone else wrote the c-code to create them). While waiting for suggestions, I have started to read Alan Gauld's tutorial on the subject http://www.alan-g.me.uk/tutor/index.htm Thanks, Andre From jacktradespublic at gmail.com Sat Sep 10 21:42:04 2011 From: jacktradespublic at gmail.com (Jack Trades) Date: Sat, 10 Sep 2011 14:42:04 -0500 Subject: [Tutor] need advice about a dictionary ({}) In-Reply-To: <CALMxxxmfW=vX8Of551_vpNT9HVYjg7x=CSj3EDpJ=D85NjxPnw@mail.gmail.com> References: <CALMxxxm2fA_Yo4bQMRHznYXBFZwD03ze-mXo1WeY7VkfM+1J9w@mail.gmail.com> <j4a9p1$a4$1@dough.gmane.org> <CALMxxxmYnzRxSbrgY3hdu-fkpAHGzEgpYTGDjsNPN=c4XqEZyw@mail.gmail.com> <CALMxxxmfW=vX8Of551_vpNT9HVYjg7x=CSj3EDpJ=D85NjxPnw@mail.gmail.com> Message-ID: <CAG5udOgde82mACHSj4NvHJOkjnZ5vveXgoP=-7Nvr+NU6fAcpw@mail.gmail.com> On Sat, Sep 10, 2011 at 1:08 PM, Richard D. Moores <rdmoores at gmail.com>wrote: > So I've done quite a bit more work. With phone_book.py the user can > not only access phone numbers by the person's initials, but can add > items to the data file. I've also solved the problem of adding a > person who's initials have already been used in a key. > > I've pasted phone_book_for_pasting.py at <http://pastebin.com/2wm4Vf1P>. > > I'd appreciate any comments, instructive criticism, etc. > > It looks pretty good overall, though I didn't examine it too closely. IMHO there are some awkward bits which I think come from your representation of the data. I would probably make the phonebook itself a list, with each entry being a dict. Something like: book = [ {'name':'Mark Sanders', 'cell':'422-318-2346', ' email':'msanders at stanfordalumni.org'}, {'name':'AAA', 'phone':'575-3992', 'phone2':'1-800-472-4630', 'notes':'Membership #422 260 0131863 00 8'}, #... ] Then you can easily search your phone book by name, email, type of contact, relation, etc. A search by name would look like this: def find_by_name(name): for entry in book: if entry['name'] == name: return entry find_by_name('Mark Sanders') #==> {'name':'Mark Sanders', 'cell':'422-318-2346', ' email':'msanders at stanfordalumni.org} or a more general procedure for doing searches on your book could be: def find(criteria, term): for entry in book: if entry[criteria] == term: return entry find('name', 'Mark Sanders') #==> {'name':'Mark Sanders', 'cell':'422-318-2346', ' email':'msanders at stanfordalumni.org} Similarly you could search for initials by providing a to_initials procedure: def to_initials(name): return ''.join([i[0] for i in name.split(' ')]) def find_by_initials(initials): for entry in book: if to_initials(entry['name']) == initials: return entry find_by_initials('MS') #==> {'cell': '422-318-2346', 'name': 'Mark Sanders', 'email': ' msanders at stanfordalumni.org'} Adding a new entry would then be as simple as: def add_new_entry(entry, book): book.append(entry) For storing data I would probably use Pickle, which would look something like this: from cPickle import load, dump f = open('book.pk', 'w') dump(book, f) f.close() and loading your book is similar f = open('book.pk', 'r') book = load(f) f.close() If you want a human readable storage format I would look into json, but pickle has served me well for most purposes. Surely you can store your phonebook as plain text and parse it the way you have, but it's not necessary to do that with all the tools that exist for that purpose. -- Nick Zarczynski Pointless Programming Blog <http://pointlessprogramming.wordpress.com> -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110910/c8fa67dd/attachment-0001.html> From eire1130 at gmail.com Sat Sep 10 21:42:26 2011 From: eire1130 at gmail.com (James Reynolds) Date: Sat, 10 Sep 2011 15:42:26 -0400 Subject: [Tutor] databases In-Reply-To: <EAEC297C-9B97-4AB6-AB5C-64ADEC022F77@gmail.com> References: <EAEC297C-9B97-4AB6-AB5C-64ADEC022F77@gmail.com> Message-ID: <CAE0jAbqBRC_7MZ1PWsC2Y67rtP58zo3vbe8wtgMfw2xaNNd3cA@mail.gmail.com> On Sat, Sep 10, 2011 at 3:39 PM, Andre' Walker-Loud <walksloud at gmail.com>wrote: > Hi All, > > I am completely new to databases as well as using python to access/create > databases. I started googling about it and found so much info, I wasn't > sure where to begin to answer my first question. So I thought I would query > this group by asking a question I am sure has been asked before - but you > all are so friendly, I thought I would give it a try. > > I have databases (many of them) which I want to manipulate, averaging data, > merging databases, etc. > > Do I need to install separate modules to access the databases? > > Do I need to know the specific style the databases were created in to open > manipulate them with python (2.7)? I ask this because with xml files, I was > able to just use > > from xml.dom import minidom > > and then by trial and error in an interactive session, I could figure out > how to walk through the xml file to find what I wanted. I am wondering if I > can do something similar with a database, or if there are more pre-defined > formats. I do not actually know what format my databases are in (someone > else wrote the c-code to create them). > > > While waiting for suggestions, I have started to read Alan Gauld's tutorial > on the subject > > http://www.alan-g.me.uk/tutor/index.htm > > > > Thanks, > > Andre > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > What type of databases? sql server, mysql, sqllite? -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110910/d699c812/attachment.html> From walksloud at gmail.com Sat Sep 10 21:44:14 2011 From: walksloud at gmail.com (Andre' Walker-Loud) Date: Sat, 10 Sep 2011 12:44:14 -0700 Subject: [Tutor] databases In-Reply-To: <CAE0jAbqBRC_7MZ1PWsC2Y67rtP58zo3vbe8wtgMfw2xaNNd3cA@mail.gmail.com> References: <EAEC297C-9B97-4AB6-AB5C-64ADEC022F77@gmail.com> <CAE0jAbqBRC_7MZ1PWsC2Y67rtP58zo3vbe8wtgMfw2xaNNd3cA@mail.gmail.com> Message-ID: <896D17E8-298D-41C4-9C3E-E0F7AFB603F1@gmail.com> > > What type of databases? sql server, mysql, sqllite? Hi James, well this already helps. I don't even know. Do I have to know ahead of time? Or is there a general database package that can open a databases without knowing there format? Thanks, Andre From rdmoores at gmail.com Sat Sep 10 23:36:07 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Sat, 10 Sep 2011 14:36:07 -0700 Subject: [Tutor] need advice about a dictionary ({}) In-Reply-To: <CAG5udOgde82mACHSj4NvHJOkjnZ5vveXgoP=-7Nvr+NU6fAcpw@mail.gmail.com> References: <CALMxxxm2fA_Yo4bQMRHznYXBFZwD03ze-mXo1WeY7VkfM+1J9w@mail.gmail.com> <j4a9p1$a4$1@dough.gmane.org> <CALMxxxmYnzRxSbrgY3hdu-fkpAHGzEgpYTGDjsNPN=c4XqEZyw@mail.gmail.com> <CALMxxxmfW=vX8Of551_vpNT9HVYjg7x=CSj3EDpJ=D85NjxPnw@mail.gmail.com> <CAG5udOgde82mACHSj4NvHJOkjnZ5vveXgoP=-7Nvr+NU6fAcpw@mail.gmail.com> Message-ID: <CALMxxxkw+-3jB9MfMRbw=VNQcvs6d=wsGP1B9oTopzuye85thw@mail.gmail.com> Thanks so much, Jack. You've given me much to chew on. I began phone_book.py without much need for it -- I already had an RTF file with 786 lines that I "grepped" using a script I wrote with Tutor help long ago. I used an RTF file instead of a text file so that any URLs in it would be live. But I wanted to refresh what little I used to know about dicts and see where I could go with it. It turns out to be something I'll actually use for quickly looking up phone numbers of people (friends, relatives, doctors, etc.) and some businesses, and the occasional address. For adding key=value items to the data file, values can be copied as is from the RTF file. It'll probably have fewer than 100 entries. Your idea doesn't seem efficient for me -- lots of typing and editing. But very interesting! I'll probably have fewer than 100 entries. Your pickle examples give me a start on using the cPickle module. Dick From rdmoores at gmail.com Sat Sep 10 23:40:11 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Sat, 10 Sep 2011 14:40:11 -0700 Subject: [Tutor] need advice about a dictionary ({}) In-Reply-To: <CAG5udOgde82mACHSj4NvHJOkjnZ5vveXgoP=-7Nvr+NU6fAcpw@mail.gmail.com> References: <CALMxxxm2fA_Yo4bQMRHznYXBFZwD03ze-mXo1WeY7VkfM+1J9w@mail.gmail.com> <j4a9p1$a4$1@dough.gmane.org> <CALMxxxmYnzRxSbrgY3hdu-fkpAHGzEgpYTGDjsNPN=c4XqEZyw@mail.gmail.com> <CALMxxxmfW=vX8Of551_vpNT9HVYjg7x=CSj3EDpJ=D85NjxPnw@mail.gmail.com> <CAG5udOgde82mACHSj4NvHJOkjnZ5vveXgoP=-7Nvr+NU6fAcpw@mail.gmail.com> Message-ID: <CALMxxxnxEfS3JuoyudOidwj-aOLx40f-itoeZi3NLdk6DYWqCw@mail.gmail.com> Thanks so much, Jack. You've given me much to chew on. I began phone_book.py without much need for it -- I already had an RTF file with 786 lines that I "grepped" using a script I wrote with Tutor help long ago. I used an RTF file instead of a text file so that any URLs in it would be live. But I wanted to refresh what little I used to know about dicts and see where I could go with it. It turns out to be something I'll actually use for quickly looking up phone numbers of people (friends, relatives, doctors, etc.) and some businesses, and the occasional address. For adding key=value items to the data file, values can be copied as is from the RTF file. It'll probably have fewer than 100 entries. Your idea doesn't seem efficient for me -- lots of typing and editing. But very interesting! I'll probably have fewer than 100 entries. Your pickle examples give me a start on using the cPickle module. Dick From rdmoores at gmail.com Sat Sep 10 23:58:40 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Sat, 10 Sep 2011 14:58:40 -0700 Subject: [Tutor] need advice about a dictionary ({}) In-Reply-To: <CAG5udOhzsE4dq-ZhDD+_dB6wMAP+XytBu=5OXze4L1FWSDCCGQ@mail.gmail.com> References: <CALMxxxm2fA_Yo4bQMRHznYXBFZwD03ze-mXo1WeY7VkfM+1J9w@mail.gmail.com> <j4a9p1$a4$1@dough.gmane.org> <CALMxxxmYnzRxSbrgY3hdu-fkpAHGzEgpYTGDjsNPN=c4XqEZyw@mail.gmail.com> <CALMxxxmfW=vX8Of551_vpNT9HVYjg7x=CSj3EDpJ=D85NjxPnw@mail.gmail.com> <CAG5udOgde82mACHSj4NvHJOkjnZ5vveXgoP=-7Nvr+NU6fAcpw@mail.gmail.com> <CAG5udOgC48pWk6Hg2SCk-s_PCjM7VNPV0888dzZfo3GPVmKB9g@mail.gmail.com> <CALMxxx=o=dhzpQCCDPDgyqvJsVr01or9cMWkkW9=nANYwEqvyw@mail.gmail.com> <CAG5udOhzsE4dq-ZhDD+_dB6wMAP+XytBu=5OXze4L1FWSDCCGQ@mail.gmail.com> Message-ID: <CALMxxx=QDgOi5WA2PTY8om=2qBodkjqtgVvRK+XUk10fkM41vA@mail.gmail.com> Jack Trades (actually Nick Zarczynski) just sent me this link to a "Simple phone book app", and has agreed to let me post it to this thread: <https://gist.github.com/1208786#file_book.py> Dick From rafadurancastaneda at gmail.com Sun Sep 11 00:12:13 2011 From: rafadurancastaneda at gmail.com (=?ISO-8859-1?Q?Rafael_Dur=E1n_Casta=F1eda?=) Date: Sun, 11 Sep 2011 00:12:13 +0200 Subject: [Tutor] databases In-Reply-To: <896D17E8-298D-41C4-9C3E-E0F7AFB603F1@gmail.com> References: <EAEC297C-9B97-4AB6-AB5C-64ADEC022F77@gmail.com> <CAE0jAbqBRC_7MZ1PWsC2Y67rtP58zo3vbe8wtgMfw2xaNNd3cA@mail.gmail.com> <896D17E8-298D-41C4-9C3E-E0F7AFB603F1@gmail.com> Message-ID: <4E6BE0BD.9040803@gmail.com> On 10/09/11 21:44, Andre' Walker-Loud wrote: >> What type of databases? sql server, mysql, sqllite? > Hi James, > > well this already helps. I don't even know. Do I have to know ahead of time? Or is there a general database package that can open a databases without knowing there format? > > > Thanks, > > Andre > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor You might look at http://www.sqlalchemy.org/, since it works with most databases. However if you are new on databases, I think you should start learning databases basics, choose a database management system (DBMS) that fit your needs and learn as much as you can about that specific DBMS. Then you can use SQLAlchemy or specific packagas (MySQL-Python, PyGreSQL,...) to acces to that DBMS. In addition if you are going to use frameworks, most of them already have their own tools for DB manipulation. From jacktradespublic at gmail.com Sun Sep 11 00:15:20 2011 From: jacktradespublic at gmail.com (Jack Trades) Date: Sat, 10 Sep 2011 17:15:20 -0500 Subject: [Tutor] need advice about a dictionary ({}) In-Reply-To: <CALMxxxkw+-3jB9MfMRbw=VNQcvs6d=wsGP1B9oTopzuye85thw@mail.gmail.com> References: <CALMxxxm2fA_Yo4bQMRHznYXBFZwD03ze-mXo1WeY7VkfM+1J9w@mail.gmail.com> <j4a9p1$a4$1@dough.gmane.org> <CALMxxxmYnzRxSbrgY3hdu-fkpAHGzEgpYTGDjsNPN=c4XqEZyw@mail.gmail.com> <CALMxxxmfW=vX8Of551_vpNT9HVYjg7x=CSj3EDpJ=D85NjxPnw@mail.gmail.com> <CAG5udOgde82mACHSj4NvHJOkjnZ5vveXgoP=-7Nvr+NU6fAcpw@mail.gmail.com> <CALMxxxkw+-3jB9MfMRbw=VNQcvs6d=wsGP1B9oTopzuye85thw@mail.gmail.com> Message-ID: <CAG5udOgaMRdrS3Eki6V4JsTPca5SqVr5jk6Zr4aTOQmeJ0SpCw@mail.gmail.com> On Sat, Sep 10, 2011 at 4:36 PM, Richard D. Moores <rdmoores at gmail.com>wrote: > Your idea doesn't seem efficient for me -- > lots of typing and editing. > Not sure what you mean by that? I've updated the gist with a quick 5min implementation of a GUI using Tkinter and the approach I outlined. I think using a GUI is best way to minimize "typing and editing" in an app like this. You can find it here: https://gist.github.com/1208786#file_book.py If you're talking about re-entering all your data from your file, you would write a script to do that. This program assumes that you are starting from scratch with a blank phone book. If you would like help converting your existing file, I'm sure I or others can help, but I'd need to see the original file. -- Nick Zarczynski Pointless Programming Blog <http://pointlessprogramming.wordpress.com> -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110910/d6e99ce2/attachment-0001.html> From alan.gauld at btinternet.com Sun Sep 11 00:24:54 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 10 Sep 2011 23:24:54 +0100 Subject: [Tutor] databases In-Reply-To: <896D17E8-298D-41C4-9C3E-E0F7AFB603F1@gmail.com> References: <EAEC297C-9B97-4AB6-AB5C-64ADEC022F77@gmail.com> <CAE0jAbqBRC_7MZ1PWsC2Y67rtP58zo3vbe8wtgMfw2xaNNd3cA@mail.gmail.com> <896D17E8-298D-41C4-9C3E-E0F7AFB603F1@gmail.com> Message-ID: <j4gnv0$j48$1@dough.gmane.org> On 10/09/11 20:44, Andre' Walker-Loud wrote: >> What type of databases? sql server, mysql, sqllite? > well this already helps. I don't even know. > Do I have to know ahead of time? Or is there a general database > package that can open a databases without knowing there format? The Python DB API is pretty good at covering all the common databases but sadly everyone has some slight variances so you do need to know which product you will be using. As an example the SQLite package that comes in the standard library - and is a good starter - doesn't require login credentials but Oracle, MySQL etc do. Also Sqllite is stored in a single file accessed via a code library whereas most other SQL databases use multiple files and a server frontend. (That's why there's a connect() function - to connect to the server... in SQLite connect just opens the file!) If you are a database noob I'd keep it simple and stick with SQLite, it's powerful enough for most beginner type projects and misses out some of the more complex features of the other packages. Provided you aren't expecting to scale up to 10's of millions of records it will do just fine. Once you understand SQLite moving to MySQL or Firebird or whatever will be an easy next step. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From achompas at gmail.com Sun Sep 11 00:28:34 2011 From: achompas at gmail.com (Alejandro Companioni) Date: Sat, 10 Sep 2011 18:28:34 -0400 Subject: [Tutor] databases In-Reply-To: <mailman.4354.1315692923.27777.tutor@python.org> References: <mailman.4354.1315692923.27777.tutor@python.org> Message-ID: <D268BEDB-BC87-4368-8F7A-EE9AF703F0A1@gmail.com> On Sep 10, 2011, at 6:15 PM, tutor-request at python.org wrote: > You might look at http://www.sqlalchemy.org/, since it works with most > databases. However if you are new on databases, I think you should start > learning databases basics, choose a database management system (DBMS) > that fit your needs and learn as much as you can about that specific > DBMS. Then you can use SQLAlchemy or specific packagas (MySQL-Python, > PyGreSQL,...) to acces to that DBMS. In addition if you are going to use > frameworks, most of them already have their own tools for DB manipulation. > Just wanted to chime in, because I wish someone had told me this sooner, but if you're using a Mac, try to steer clear of mysql-python. Setting it up on a Mac is absolutely infuriating. If your databases are MySQL-based and you're using a Mac, I'd recommend setting up a Linux VM to access them with Python (or not using Python at all). Good luck! -Alejandro -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110910/7c0ad2e8/attachment.html> From alan.gauld at btinternet.com Sun Sep 11 00:32:11 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 10 Sep 2011 23:32:11 +0100 Subject: [Tutor] need advice about a dictionary ({}) In-Reply-To: <CALMxxxmfW=vX8Of551_vpNT9HVYjg7x=CSj3EDpJ=D85NjxPnw@mail.gmail.com> References: <CALMxxxm2fA_Yo4bQMRHznYXBFZwD03ze-mXo1WeY7VkfM+1J9w@mail.gmail.com> <j4a9p1$a4$1@dough.gmane.org> <CALMxxxmYnzRxSbrgY3hdu-fkpAHGzEgpYTGDjsNPN=c4XqEZyw@mail.gmail.com> <CALMxxxmfW=vX8Of551_vpNT9HVYjg7x=CSj3EDpJ=D85NjxPnw@mail.gmail.com> Message-ID: <j4gock$ld6$1@dough.gmane.org> On 10/09/11 19:08, Richard D. Moores wrote: > Some have suggested using the shelve module. I looked at it but > couldn't see in detail how to use it. Did you read the help page? It says: import shelve d = shelve.open(filename) # open, with (g)dbm filename -- no suffix d[key] = data # store data at key data = d[key] # retrieve a COPY of the data at key del d[key] # delete data stored at key flag = d.has_key(key) # true if the key exists list = d.keys() # a list of all existing keys (slow!) d.close() # close it So you open the file and from that point on treat it exactly like a dictionary. Then close the file at the end. Now which part don't you understand? The ony bit that migt confuse is the mention of gdbm filename which just means give it a filename without any suffix...just ignore the gdbm reference. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From rdmoores at gmail.com Sun Sep 11 01:18:18 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Sat, 10 Sep 2011 16:18:18 -0700 Subject: [Tutor] need advice about a dictionary ({}) In-Reply-To: <j4gock$ld6$1@dough.gmane.org> References: <CALMxxxm2fA_Yo4bQMRHznYXBFZwD03ze-mXo1WeY7VkfM+1J9w@mail.gmail.com> <j4a9p1$a4$1@dough.gmane.org> <CALMxxxmYnzRxSbrgY3hdu-fkpAHGzEgpYTGDjsNPN=c4XqEZyw@mail.gmail.com> <CALMxxxmfW=vX8Of551_vpNT9HVYjg7x=CSj3EDpJ=D85NjxPnw@mail.gmail.com> <j4gock$ld6$1@dough.gmane.org> Message-ID: <CALMxxxmDhCGPhJ0i+BOKHqRLpLqTPeoHiG_4q9Ouk-dUXjBqRg@mail.gmail.com> On Sat, Sep 10, 2011 at 15:32, Alan Gauld <alan.gauld at btinternet.com> wrote: > On 10/09/11 19:08, Richard D. Moores wrote: > >> Some have suggested using the shelve module. I looked at it but >> couldn't see in detail how to use it. > > Did you read the help page? I did. I can see it would be a useful reference once I learned from elsewhere how to use shelve. > It says: > > import shelve > d = shelve.open(filename) # open, with (g)dbm filename -- no suffix > > d[key] = data ? # store data at key > data = d[key] ? # retrieve a COPY of the data at key > del d[key] ? ? ?# delete data stored at key > flag = d.has_key(key) ? # true if the key exists > list = d.keys() # a list of all existing keys (slow!) > d.close() ? ? ? # close it > > > So you open the file and from that point on treat it exactly like a > dictionary. I'm still a bit shaky about dictionaries. > Then close the file at the end. > > Now which part don't you understand? Much of what comes after that is beyond me. > The ony bit that migt confuse is the mention of gdbm filename which just > means give it a filename without any suffix...just ignore the gdbm > reference. Thanks for your encouragement Alan, but I'm still looking among my Python books for a good exposition of shelve. Dick From walksloud at gmail.com Sun Sep 11 02:24:56 2011 From: walksloud at gmail.com (Andre' Walker-Loud) Date: Sat, 10 Sep 2011 17:24:56 -0700 Subject: [Tutor] databases In-Reply-To: <j4gnv0$j48$1@dough.gmane.org> References: <EAEC297C-9B97-4AB6-AB5C-64ADEC022F77@gmail.com> <CAE0jAbqBRC_7MZ1PWsC2Y67rtP58zo3vbe8wtgMfw2xaNNd3cA@mail.gmail.com> <896D17E8-298D-41C4-9C3E-E0F7AFB603F1@gmail.com> <j4gnv0$j48$1@dough.gmane.org> Message-ID: <4D6D29B3-701F-4B2F-B079-DBB0052BEA2B@gmail.com> > > package that can open a databases without knowing there format? > > The Python DB API is pretty good at covering all the common databases but sadly everyone has some slight variances so you do need to know which product you will be using. > > As an example the SQLite package that comes in the standard library - and is a good starter - doesn't require login credentials but Oracle, MySQL etc do. Also Sqllite is stored in a single file accessed via a code library whereas most other SQL databases use multiple files and a server frontend. (That's why there's a connect() function - to connect to the server... in SQLite connect just opens the file!) > > If you are a database noob I'd keep it simple and stick with SQLite, it's powerful enough for most beginner type projects and misses out some of the more complex features of the other packages. Provided you aren't expecting to scale up to 10's of millions of records it will do just fine. Once you understand SQLite moving to MySQL or Firebird or whatever will be an easy next step. So, in case I wasn't clear, the databases are already made by someone else, and the format is beyond my control. I need/want to learn to manipulate them. Most likely they are similar to the Berkeley database (but I don't know what this means yet). Thanks for the help, Andre From walksloud at gmail.com Sun Sep 11 02:26:48 2011 From: walksloud at gmail.com (Andre' Walker-Loud) Date: Sat, 10 Sep 2011 17:26:48 -0700 Subject: [Tutor] databases In-Reply-To: <D268BEDB-BC87-4368-8F7A-EE9AF703F0A1@gmail.com> References: <mailman.4354.1315692923.27777.tutor@python.org> <D268BEDB-BC87-4368-8F7A-EE9AF703F0A1@gmail.com> Message-ID: <C2D92563-6971-43C4-BE3F-2DB010338A02@gmail.com> >> You might look at http://www.sqlalchemy.org/, since it works with most >> databases. However if you are new on databases, I think you should start >> learning databases basics, choose a database management system (DBMS) >> that fit your needs and learn as much as you can about that specific >> DBMS. Then you can use SQLAlchemy or specific packagas (MySQL-Python, >> PyGreSQL,...) to acces to that DBMS. In addition if you are going to use >> frameworks, most of them already have their own tools for DB manipulation. >> > > Just wanted to chime in, because I wish someone had told me this sooner, but if you're using a Mac, try to steer clear of mysql-python. Setting it up on a Mac is absolutely infuriating. > > If your databases are MySQL-based and you're using a Mac, I'd recommend setting up a Linux VM to access them with Python (or not using Python at all). Good luck! Thanks for the warning Alejandro. Turns out, they live on a linux cluster - but I log in via a Mac, and likely will copy locally to play around with. I figured I could either hack the c++ code built already to manipulate them, or use this as an excuse to learn about databases via python. Andre From alan.gauld at btinternet.com Sun Sep 11 02:34:18 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 11 Sep 2011 01:34:18 +0100 Subject: [Tutor] need advice about a dictionary ({}) In-Reply-To: <CALMxxxmDhCGPhJ0i+BOKHqRLpLqTPeoHiG_4q9Ouk-dUXjBqRg@mail.gmail.com> References: <CALMxxxm2fA_Yo4bQMRHznYXBFZwD03ze-mXo1WeY7VkfM+1J9w@mail.gmail.com> <j4a9p1$a4$1@dough.gmane.org> <CALMxxxmYnzRxSbrgY3hdu-fkpAHGzEgpYTGDjsNPN=c4XqEZyw@mail.gmail.com> <CALMxxxmfW=vX8Of551_vpNT9HVYjg7x=CSj3EDpJ=D85NjxPnw@mail.gmail.com> <j4gock$ld6$1@dough.gmane.org> <CALMxxxmDhCGPhJ0i+BOKHqRLpLqTPeoHiG_4q9Ouk-dUXjBqRg@mail.gmail.com> Message-ID: <j4gvhi$bvu$1@dough.gmane.org> On 11/09/11 00:18, Richard D. Moores wrote: >> So you open the file and from that point on treat it exactly like a >> dictionary. > > I'm still a bit shaky about dictionaries. But you started the post with using a dictionary. Shelve is just a dictionary that lives in a file instead of memory. If you can put data into or read it out of a dictionary then you can do the same with shelve. The only complexity is you have to open the file before sing it and close it when your done. > Much of what comes after that is beyond me. > Thanks for your encouragement Alan, but I'm still looking among my > Python books for a good exposition of shelve. You probably won't find much in books because shelve has such a specific purpose. As a result there isn't much to say about it if you've already covered dictionaries. It's a file based dictionary. So read up on dictionaries. Then just use it. There are a few limitations with shelve but for most normal cases you can ignore that and just use it like any normal dictionary. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From marc.tompkins at gmail.com Sun Sep 11 02:34:26 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Sat, 10 Sep 2011 17:34:26 -0700 Subject: [Tutor] need advice about a dictionary ({}) In-Reply-To: <CALMxxxmDhCGPhJ0i+BOKHqRLpLqTPeoHiG_4q9Ouk-dUXjBqRg@mail.gmail.com> References: <CALMxxxm2fA_Yo4bQMRHznYXBFZwD03ze-mXo1WeY7VkfM+1J9w@mail.gmail.com> <j4a9p1$a4$1@dough.gmane.org> <CALMxxxmYnzRxSbrgY3hdu-fkpAHGzEgpYTGDjsNPN=c4XqEZyw@mail.gmail.com> <CALMxxxmfW=vX8Of551_vpNT9HVYjg7x=CSj3EDpJ=D85NjxPnw@mail.gmail.com> <j4gock$ld6$1@dough.gmane.org> <CALMxxxmDhCGPhJ0i+BOKHqRLpLqTPeoHiG_4q9Ouk-dUXjBqRg@mail.gmail.com> Message-ID: <CAKK8jXYiADt=W9J6_qvH4TDsSw573vmCiQnAPVYEBgWDFpKWnQ@mail.gmail.com> On Sat, Sep 10, 2011 at 4:18 PM, Richard D. Moores <rdmoores at gmail.com>wrote: > On Sat, Sep 10, 2011 at 15:32, Alan Gauld <alan.gauld at btinternet.com> > wrote: > > So you open the file and from that point on treat it exactly like a > > dictionary. > > I'm still a bit shaky about dictionaries. > > That right there is the salient bit. Using shelve is just like using a dictionary; probably that's why you're finding the documentation sparse: dictionaries are core Python, so they assume you know how to use them. ("First, catch your rabbit...") I was about to write an introduction to dictionaries, but I realized it's been done, and done better than I could. I really recommend that you learn them; I think that once you do, you'll find that they're a better fit in all sorts of places where you've been using lists. (Speaking from personal experience...) -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110910/7d80fb10/attachment.html> From alan.gauld at btinternet.com Sun Sep 11 02:41:35 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 11 Sep 2011 01:41:35 +0100 Subject: [Tutor] need advice about a dictionary ({}) In-Reply-To: <CALMxxxmDhCGPhJ0i+BOKHqRLpLqTPeoHiG_4q9Ouk-dUXjBqRg@mail.gmail.com> References: <CALMxxxm2fA_Yo4bQMRHznYXBFZwD03ze-mXo1WeY7VkfM+1J9w@mail.gmail.com> <j4a9p1$a4$1@dough.gmane.org> <CALMxxxmYnzRxSbrgY3hdu-fkpAHGzEgpYTGDjsNPN=c4XqEZyw@mail.gmail.com> <CALMxxxmfW=vX8Of551_vpNT9HVYjg7x=CSj3EDpJ=D85NjxPnw@mail.gmail.com> <j4gock$ld6$1@dough.gmane.org> <CALMxxxmDhCGPhJ0i+BOKHqRLpLqTPeoHiG_4q9Ouk-dUXjBqRg@mail.gmail.com> Message-ID: <j4gvv7$fas$1@dough.gmane.org> On 11/09/11 00:18, Richard D. Moores wrote: >> Now which part don't you understand? > > Much of what comes after that is beyond me. I meant to add, you can pretty much ignore all the stuff at the end of the Help page about class definitions. You only need that if you intend to create your own specialised Shelf object. All you need to know is in the pseudocode bit that I posted. open() the file use the shelf like a dictionary close() the file And there are two main caveats given: 1) Don't try to edit mutable data objects (lists) in place. Extract them, modify them and replace them 2) Don't use the writeback=True setting when you open large data sets. That's it. Alan G. From alan.gauld at btinternet.com Sun Sep 11 02:46:30 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 11 Sep 2011 01:46:30 +0100 Subject: [Tutor] databases In-Reply-To: <D268BEDB-BC87-4368-8F7A-EE9AF703F0A1@gmail.com> References: <mailman.4354.1315692923.27777.tutor@python.org> <D268BEDB-BC87-4368-8F7A-EE9AF703F0A1@gmail.com> Message-ID: <j4h08e$hhj$1@dough.gmane.org> On 10/09/11 23:28, Alejandro Companioni wrote: > Just wanted to chime in, because I wish someone had told me this sooner, > but if you're using a Mac, try to steer clear of mysql-python. Setting > it up on a Mac is absolutely infuriating. I've never used MySql on a Mac but I'm curious why it should be so difficult. MacOS is just BSD Unix under the GUI so why would be any different to any other Unix type system? What were the problems that you encountered? > If your databases are MySQL-based and you're using a Mac, I'd recommend > setting up a Linux VM to access them with Python (or not using Python at > all). Good luck! Now that sounds like it should be much more difficult. You'd effectively be running a client server setup to a foreign OS on your own computer but sharing the physical resources... There must be something really weird about the MacOS setup to make that easier! I'm intrigued. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sun Sep 11 02:49:44 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sun, 11 Sep 2011 01:49:44 +0100 (BST) Subject: [Tutor] databases In-Reply-To: <4D6D29B3-701F-4B2F-B079-DBB0052BEA2B@gmail.com> References: <EAEC297C-9B97-4AB6-AB5C-64ADEC022F77@gmail.com> <CAE0jAbqBRC_7MZ1PWsC2Y67rtP58zo3vbe8wtgMfw2xaNNd3cA@mail.gmail.com> <896D17E8-298D-41C4-9C3E-E0F7AFB603F1@gmail.com> <j4gnv0$j48$1@dough.gmane.org> <4D6D29B3-701F-4B2F-B079-DBB0052BEA2B@gmail.com> Message-ID: <1315702184.64895.YahooMailRC@web86702.mail.ird.yahoo.com> > > package that can open a databases without knowing there format? > So, in case I wasn't clear, the databases are already made by someone else, > and the format is beyond my control. I need/want to learn to manipulate them. > OK, That wasn't clear. And it makes a difference. You need to know the format. > Most likely they are similar to the Berkeley database And that makes a much bigger difference because most folks assume by 'database' you mean a SQL database. Berkeley databases are flat file based and there is a module to read them in the Python library, but they don't use SQL. They are more like a random access file mechanism than a relational database. If that's what you are dealing with then it's a whole lot of different references you need. I'd start with wikipedia and the [g]dbm module documentation. HTH, Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110911/690b5646/attachment.html> From rdmoores at gmail.com Sun Sep 11 03:28:40 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Sat, 10 Sep 2011 18:28:40 -0700 Subject: [Tutor] need advice about a dictionary ({}) In-Reply-To: <CAKK8jXYiADt=W9J6_qvH4TDsSw573vmCiQnAPVYEBgWDFpKWnQ@mail.gmail.com> References: <CALMxxxm2fA_Yo4bQMRHznYXBFZwD03ze-mXo1WeY7VkfM+1J9w@mail.gmail.com> <j4a9p1$a4$1@dough.gmane.org> <CALMxxxmYnzRxSbrgY3hdu-fkpAHGzEgpYTGDjsNPN=c4XqEZyw@mail.gmail.com> <CALMxxxmfW=vX8Of551_vpNT9HVYjg7x=CSj3EDpJ=D85NjxPnw@mail.gmail.com> <j4gock$ld6$1@dough.gmane.org> <CALMxxxmDhCGPhJ0i+BOKHqRLpLqTPeoHiG_4q9Ouk-dUXjBqRg@mail.gmail.com> <CAKK8jXYiADt=W9J6_qvH4TDsSw573vmCiQnAPVYEBgWDFpKWnQ@mail.gmail.com> Message-ID: <CALMxxx=0VViCgn66b3vwkYPtg0Hnp_u_rAX_C6TVFzzt3t-N0w@mail.gmail.com> On Sat, Sep 10, 2011 at 17:34, Marc Tompkins <marc.tompkins at gmail.com> wrote: > On Sat, Sep 10, 2011 at 4:18 PM, Richard D. Moores <rdmoores at gmail.com> > wrote: >> >> On Sat, Sep 10, 2011 at 15:32, Alan Gauld <alan.gauld at btinternet.com> >> wrote: >> >> > So you open the file and from that point on treat it exactly like a >> > dictionary. >> >> I'm still a bit shaky about dictionaries. >> > That right there is the salient bit.? Using shelve is just like using a > dictionary; probably that's why you're finding the documentation sparse: > dictionaries are core Python, so they assume you know how to use them. > ("First, catch your rabbit...") > > I was about to write an introduction to dictionaries, but I realized it's > been done, and done better than I could.? I really recommend that you learn > them; I think that once you do, you'll find that they're a better fit in all > sorts of places where you've been using lists.? (Speaking from personal > experience...) Well, I wrote "a BIT shaky". I sure learned a lot writing my phone_book.py, with important input from you . And am still pretty happy with it. And dictionaries seem to be well-covered in some of the Python books I have. Dick From rdmoores at gmail.com Sun Sep 11 03:32:15 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Sat, 10 Sep 2011 18:32:15 -0700 Subject: [Tutor] need advice about a dictionary ({}) In-Reply-To: <j4gvhi$bvu$1@dough.gmane.org> References: <CALMxxxm2fA_Yo4bQMRHznYXBFZwD03ze-mXo1WeY7VkfM+1J9w@mail.gmail.com> <j4a9p1$a4$1@dough.gmane.org> <CALMxxxmYnzRxSbrgY3hdu-fkpAHGzEgpYTGDjsNPN=c4XqEZyw@mail.gmail.com> <CALMxxxmfW=vX8Of551_vpNT9HVYjg7x=CSj3EDpJ=D85NjxPnw@mail.gmail.com> <j4gock$ld6$1@dough.gmane.org> <CALMxxxmDhCGPhJ0i+BOKHqRLpLqTPeoHiG_4q9Ouk-dUXjBqRg@mail.gmail.com> <j4gvhi$bvu$1@dough.gmane.org> Message-ID: <CALMxxxnjYtwqv6P8vFvYutET0r-k55RQ620dtdrh6otWhnPqNQ@mail.gmail.com> On Sat, Sep 10, 2011 at 17:34, Alan Gauld <alan.gauld at btinternet.com> wrote: > On 11/09/11 00:18, Richard D. Moores wrote: > >>> So you open the file and from that point on treat it exactly like a >>> dictionary. >> >> I'm still a bit shaky about dictionaries. > > But you started the post with using a dictionary. > > Shelve is just a dictionary that lives in a file instead of memory. > If you can put data into or read it out of a dictionary then you can do the > same with shelve. > > The only complexity is you have to open the file before sing it and close it > when your done. > >> Much of what comes after that is beyond me. > > >> Thanks for your encouragement Alan, but I'm still looking among my >> Python books for a good exposition of shelve. > > You probably won't find much in books because shelve has such a specific > purpose. As a result there isn't much to say about it > if you've already covered dictionaries. > > It's a file based dictionary. So read up on dictionaries. > Then just use it. > > There are a few limitations with shelve but for most normal > cases you can ignore that and just use it like any normal > dictionary. OK, Alan, I really will give shelve a try. Dick From rdmoores at gmail.com Sun Sep 11 03:35:33 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Sat, 10 Sep 2011 18:35:33 -0700 Subject: [Tutor] need advice about a dictionary ({}) In-Reply-To: <CAG5udOgaMRdrS3Eki6V4JsTPca5SqVr5jk6Zr4aTOQmeJ0SpCw@mail.gmail.com> References: <CALMxxxm2fA_Yo4bQMRHznYXBFZwD03ze-mXo1WeY7VkfM+1J9w@mail.gmail.com> <j4a9p1$a4$1@dough.gmane.org> <CALMxxxmYnzRxSbrgY3hdu-fkpAHGzEgpYTGDjsNPN=c4XqEZyw@mail.gmail.com> <CALMxxxmfW=vX8Of551_vpNT9HVYjg7x=CSj3EDpJ=D85NjxPnw@mail.gmail.com> <CAG5udOgde82mACHSj4NvHJOkjnZ5vveXgoP=-7Nvr+NU6fAcpw@mail.gmail.com> <CALMxxxkw+-3jB9MfMRbw=VNQcvs6d=wsGP1B9oTopzuye85thw@mail.gmail.com> <CAG5udOgaMRdrS3Eki6V4JsTPca5SqVr5jk6Zr4aTOQmeJ0SpCw@mail.gmail.com> Message-ID: <CALMxxxnMLmMiZsxyNurzjK9MuWasKFJNbXZtc5bLch-OYNBW2A@mail.gmail.com> On Sat, Sep 10, 2011 at 15:15, Jack Trades <jacktradespublic at gmail.com> wrote: > On Sat, Sep 10, 2011 at 4:36 PM, Richard D. Moores <rdmoores at gmail.com> > wrote: >> >> Your idea doesn't seem efficient for me -- >> lots of typing and editing. > > Not sure what you mean by that?? I've updated the gist with a quick 5min > implementation of a GUI using Tkinter and the approach I outlined.? I think > using a GUI is best way to minimize "typing and editing" in an app like > this.? You can find it here: > > https://gist.github.com/1208786#file_book.py Using Python 2.7 for it, it seems to work fine, except that I can't see how the GUI helps. It opens only when I use the g option to find an entry already made. Useful for editing an entry, though. As for the non-GUI script, I get this error no matter which choice I make. I'm too dumb, and have forgotten too much of Python 2.x to debug: ============================== What's next: (q) Quit (a) Add new Entry (v) View all Entries (s) General Search (si) Search by Initials (sn) Search by Name > q Traceback (most recent call last): File "c:\P32Working\Pickles\nicks_simple_phone_book_app.py", line 171, in <module> main_loop() File "c:\P32Working\Pickles\nicks_simple_phone_book_app.py", line 94, in main_loop > """) File "<string>", line 1, in <module> NameError: name 'q' is not defined Process terminated with an exit code of 1 ============================ > > If you're talking about re-entering all your data from your file, you would > write a script to do that. Ha! I would? >? This program assumes that you are starting from > scratch with a blank phone book.? If you would like help converting your > existing file, I'm sure I or others can help, but I'd need to see the > original file. I'll take you up on that. I'll have to edit it some first. What I have now with "grepping" that 786-line RTF file is maximum flexibility. A line in the file always begins with a name, with at least one phone number, then if a company, the hours they are reachable by phone, possibly their web address, maybe an email address, my contact there plus maybe her secretary. If a physician, there might very well be his specialty, his nurse's name, mention of who recommended him to me, etc. It seems that the format of info for your way is set rigidly in advance, or am I wrong? Dick > > -- > Nick Zarczynski > Pointless Programming Blog > > From jacktradespublic at gmail.com Sun Sep 11 04:13:32 2011 From: jacktradespublic at gmail.com (Jack Trades) Date: Sat, 10 Sep 2011 21:13:32 -0500 Subject: [Tutor] need advice about a dictionary ({}) In-Reply-To: <CALMxxxnMLmMiZsxyNurzjK9MuWasKFJNbXZtc5bLch-OYNBW2A@mail.gmail.com> References: <CALMxxxm2fA_Yo4bQMRHznYXBFZwD03ze-mXo1WeY7VkfM+1J9w@mail.gmail.com> <j4a9p1$a4$1@dough.gmane.org> <CALMxxxmYnzRxSbrgY3hdu-fkpAHGzEgpYTGDjsNPN=c4XqEZyw@mail.gmail.com> <CALMxxxmfW=vX8Of551_vpNT9HVYjg7x=CSj3EDpJ=D85NjxPnw@mail.gmail.com> <CAG5udOgde82mACHSj4NvHJOkjnZ5vveXgoP=-7Nvr+NU6fAcpw@mail.gmail.com> <CALMxxxkw+-3jB9MfMRbw=VNQcvs6d=wsGP1B9oTopzuye85thw@mail.gmail.com> <CAG5udOgaMRdrS3Eki6V4JsTPca5SqVr5jk6Zr4aTOQmeJ0SpCw@mail.gmail.com> <CALMxxxnMLmMiZsxyNurzjK9MuWasKFJNbXZtc5bLch-OYNBW2A@mail.gmail.com> Message-ID: <CAG5udOjwCUmBzAUQvB5FiemL==CNkKN5eg=sHgiSZbaB+8APnw@mail.gmail.com> > > Using Python 2.7 for it, it seems to work fine, except that I can't > see how the GUI helps. It opens only when I use the g option to find > an entry already made. Useful for editing an entry, though. > Well the idea would be to build the app as a full-blown GUI. The GUI search and edit functionality was just a proof-of-concept to show how that may work. I was just having some fun and seeing what I could do in less than an hour. Turning this into a full blown app is not what I had in mind, though if you want to build on it to learn I would be willing to help. > > As for the non-GUI script, I get this error no matter which choice I > make. I'm too dumb, and have forgotten too much of Python 2.x to > debug: > > ============================== > What's next: > (q) Quit > (a) Add new Entry > (v) View all Entries > (s) General Search > (si) Search by Initials > (sn) Search by Name > > > q > Traceback (most recent call last): > File "c:\P32Working\Pickles\nicks_simple_phone_book_app.py", line > 171, in <module> > main_loop() > File "c:\P32Working\Pickles\nicks_simple_phone_book_app.py", line > 94, in main_loop > > """) > File "<string>", line 1, in <module> > NameError: name 'q' is not defined > Process terminated with an exit code of 1 > ============================ > My guess is that this has something to do with Python 3.x not having raw_input. Try changing the raw_input calls to input. I don't get that error with 2.7. > > > If you're talking about re-entering all your data from your file, you > would > > write a script to do that. > > Ha! I would? > > Well, yeah. A line in the file always begins with a name, with at > least one phone number, then if a company, the hours they are > reachable by phone, possibly their web address, maybe an email > address, my contact there plus maybe her secretary. If a physician, > there might very well be his specialty, his nurse's name, mention of > who recommended him to me, etc. Like I said, I'd have to see the file to comment more, but it sounds like it may be too irregular to make writing a script an easy process. Though I can't be sure without seeing it. You could always enter these things by hand... I should probably ask; what is your goal for this app? Is it to learn some Python while making a usable app? Or are you looking for a robust address book for quick lookups of information? If it's the latter, I'd recommend you look around for something that's already made. It will save you a lot of trouble in the long run. If you're looking for a good learning experience this kind of app is a great starting place. However expect to run into problems along the way, up to and possibly beyond possibly hosing all the data you have entered into the app. Make regular backups of the data and keep your original around. > It seems that the format of info for > your way is set rigidly in advance, or am I wrong? > > Not really. Key/value pairs can be entered in arbitrary order. I used = to seperate key/values because that's what you used in your app and | to seperate k/v pairs to allow spaces without quoting strings. You could easily replace these tokens (= or |) with whatever you want. If you have another format that differs by more than those characters you would need to write a different parser. However there does have to be some consistency to the format of your data to make parsing easier. The less rigid your data the more work you will have to do to parse it. Since you said earlier that you will probably have less than 100 entries in your phone book, you may want to think about restructuring your data by hand to make it easier to parse before writing your parser. -- Nick Zarczynski Pointless Programming Blog <http://pointlessprogramming.wordpress.com> -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110910/77dd95f5/attachment.html> From achompas at gmail.com Sun Sep 11 07:19:02 2011 From: achompas at gmail.com (Alejandro Companioni) Date: Sun, 11 Sep 2011 01:19:02 -0400 Subject: [Tutor] databases In-Reply-To: <mailman.4370.1315704541.27777.tutor@python.org> References: <mailman.4370.1315704541.27777.tutor@python.org> Message-ID: <1901FF48-1741-42AA-B37A-588FD449CC83@gmail.com> On Sep 10, 2011, at 9:29 PM, tutor-request at python.org wrote: > I've never used MySql on a Mac but I'm curious why it should be so > difficult. > > MacOS is just BSD Unix under the GUI so why would be any different > to any other Unix type system? What were the problems that you encountered? Hey Alan, I had the same thoughts at first: OS X is just BSD! This can't be too different from a Linux installation, right? There are a number of problems with mysql-python--chiefly its poor maintenance. I'll link to a nine (!) step guide on installing mysql-python on Mac as an example: http://friendlybit.com/tutorial/install-mysql-python-on-mac-os-x-leopard/ At Step 9 the author suggests using setuptools even though it will fail, and you'd actually have to patch a (old, well-documented) bug yourself. I wish I had found that website sooner, as installing mysql-python on my Mac took about 5-6 hours of constant frustration. Not a good start for a new Python coder, but if at least one novice skips my experience after reading this email then I'll be happy. -Alejandro -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110911/064279ab/attachment-0001.html> From thisisonlyatest at gmx.com Sun Sep 11 08:15:26 2011 From: thisisonlyatest at gmx.com (brandon w) Date: Sun, 11 Sep 2011 02:15:26 -0400 Subject: [Tutor] Tkinter Entry field text In-Reply-To: <CAPM86Nf0-qkNMbg4U7WUC3sBX74UCj_bTjTLqPZASQXNMbEEag@mail.gmail.com> References: <4E697A8C.1030106@gmx.com> <CAPM86Nf0-qkNMbg4U7WUC3sBX74UCj_bTjTLqPZASQXNMbEEag@mail.gmail.com> Message-ID: <4E6C51FE.6010906@gmx.com> On 09/10/2011 10:16 AM, Wayne Werner wrote: > On Thu, Sep 8, 2011 at 9:31 PM, brandon w <thisisonlyatest at gmx.com > <mailto:thisisonlyatest at gmx.com>> wrote: > > How do you display text in a Entry field and have it disappear > when a person clicks in it? > <snip some code> To get text into this box the person must first > delete what is already in there. > > Python 2.6.6 > > > Think about the process. You're already mostly there: you're > displaying data already, and you know what you want to do. > > You'll want to take a look at binding events, and if you Google for > "tkinter events" (http://www.google.com/search?q=tkinter+events) then > your first result takes you here: > http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm > > To point you in the right direction, you want to take a look at the > <FocusIn> event. If you're not familiar with what a callback is, you > should also read this page: http://effbot.org/zone/tkinter-callbacks.htm > > If you still have problems after that, show us what else you've tried > and we'll be happy to give you more pointers in the right direction. > > > > Of course, while this answers your questions, I would be remiss if I > didn't suggest a few more things about your program in general. > > > label1 = Label(root, text="Enter you password: ") > > label1 isn't a terribly descriptive name. That's fine if you don't > intend to actually do anything with the label. However, you can make > this even more explicit by chaining the commands together. Since > Label() returns a label, you can add a dot to the end and treat it > just like you would the variable: > > Label(root, text="Enter you password: ").grid(sticky=W, row=0, column=0) > > That will create your label and stick it in the grid in one step, and > makes it clear to anyone reading your code (including yourself down > the road!) that you don't care to do anything with that label. > > Next: > > > enter_data1 = Entry(root, bg = "pale green") > > enter_data1 also suffers from the same naming problem. It doesn't > describe what the variable is or does very well, aside from entering > data. You could change it to something like "password_entry" - which > tells anyone reading your program that the variable should contain > something that lets you do some password entry. Just naming it > password would also be better than enter_data1. > > One other issue that you should consider - with the options you have > set, anyone could see what you typed in as your password. If you're > just using this as a testing program to play around with, that's > probably OK, but what's even better is to change what's shown in the > box. You can do this by setting the "show" option, either in the > constructor or somewhere later: > > from Tkinter import * > > root = Tk() > entry = Entry(root) > entry.pack() > entry.insert(0, "My Cool Password") > entry.config(show="*") > root.mainloop() > > The nice thing about the config() method is that it allows you to > change config attributes later. You can combine this knowledge with > some of what I mentioned earlier to show 'password' until they > navigate to the field, and then just show asterisks. > > For bonus points, if they leave the password field without typing a > password, can you make it show 'password' again? > > HTH, > Wayne Wayne, Your advice was extremely helpful. I pointed me into the right direction. I got the code to work after some time. I know how to make it show the "password" again. I would have to do this: from Tkinter import * root = Tk() root.title("Show me your Password") root.geometry("375x100+600+250") root.grid() def callback(event): passwd_entry.delete(0, END) # It would come back because there is no .insert() function. return [....snip...] #========================= Here is the final working code: #!/usr/bin/python from Tkinter import * root = Tk() root.title("Show me your Password") root.geometry("375x100+600+250") root.grid() def callback(event): field0 = varText1.get() passwd_entry.delete(0, END) passwd_entry.insert(0, field0) return def showPasswd(): field1 = varText.get() passwd_display.delete(0, END) passwd_display.insert(0, field1) return Label(root, text="Type your password in this box: ").grid(sticky=W, row=0, column=0) Label(root, text="Your password is:").grid(sticky=W, row=2, column=0) varText = StringVar() varText.set("Enter password") passwd_entry = Entry(root, textvariable=varText, bg = "pale green") passwd_entry.bind("<Enter>", callback) passwd_entry.config(show="*") passwd_entry.grid(row=0, column=1) varText1 = StringVar(None) passwd_display = Entry(root, textvariable=varText1, bg = "pale green") passwd_display.grid(row=2, column=1) Button(root, text="Show Password", width=10, command=showPasswd).grid(sticky=W, row=1, column=0) root.mainloop() Thanks a lot for your help!!!!! -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110911/35bffd27/attachment.html> From alan.gauld at btinternet.com Sun Sep 11 10:34:38 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 11 Sep 2011 09:34:38 +0100 Subject: [Tutor] databases In-Reply-To: <1901FF48-1741-42AA-B37A-588FD449CC83@gmail.com> References: <mailman.4370.1315704541.27777.tutor@python.org> <1901FF48-1741-42AA-B37A-588FD449CC83@gmail.com> Message-ID: <j4hrlv$nur$1@dough.gmane.org> On 11/09/11 06:19, Alejandro Companioni wrote: > I had the same thoughts at first: OS X is just BSD! This can't be too > different from a Linux installation, right? > > There are a number of problems with mysql-python--chiefly its poor > maintenance. I'll link to a nine (!) step guide on installing > mysql-python on Mac as an example: > > http://friendlybit.com/tutorial/install-mysql-python-on-mac-os-x-leopard/ > Hmm, That's not really that difficult, about the same as on any standard Unix system. I guess its much harder than the usual MacOS install though, so for a Mac user would seem pretty bad. > At Step 9 the author suggests using setuptools even though it will fail, > and you'd actually have to patch a (old, well-documented) bug yourself. Yeah, but he could have shortened it slightly by telling you about the types.h bug at step 7 rather than wait till it failed!... But its a pity they MySQL folks haven't fixed that yet. Then it would only have been a 7 step process. Also I suspect you don't really need to download the full Developers Tools(XCode) you could probably just use the gcc compiler which is much smaller from Macports or Fink. OTOH IF you are using Python on a Mac then using XCode as your IDE is a good idea! Especially if you want to write Mac GUIs. And if you already had XCode installed then the process would go dowen to 5 steps... And as one commentator said the Developer tools are on the MacOS DVD, you don't need to download them and register on the site (although that's a good idea too) > ....Not a good start for a new Python coder, I can see it might be intimidating to a Mac user trying to get into programming. But OTOH wouldn't setting up a Linux VM be even more steps? But sadly as a programmer that kind of installation routine is fairly normal(*). Developers are expected to be fairly savvy about how their computer works so slick installation tools are rarely a high priority... And in fact some developers don't like fancy installers that do all the setup for them because they have set up their machines "just so" for their own ends and want complete control. You can't please everyone... (*)I once worked on a project that required Oracle 6 to be installed on our Sun server and after two days I got it working. I then documented the process for the rest of the team. It was 22 steps and even after doing it a half dozen times it still took several hours to complete. Thankfully Oracle have improved their installers nowadays! :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From rdmoores at gmail.com Mon Sep 12 05:02:56 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Sun, 11 Sep 2011 20:02:56 -0700 Subject: [Tutor] About installing 3.2.2 In-Reply-To: <CALMxxxnZx3oEEo_2svB91TiO8Bed6WW_qO0LMfaKj3zDGDYH9Q@mail.gmail.com> References: <CALMxxx=qfiP4_a37Tq6KbNH2j5sJ==Me+At-VbtYF7Z07m33GQ@mail.gmail.com> <CALMxxxkDqAzc-WxAx4aZv+=ENNc3MwSD3O_k-Z0tzip67HDQAw@mail.gmail.com> <CALMxxxnZx3oEEo_2svB91TiO8Bed6WW_qO0LMfaKj3zDGDYH9Q@mail.gmail.com> Message-ID: <CALMxxxmzneoCP4fxRRPbMCv5nLuWmyd68pk9b8D0qk6WCBjx8A@mail.gmail.com> Win 7, Python 3.2.1 I had downloaded python-3.2.2.amd64.msi and started the installation when I saw the attached. Does it mean that I would lose everything in the site-packages folder? Is this something even the Python newbie is supposed to know? Thanks, Dick Moores -------------- next part -------------- A non-text attachment was scrubbed... Name: Python3.2.2Setup3.jpg Type: image/jpeg Size: 19863 bytes Desc: not available URL: <http://mail.python.org/pipermail/tutor/attachments/20110911/2d88d7a8/attachment.jpg> From rdmoores at gmail.com Mon Sep 12 07:29:30 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Sun, 11 Sep 2011 22:29:30 -0700 Subject: [Tutor] Can't edit a file I've opened with open(), then closed with close() Message-ID: <CALMxxxmadVGjRNcjkxxXwzefUOG9afqajW7DYA1ci884iYArsg@mail.gmail.com> Win 7, Python 3.2.1 I'm trying to improve my skills with opening text files, reading from them, and writing to them. But while I'm doing this sometimes I want to manually modify the text file I'm using, C:\t\text.txt . Say I've done this: >>> f = open(r"C:\t\test.txt", 'r+') >>> f.read() '0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19Now is the time for all goo men\nto come to the aid\nof their party.\n' >>> f.close() >>> and I decide to manually delete all those integers, and also correct "goo". So I open test.txt and do that. But when I try to save, I get "The process cannot access the file because it is being used by another process." I'm using IDLE, so I close it. But still no save. Why? And what can I do about it? I check with the task manager and see 22 pythonw.exe processes.. Thanks, Dick Moores -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110911/bf26b96c/attachment-0001.html> From d at davea.name Mon Sep 12 13:51:51 2011 From: d at davea.name (Dave Angel) Date: Mon, 12 Sep 2011 07:51:51 -0400 Subject: [Tutor] Can't edit a file I've opened with open(), then closed with close() In-Reply-To: <CALMxxxmadVGjRNcjkxxXwzefUOG9afqajW7DYA1ci884iYArsg@mail.gmail.com> References: <CALMxxxmadVGjRNcjkxxXwzefUOG9afqajW7DYA1ci884iYArsg@mail.gmail.com> Message-ID: <4E6DF257.6060801@davea.name> On 09/12/2011 01:29 AM, Richard D. Moores wrote: > Win 7, Python 3.2.1 > > I'm trying to improve my skills with opening text files, reading from them, > and writing to them. > > But while I'm doing this sometimes I want to manually modify the text file > I'm using, C:\t\text.txt . Say I've done this: > >>>> f = open(r"C:\t\test.txt", 'r+') >>>> f.read() > '0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19Now is > the time for all goo men\nto come to the aid\nof their party.\n' >>>> f.close() >>>> > and I decide to manually delete all those integers, and also correct "goo". > So I open test.txt and do that. But when I try to save, I get "The process > cannot access the file because it is being used by another process." I'm > using IDLE, so I close it. But still no save. Why? And what can I do about > it? I check with the task manager and see 22 pythonw.exe processes.. > > Thanks, > > Dick Moores > Nothing wrong with the program as you show it. Once it you've entered the close(), it should release the file so a text editor can work on it. However, I notice you're doing this interactively. So probably in one of the many sessions you DIDN'T close it. Or you used the wrong variable to try to close it. Until that shell is closed, it'll prevent anyone else from writing to the file. Each of those pythonw processes is a potential problem. One of them is presumably holding onto the file. Sysinternals has a number of utilities to help track down problems like that. However, in this case, you probably don' t care which process it is, just close them all from the task manager. If you did, the utility 'handle' would probably identify which process it was. Sysinternals, hosted here: http://technet.microsoft.com/en-us/sysinternals/default.aspx handle is here: http://technet.microsoft.com/en-us/sysinternals/bb795533Sy -- DaveA From ramit.prasad at jpmorgan.com Mon Sep 12 15:43:50 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Mon, 12 Sep 2011 09:43:50 -0400 Subject: [Tutor] databases In-Reply-To: <j4hrlv$nur$1@dough.gmane.org> References: <mailman.4370.1315704541.27777.tutor@python.org> <1901FF48-1741-42AA-B37A-588FD449CC83@gmail.com> <j4hrlv$nur$1@dough.gmane.org> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16A197FB@EMARC112VS01.exchad.jpmchase.net> > Also I suspect you don't really need to download the full Developers >Tools(XCode) you could probably just use the gcc compiler which >is much smaller from Macports or Fink. The last I checked, Macports required XCode compiler to build/install itself (and requires XCode to be updated on OS upgrade). This might have changed. I have never used Fink, so not sure if that is different. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From ramit.prasad at jpmorgan.com Mon Sep 12 15:48:44 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Mon, 12 Sep 2011 09:48:44 -0400 Subject: [Tutor] About installing 3.2.2 In-Reply-To: <CALMxxxmzneoCP4fxRRPbMCv5nLuWmyd68pk9b8D0qk6WCBjx8A@mail.gmail.com> References: <CALMxxx=qfiP4_a37Tq6KbNH2j5sJ==Me+At-VbtYF7Z07m33GQ@mail.gmail.com> <CALMxxxkDqAzc-WxAx4aZv+=ENNc3MwSD3O_k-Z0tzip67HDQAw@mail.gmail.com> <CALMxxxnZx3oEEo_2svB91TiO8Bed6WW_qO0LMfaKj3zDGDYH9Q@mail.gmail.com> <CALMxxxmzneoCP4fxRRPbMCv5nLuWmyd68pk9b8D0qk6WCBjx8A@mail.gmail.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16A19816@EMARC112VS01.exchad.jpmchase.net> -----Original Message----- From: tutor-bounces+ramit.prasad=jpmorgan.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of Richard D. Moores Sent: Sunday, September 11, 2011 10:03 PM To: Tutor List Subject: [Tutor] About installing 3.2.2 Win 7, Python 3.2.1 I had downloaded python-3.2.2.amd64.msi and started the installation when I saw the attached. Does it mean that I would lose everything in the site-packages folder? Is this something even the Python newbie is supposed to know? Thanks, Dick Moores ============================= I would think not. The message leads me to think it will update an existing Python install but not in a delete-replace manner. You could always test it by copying the directory or creating a zip of it, update, and see if the site-packages folder has been modified. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From susana.delgado_s at utzmg.edu.mx Mon Sep 12 16:49:25 2011 From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez) Date: Mon, 12 Sep 2011 09:49:25 -0500 Subject: [Tutor] Unusual pathfile Message-ID: <CAFEP6HtuBrHnK3P1zXzneEhO1WMp-yj-EVV+2A6gD0N70=mVCQ@mail.gmail.com> Hi! I developed a python gui module to make a walk through a directory. This time I want the user to select the parameters I need from the python gui. The results will be written in a csv file, the problem I found is the pathfile shows this way: C:/\Archivos de programa\FWTools2.4.7\bin\mapnik-0.7.1\demo\data I'm workin with Python 2.6.6 and Windows XP, the code is: from Tkinter import * #Llamo las librerias graficas de Tk import tkSimpleDialog #Libreria de almacenamiento de dialogos import tkMessageBox #Libreria de mensajes import tkFileDialog import sys, os, csv, time, socket, stat from osgeo import ogr,gdal,osr from osgeo.gdalconst import * from PIL import Image dir = "" extn = "" csv_name = "" def directorio(): global dir print 'Seleccione directorio donde empezar' dirname = tkFileDialog.askdirectory(parent=root,initialdir="/",title='Selecciona la ruta a escanear') if len(dirname ) > 0: print "You chose %s" % dirname dir = dirname def extension(): global extn print "Escribe la extension que necesitas buscar" ext=tkSimpleDialog.askstring('Extension a buscar:','') print 'Buscando archivos: ',ext extn = ext def csv_w(): global csv_name print "Nombre del csv a crear" inv=tkSimpleDialog.askstring('Nombre de .csv:','') print 'Archivo de salidad: ',inv csv_name = inv def boton4(): print 'Iniciando...' gdal.AllRegister() file_list = [] folders = None for root, folders, files in os.walk(dir): file_list.extend(os.path.join(root,fi) for fi in files if fi.endswith(extn)) f = open(csv_name, 'wb') log = open ('log_errores.txt','w') writer = csv.writer(f) ruta = 'Ruta' archivo = 'archivo' x_min = 'x_min' x_max = 'x_max' y_min = 'y_min' y_max = 'y_max' geometria = 'geometria' num_elem = 'num_elem' prj = '.prj' proyeccion = 'proyeccion' fecha = 'fecha_modificacion' creacion = 'fecha_creacion' ultimo = 'ultimo_acceso' tamanio = 'tamanio_aprox' maq = 'maquina_host' usu = 'usuario' campos = [ruta,archivo,x_min,x_max,y_min,y_max,geometria,num_elem,prj,proyeccion,creacion,fecha,ultimo,tamanio,maq,usu] writer.writerow(campos) for row, filepath in enumerate(file_list, start=1): directorio = os.path.dirname(filepath) filename = os.path.basename(filepath) shapeData = ogr.Open(filepath) shp = 'Error al abrir el archivo' +filepath if shapeData is None: print shp log.write(shp+"\n") I don't want to get filepath order -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110912/9d4b5750/attachment.html> From alan.gauld at btinternet.com Mon Sep 12 21:05:27 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 12 Sep 2011 20:05:27 +0100 Subject: [Tutor] Unusual pathfile In-Reply-To: <CAFEP6HtuBrHnK3P1zXzneEhO1WMp-yj-EVV+2A6gD0N70=mVCQ@mail.gmail.com> References: <CAFEP6HtuBrHnK3P1zXzneEhO1WMp-yj-EVV+2A6gD0N70=mVCQ@mail.gmail.com> Message-ID: <j4lkvq$v0t$1@dough.gmane.org> On 12/09/11 15:49, Susana Iraiis Delgado Rodriguez wrote: > Hi! > I developed a python gui module to make a walk through a directory. This > time I want the user to select the parameters I need from the python > gui. The results will be written in a csv file, the problem I found is > the pathfile shows this way: > C:/\Archivos de programa\FWTools2.4.7\bin\mapnik-0.7.1\demo\data What exactly do you feel is wrong with that? Is it the fact that the first slash after the colon is forward facing? Or is there something else? > I'm workin with Python 2.6.6 and Windows XP, the code is: Could you please use a few more spaces. Both to indent the code (2 spaces ids really the minimum and 3 or 4 is normal. But one is useless) and to separate the functions vertically. (ie a blank line before the def statements) It is really very hard work wading through this stuff! I don't know how you can read it but I'm struggling to see the structure. > from Tkinter import * #Llamo las librerias graficas de Tk > import tkSimpleDialog #Libreria de almacenamiento de dialogos > import tkMessageBox #Libreria de mensajes > import tkFileDialog > import sys, os, csv, time, socket, stat > from osgeo import ogr,gdal,osr > from osgeo.gdalconst import * > from PIL import Image > dir = "" > extn = "" > csv_name = "" > def directorio(): > global dir > print 'Seleccione directorio donde empezar' > dirname = > tkFileDialog.askdirectory(parent=root,initialdir="/",title='Selecciona > la ruta a escanear') > if len(dirname ) > 0: > print "You chose %s" % dirname > dir = dirname > def extension(): > global extn > print "Escribe la extension que necesitas buscar" > ext=tkSimpleDialog.askstring('Extension a buscar:','') > print 'Buscando archivos: ',ext > extn = ext > def csv_w(): > global csv_name > print "Nombre del csv a crear" > inv=tkSimpleDialog.askstring('Nombre de .csv:','') > print 'Archivo de salidad: ',inv > csv_name = inv > def boton4(): > print 'Iniciando...' > gdal.AllRegister() > file_list = [] > folders = None > for root, folders, files in os.walk(dir): > file_list.extend(os.path.join(root,fi) for fi in files if > fi.endswith(extn)) > f = open(csv_name, 'wb') > log = open ('log_errores.txt','w') > writer = csv.writer(f) > ruta = 'Ruta' > archivo = 'archivo' > x_min = 'x_min' > x_max = 'x_max' > y_min = 'y_min' > y_max = 'y_max' > geometria = 'geometria' > num_elem = 'num_elem' > prj = '.prj' > proyeccion = 'proyeccion' > fecha = 'fecha_modificacion' > creacion = 'fecha_creacion' > ultimo = 'ultimo_acceso' > tamanio = 'tamanio_aprox' > maq = 'maquina_host' > usu = 'usuario' > campos = > [ruta,archivo,x_min,x_max,y_min,y_max,geometria,num_elem,prj,proyeccion,creacion,fecha,ultimo,tamanio,maq,usu] > writer.writerow(campos) > for row, filepath in enumerate(file_list, start=1): > directorio = os.path.dirname(filepath) > filename = os.path.basename(filepath) > shapeData = ogr.Open(filepath) > shp = 'Error al abrir el archivo' +filepath > if shapeData is None: > print shp > log.write(shp+"\n") > I don't want to get filepath order I don't understand what that means? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From nitinchandra1 at gmail.com Mon Sep 12 21:15:22 2011 From: nitinchandra1 at gmail.com (nitin chandra) Date: Tue, 13 Sep 2011 00:45:22 +0530 Subject: [Tutor] Calendar Message-ID: <CAFSKaexfCfNjYNMWYXYaQ3ZMHBEXw3HjaUoB7jXsADvdE73gZA@mail.gmail.com> Hi All, I need to create a calendar with python & CSS for the web page, in the following format Dec , 2011 ------------------------------------------------------------------------------------------------- sun | mon | tue | wed thu fri sat sun mon tue wed thu fri sat sun -------|-----------|----------|---------------------------------------------------------------------- 1 | 2 | 3 | 4 5 6 7 8 9 10 11 12 13 14 15 -------|-----------|----------|----------------------------------------------------------------------- img1 | img2 | img3 | .... Jan , 2012 ------------------------------------------------------------------------------------------------- sun | mon | tue | wed thu fri sat sun mon tue wed thu fri sat sun -------|-----------|----------|---------------------------------------------------------------------- 1 | 2 | 3 | 4 5 6 7 8 9 10 11 12 13 14 15 -------|-----------|----------|----------------------------------------------------------------------- img1 | img2 | img3 | .... Feb , 2012 ------------------------------------------------------------------------------------------------- sun | mon | tue | wed thu fri sat sun mon tue wed thu fri sat sun -------|-----------|----------|---------------------------------------------------------------------- 1 | 2 | 3 | 4 5 6 7 8 9 10 11 12 13 14 15 -------|-----------|----------|----------------------------------------------------------------------- img1 | img2 | img3 | .... Can some one please show me how to do the above ? Thanks Nitin From spawgi at gmail.com Mon Sep 12 21:33:09 2011 From: spawgi at gmail.com (spawgi at gmail.com) Date: Tue, 13 Sep 2011 01:03:09 +0530 Subject: [Tutor] Calendar In-Reply-To: <CAFSKaexfCfNjYNMWYXYaQ3ZMHBEXw3HjaUoB7jXsADvdE73gZA@mail.gmail.com> References: <CAFSKaexfCfNjYNMWYXYaQ3ZMHBEXw3HjaUoB7jXsADvdE73gZA@mail.gmail.com> Message-ID: <CACPRw_w7Wwf5DqB05U=4nwFKVicx0JhMx-HCkv0NfMo3uMBm5Q@mail.gmail.com> If you want to create a calendar for a webpage, I think you can use many ready made JS packages for this. May be jquery also has something. Is using Python mandatory for this task? And why? On Tue, Sep 13, 2011 at 12:45 AM, nitin chandra <nitinchandra1 at gmail.com>wrote: > Hi All, > > I need to create a calendar with python & CSS for the web page, in the > following format > > Dec , 2011 > > ------------------------------------------------------------------------------------------------- > sun | mon | tue | wed thu fri sat sun mon tue wed thu fri sat > sun > > -------|-----------|----------|---------------------------------------------------------------------- > 1 | 2 | 3 | 4 5 6 7 8 9 10 11 > 12 13 14 15 > > -------|-----------|----------|----------------------------------------------------------------------- > img1 | img2 | img3 | .... > > Jan , 2012 > > ------------------------------------------------------------------------------------------------- > sun | mon | tue | wed thu fri sat sun mon tue wed thu fri sat > sun > > -------|-----------|----------|---------------------------------------------------------------------- > 1 | 2 | 3 | 4 5 6 7 8 9 10 11 > 12 13 14 15 > > -------|-----------|----------|----------------------------------------------------------------------- > img1 | img2 | img3 | .... > > Feb , 2012 > > ------------------------------------------------------------------------------------------------- > sun | mon | tue | wed thu fri sat sun mon tue wed thu fri sat > sun > > -------|-----------|----------|---------------------------------------------------------------------- > 1 | 2 | 3 | 4 5 6 7 8 9 10 11 > 12 13 14 15 > > -------|-----------|----------|----------------------------------------------------------------------- > img1 | img2 | img3 | .... > > > Can some one please show me how to do the above ? > > Thanks > > Nitin > _______________________________________________ > 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: <http://mail.python.org/pipermail/tutor/attachments/20110913/9ec271e4/attachment.html> From sander.sweers at gmail.com Mon Sep 12 23:21:34 2011 From: sander.sweers at gmail.com (Sander Sweers) Date: Mon, 12 Sep 2011 23:21:34 +0200 Subject: [Tutor] Calendar In-Reply-To: <CAFSKaexfCfNjYNMWYXYaQ3ZMHBEXw3HjaUoB7jXsADvdE73gZA@mail.gmail.com> References: <CAFSKaexfCfNjYNMWYXYaQ3ZMHBEXw3HjaUoB7jXsADvdE73gZA@mail.gmail.com> Message-ID: <4E6E77DE.3040602@gmail.com> On 12/09/11 21:15, nitin chandra wrote: > I need to create a calendar with python& CSS for the web page, in the > following format > > Dec , 2011 > ------------------------------------------------------------------------------------------------- > sun | mon | tue | wed thu fri sat sun mon tue wed thu fri sat sun > -------|-----------|----------|---------------------------------------------------------------------- > 1 | 2 | 3 | 4 5 6 7 8 9 10 11 > 12 13 14 15 > -------|-----------|----------|----------------------------------------------------------------------- > img1 | img2 | img3 | .... > > Jan , 2012 > ------------------------------------------------------------------------------------------------- > sun | mon | tue | wed thu fri sat sun mon tue wed thu fri sat sun > -------|-----------|----------|---------------------------------------------------------------------- > 1 | 2 | 3 | 4 5 6 7 8 9 10 11 > 12 13 14 15 > -------|-----------|----------|----------------------------------------------------------------------- > img1 | img2 | img3 | .... > > Feb , 2012 > ------------------------------------------------------------------------------------------------- > sun | mon | tue | wed thu fri sat sun mon tue wed thu fri sat sun > -------|-----------|----------|---------------------------------------------------------------------- > 1 | 2 | 3 | 4 5 6 7 8 9 10 11 > 12 13 14 15 > -------|-----------|----------|----------------------------------------------------------------------- > img1 | img2 | img3 | .... > > > Can some one please show me how to do the above ? Have a look at the calendar module. A quick google search I also found [1] which does all the bits you just need to adapt it for your needs. Greets Sander From nitinchandra1 at gmail.com Tue Sep 13 07:02:34 2011 From: nitinchandra1 at gmail.com (nitin chandra) Date: Tue, 13 Sep 2011 10:32:34 +0530 Subject: [Tutor] Calendar In-Reply-To: <4E6E77DE.3040602@gmail.com> References: <CAFSKaexfCfNjYNMWYXYaQ3ZMHBEXw3HjaUoB7jXsADvdE73gZA@mail.gmail.com> <4E6E77DE.3040602@gmail.com> Message-ID: <CAFSKaeyfo0jsf4+zvo1hwSx-gcPM=rnkjwzq_Zwu7tqu6n-QMg@mail.gmail.com> I tried it in the following way, but beyond that i am not able to go. #!/usr/bin/env python import os, re, sys, calendar from datetime import datetime myCal = calendar.monthcalendar(2011,9) html += str(myCal) mycal = myCal[:1] cal1 = myCal[1:2] cal2 = myCal[2:3] cal3 = myCal[3:4] cal4 = myCal[4:5] html += str(mycal)+'<br>' html += str(cal1)+'<br>' html += str(cal2)+'<br>' html += str(cal3)+'<br>' html += str(cal4)+'<br>' html += "<br>" This is the following output ? which I need in the above format: [[0, 0, 0, 1, 2, 3, 4]] [[5, 6, 7, 8, 9, 10, 11]] [[12, 13, 14, 15, 16, 17, 18]] [[19, 20, 21, 22, 23, 24, 25]] [[26, 27, 28, 29, 30, 0, 0]] How do I proceed, or is there another way? Thanks From rdmoores at gmail.com Tue Sep 13 08:43:34 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Mon, 12 Sep 2011 23:43:34 -0700 Subject: [Tutor] need advice about a dictionary ({}) In-Reply-To: <CAKK8jXYiADt=W9J6_qvH4TDsSw573vmCiQnAPVYEBgWDFpKWnQ@mail.gmail.com> References: <CALMxxxm2fA_Yo4bQMRHznYXBFZwD03ze-mXo1WeY7VkfM+1J9w@mail.gmail.com> <j4a9p1$a4$1@dough.gmane.org> <CALMxxxmYnzRxSbrgY3hdu-fkpAHGzEgpYTGDjsNPN=c4XqEZyw@mail.gmail.com> <CALMxxxmfW=vX8Of551_vpNT9HVYjg7x=CSj3EDpJ=D85NjxPnw@mail.gmail.com> <j4gock$ld6$1@dough.gmane.org> <CALMxxxmDhCGPhJ0i+BOKHqRLpLqTPeoHiG_4q9Ouk-dUXjBqRg@mail.gmail.com> <CAKK8jXYiADt=W9J6_qvH4TDsSw573vmCiQnAPVYEBgWDFpKWnQ@mail.gmail.com> Message-ID: <CALMxxxmOCv7jCOX2fYdwYYUGGPySSwjqO0-yLVo1z70f8j44QA@mail.gmail.com> I'm the OP. Nick Zarr, alias Jack Trades, has done something really marvelous. He's made a thorough critique and refactoring of my phone_book.py, in its last incarnation as <http://pastebin.com/2wm4Vf1P>. See <https://gist.github.com/1212290>. He'll be making that part of his blog (<http://pointlessprogramming.wordpress.com/>), and may turn it into an article. Dick From rdmoores at gmail.com Tue Sep 13 08:49:31 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Mon, 12 Sep 2011 23:49:31 -0700 Subject: [Tutor] About installing 3.2.2 In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16A19816@EMARC112VS01.exchad.jpmchase.net> References: <CALMxxx=qfiP4_a37Tq6KbNH2j5sJ==Me+At-VbtYF7Z07m33GQ@mail.gmail.com> <CALMxxxkDqAzc-WxAx4aZv+=ENNc3MwSD3O_k-Z0tzip67HDQAw@mail.gmail.com> <CALMxxxnZx3oEEo_2svB91TiO8Bed6WW_qO0LMfaKj3zDGDYH9Q@mail.gmail.com> <CALMxxxmzneoCP4fxRRPbMCv5nLuWmyd68pk9b8D0qk6WCBjx8A@mail.gmail.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16A19816@EMARC112VS01.exchad.jpmchase.net> Message-ID: <CALMxxxmdNRFe2ZPn2QP8wWWxW_fBbg2hLR3P5ydAzYrqczSYBw@mail.gmail.com> On Mon, Sep 12, 2011 at 06:48, Prasad, Ramit <ramit.prasad at jpmorgan.com> wrote: > -----Original Message----- > From: tutor-bounces+ramit.prasad=jpmorgan.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of Richard D. Moores > Sent: Sunday, September 11, 2011 10:03 PM > To: Tutor List > Subject: [Tutor] About installing 3.2.2 > > Win 7, Python 3.2.1 > > I had downloaded python-3.2.2.amd64.msi and started the installation when I saw the attached. Does it mean that I would lose everything in the site-packages folder? Is this something even the Python newbie is supposed to know? > > Thanks, > > Dick Moores > ============================= > > > I would think not. The message leads me to think it will update an existing Python install but not in a delete-replace manner. You could always test it by copying the directory or creating a zip of it, update, and see if the site-packages folder has been modified. > > > Ramit Thanks, Ramit. I didn't see your reply until just now. I'll follow your advice. Dick From rdmoores at gmail.com Tue Sep 13 09:21:15 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Tue, 13 Sep 2011 00:21:15 -0700 Subject: [Tutor] About installing 3.2.2 In-Reply-To: <CALMxxxmdNRFe2ZPn2QP8wWWxW_fBbg2hLR3P5ydAzYrqczSYBw@mail.gmail.com> References: <CALMxxx=qfiP4_a37Tq6KbNH2j5sJ==Me+At-VbtYF7Z07m33GQ@mail.gmail.com> <CALMxxxkDqAzc-WxAx4aZv+=ENNc3MwSD3O_k-Z0tzip67HDQAw@mail.gmail.com> <CALMxxxnZx3oEEo_2svB91TiO8Bed6WW_qO0LMfaKj3zDGDYH9Q@mail.gmail.com> <CALMxxxmzneoCP4fxRRPbMCv5nLuWmyd68pk9b8D0qk6WCBjx8A@mail.gmail.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16A19816@EMARC112VS01.exchad.jpmchase.net> <CALMxxxmdNRFe2ZPn2QP8wWWxW_fBbg2hLR3P5ydAzYrqczSYBw@mail.gmail.com> Message-ID: <CALMxxxmrSTtZOf_twQgkCPK4Zd_sFbZqEU9xBNyepX2K+Zsj4g@mail.gmail.com> On Mon, Sep 12, 2011 at 23:49, Richard D. Moores <rdmoores at gmail.com> wrote: > On Mon, Sep 12, 2011 at 06:48, Prasad, Ramit <ramit.prasad at jpmorgan.com> wrote: >> -----Original Message----- >> From: tutor-bounces+ramit.prasad=jpmorgan.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of Richard D. Moores >> Sent: Sunday, September 11, 2011 10:03 PM >> To: Tutor List >> Subject: [Tutor] About installing 3.2.2 >> >> Win 7, Python 3.2.1 >> >> I had downloaded python-3.2.2.amd64.msi and started the installation when I saw the attached. Does it mean that I would lose everything in the site-packages folder? Is this something even the Python newbie is supposed to know? >> >> Thanks, >> >> Dick Moores >> ============================= >> >> >> I would think not. The message leads me to think it will update an existing Python install but not in a delete-replace manner. You could always test it by copying the directory or creating a zip of it, update, and see if the site-packages folder has been modified. >> >> >> Ramit > > Thanks, Ramit. I didn't see your reply until just now. I'll follow your advice. The installation didn't NOT disturb anything in the site-packages folder, exactly as Ramit surmised. Dick From susana.delgado_s at utzmg.edu.mx Tue Sep 13 17:41:26 2011 From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez) Date: Tue, 13 Sep 2011 10:41:26 -0500 Subject: [Tutor] Unusual pathfile In-Reply-To: <j4lkvq$v0t$1@dough.gmane.org> References: <CAFEP6HtuBrHnK3P1zXzneEhO1WMp-yj-EVV+2A6gD0N70=mVCQ@mail.gmail.com> <j4lkvq$v0t$1@dough.gmane.org> Message-ID: <CAFEP6HvmfmEfsm8w5+g-95iZuDnZPcbiFJVV0crtzeqEWVeR_A@mail.gmail.com> Hi! I just want to look the pathfile like this: C:\Python26 instead of C:/\Python26, I feel the loop repeats its walking with this pathfile structure. About the indention for the code, I tried my best to make it clear ande neat. But the mi e-mail editor it's mixing-up spaces. Here's again: from Tkinter import * #Llamo las librerias graficas de Tk import tkSimpleDialog #Libreria de almacenamiento de dialogos import tkMessageBox #Libreria de mensajes import tkFileDialog import sys, os, csv, time, socket, stat from osgeo import ogr,gdal,osr from osgeo.gdalconst import * from PIL import Image dir = "" extn = "" csv_name = "" filesystemencoding = sys.getfilesystemencoding() def directorio(): global dir print 'Seleccione directorio donde empezar' dirname1 = tkFileDialog.askdirectory(parent=root,initialdir="/",title='Selecciona la ruta a escanear') if len(dirname1 ) > 0: print "You chose %s" % dirname1 dir = dirname1 def extension(): global extn print "Escribe la extension que necesitas buscar" ext=tkSimpleDialog.askstring('Extension a buscar:','') print 'Buscando archivos: ',ext extn = ext def csv_w(): global csv_name print "Nombre del csv a crear" inv=tkSimpleDialog.askstring('Nombre de .csv:','') print 'Archivo de salidad: ',inv csv_name = inv def buscar(): print 'Iniciando...' gdal.AllRegister() file_list = [] folders = None for root, folders, files in os.walk(dir): file_list.extend(os.path.join(root,fi) for fi in files if fi.endswith(extn)) f = open(csv_name, 'wb') log = open ('log_errores.txt','w') writer = csv.writer(f) ruta = 'Ruta' archivo = 'archivo' x_min = 'x_min' x_max = 'x_max' y_min = 'y_min' y_max = 'y_max' geometria = 'geometria' num_elem = 'num_elem' prj = '.prj' proyeccion = 'proyeccion' fecha = 'fecha_modificacion' creacion = 'fecha_creacion' ultimo = 'ultimo_acceso' tamanio = 'tamanio_aprox' maq = 'maquina_host' usu = 'usuario' campos = [ruta,archivo,x_min,x_max,y_min,y_max,geometria,num_elem,prj,proyeccion,creacion,fecha,ultimo,tamanio,maq,usu] writer.writerow(campos) for row, filepath in enumerate(file_list, start=1): directorio = os.path.dirname(filepath) filename = os.path.basename(filepath) #shapeData = ogr.Open(filepath) shapeData = ogr.Open(filepath.encode(filesystemencoding)) if shapeData is None: shp = 'Error al abrir el archivo ' + filepath.encode(filesystemencoding) print shp log.write(shp+"\n") else: print 'Trabajando en: ' +filepath layer = shapeData.GetLayer() feature = layer.GetNextFeature() x_y = layer.GetExtent() #x_min x1 = x_y[0] #x_max x2 = x_y[1] #y_min y1 = x_y[2] #y_max y2 = x_y[3] #Escribir el tipo de geometria del shp. 1=Point, 2=LineString, 3=Polygon defn = layer.GetLayerDefn() geo = defn.GetGeomType() #Comenzar el featurecount() cuenta = layer.GetFeatureCount() proy = layer.GetSpatialRef() prjtext = ''+str(proy)+'' ### n = os.path.splitext(filepath) p = n[0]+'.prj' shx = n[0]+'.shx' #shx_msj = 'Error al abrir el archivo' +shx dbf = n[0]+'.dbf' #dbf_msj = 'Error al abrir el archivo' +dbf filepath = ''+filepath+'' filename = ''+filename+'' t = time.strftime("%m/%d/%Y %I:%M:%S %p",time.localtime(os.path.getmtime(filepath))) modificacion = ''+t+'' crdt = time.strftime("%m/%d/%Y %I:%M:%S %p",time.localtime(os.path.getctime(filepath))) crea = ''+crdt+'' lt_acc = time.strftime("%m/%d/%Y %I:%M:%S %p",time.localtime(os.path.getatime(filepath))) acceso = ''+lt_acc+'' s = os.path.getsize(filepath) def sizeof_fmt(num): for x in ['bytes','KB','MB','GB','TB']: if num < 1024.0: return "%3.1f%s" % (num, x) num /= 1024.0 #Obtener usuario usuario = os.environ.get("USERNAME") user = ''+usuario+'' host = socket.gethostname() maquina = ''+host+'' if os.path.exists(shx): print '.' shx1 = os.path.getsize(shx) #kb2 = sizeof_fmt(shx1) else: log.write('No existe el archivo ' +shx+"\n") if os.path.exists(dbf): print '.' else: log.write('No existe el archivo ' +dbf+"\n") if os.path.exists(p): #Si existe, asignar 1 p1 = os.path.getsize(p) total = sizeof_fmt(s+shx1+p1) aRow= [ directorio, filename, x1, x2, y1, y2, geo, cuenta, 1, prjtext, crea, modificacion, acceso, total, maquina, user] writer.writerow(aRow) else: #Sino asignar 0 #no_prj = 'Sin prj, no se puede determinar la proyeccion' total = sizeof_fmt(s+shx1) aRow1= [ directorio, filename, x1, x2, y1, y2, geo, cuenta, 0, prjtext, crea, modificacion, acceso, total, maquina, user] writer.writerow(aRow1) log.close() f.close() print "El archivo esta listo" root = Tk() top = Toplevel() #Llamo una nueva ventana #Dimensiones de la ventana root.minsize(400,200) #Barra de herramientas toolbar = Frame(root) #Botones b = Button(toolbar, text="Selecciona ruta", width=15, command=directorio) b.pack(side=LEFT, padx=2, pady=2) b = Button(toolbar, text="Escriba extension", width=15, command=extension) b.pack(side=LEFT, padx=2, pady=2) b = Button(toolbar, text="Nombre de csv", width=15, command=csv_w) b.pack(side=LEFT, padx=2, pady=2) b = Button(toolbar, text="Aceptar", width=6, command=buscar) b.pack(side=LEFT, padx=2, pady=2) toolbar.pack(side=TOP, fill=X) root.mainloop() 2011/9/12 Alan Gauld <alan.gauld at btinternet.com> > On 12/09/11 15:49, Susana Iraiis Delgado Rodriguez wrote: > >> Hi! >> I developed a python gui module to make a walk through a directory. This >> time I want the user to select the parameters I need from the python >> gui. The results will be written in a csv file, the problem I found is >> the pathfile shows this way: >> C:/\Archivos de programa\FWTools2.4.7\bin\**mapnik-0.7.1\demo\data >> > > What exactly do you feel is wrong with that? > Is it the fact that the first slash after the colon is forward facing? > Or is there something else? > > > I'm workin with Python 2.6.6 and Windows XP, the code is: >> > > Could you please use a few more spaces. Both to indent the code (2 spaces > ids really the minimum and 3 or 4 is normal. But one is > useless) and to separate the functions vertically. (ie a blank line before > the def statements) > > It is really very hard work wading through this stuff! I don't know how you > can read it but I'm struggling to see the structure. > > > > from Tkinter import * #Llamo las librerias graficas de Tk >> import tkSimpleDialog #Libreria de almacenamiento de dialogos >> import tkMessageBox #Libreria de mensajes >> import tkFileDialog >> import sys, os, csv, time, socket, stat >> from osgeo import ogr,gdal,osr >> from osgeo.gdalconst import * >> from PIL import Image >> dir = "" >> extn = "" >> csv_name = "" >> > > def directorio(): >> global dir >> print 'Seleccione directorio donde empezar' >> dirname = >> tkFileDialog.askdirectory(**parent=root,initialdir="/",** >> title='Selecciona >> la ruta a escanear') >> if len(dirname ) > 0: >> print "You chose %s" % dirname >> dir = dirname >> > > def extension(): >> global extn >> print "Escribe la extension que necesitas buscar" >> ext=tkSimpleDialog.askstring('**Extension a buscar:','') >> print 'Buscando archivos: ',ext >> extn = ext >> > > def csv_w(): >> global csv_name >> print "Nombre del csv a crear" >> inv=tkSimpleDialog.askstring('**Nombre de .csv:','') >> print 'Archivo de salidad: ',inv >> csv_name = inv >> > > def boton4(): >> print 'Iniciando...' >> gdal.AllRegister() >> file_list = [] >> folders = None >> for root, folders, files in os.walk(dir): >> file_list.extend(os.path.join(**root,fi) for fi in files if >> fi.endswith(extn)) >> f = open(csv_name, 'wb') >> log = open ('log_errores.txt','w') >> writer = csv.writer(f) >> ruta = 'Ruta' >> archivo = 'archivo' >> x_min = 'x_min' >> x_max = 'x_max' >> y_min = 'y_min' >> y_max = 'y_max' >> geometria = 'geometria' >> num_elem = 'num_elem' >> prj = '.prj' >> proyeccion = 'proyeccion' >> fecha = 'fecha_modificacion' >> creacion = 'fecha_creacion' >> ultimo = 'ultimo_acceso' >> tamanio = 'tamanio_aprox' >> maq = 'maquina_host' >> usu = 'usuario' >> campos = >> [ruta,archivo,x_min,x_max,y_**min,y_max,geometria,num_elem,** >> prj,proyeccion,creacion,fecha,**ultimo,tamanio,maq,usu] >> writer.writerow(campos) >> for row, filepath in enumerate(file_list, start=1): >> directorio = os.path.dirname(filepath) >> filename = os.path.basename(filepath) >> shapeData = ogr.Open(filepath) >> shp = 'Error al abrir el archivo' +filepath >> if shapeData is None: >> print shp >> log.write(shp+"\n") >> > > > > I don't want to get filepath order >> > > I don't understand what that means? > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor> > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110913/ad481183/attachment.html> From d at davea.name Tue Sep 13 18:55:04 2011 From: d at davea.name (Dave Angel) Date: Tue, 13 Sep 2011 12:55:04 -0400 Subject: [Tutor] Unusual pathfile In-Reply-To: <CAFEP6HvmfmEfsm8w5+g-95iZuDnZPcbiFJVV0crtzeqEWVeR_A@mail.gmail.com> References: <CAFEP6HtuBrHnK3P1zXzneEhO1WMp-yj-EVV+2A6gD0N70=mVCQ@mail.gmail.com> <j4lkvq$v0t$1@dough.gmane.org> <CAFEP6HvmfmEfsm8w5+g-95iZuDnZPcbiFJVV0crtzeqEWVeR_A@mail.gmail.com> Message-ID: <4E6F8AE8.70300@davea.name> 1. Don't top-post. Put your response after whatever parts of a previous message you're quoting. And delete the parts that are no longer relevant. 2. If you used tabs in your code, convert to spaces before pasting into some email editors. Apparently your email editor is converting the tabs to single spaces. On 09/13/2011 11:41 AM, Susana Iraiis Delgado Rodriguez wrote: > Hi! > I just want to look the pathfile like this: C:\Python26 instead of > C:/\Python26, I feel the loop repeats its walking with this pathfile > structure. > > <SNIP> Try using mypath = os.path.abspath(mypath) No clue what you mean by "repeats its walking" -- DaveA From steve at pearwood.info Tue Sep 13 19:00:50 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 14 Sep 2011 03:00:50 +1000 Subject: [Tutor] Unusual pathfile In-Reply-To: <CAFEP6HvmfmEfsm8w5+g-95iZuDnZPcbiFJVV0crtzeqEWVeR_A@mail.gmail.com> References: <CAFEP6HtuBrHnK3P1zXzneEhO1WMp-yj-EVV+2A6gD0N70=mVCQ@mail.gmail.com> <j4lkvq$v0t$1@dough.gmane.org> <CAFEP6HvmfmEfsm8w5+g-95iZuDnZPcbiFJVV0crtzeqEWVeR_A@mail.gmail.com> Message-ID: <4E6F8C42.4070709@pearwood.info> Susana Iraiis Delgado Rodriguez wrote: > Hi! > I just want to look the pathfile like this: C:\Python26 instead of > C:/\Python26, I feel the loop repeats its walking with this pathfile > structure. About the indention for the code, I tried my best to make it > clear ande neat. But the mi e-mail editor it's mixing-up spaces. > Here's again: Susana, you are showing too much code that is unrelated to your problem. Your problem is that your code gives the wrong result for the file name: you want C:\Python26 but get C:/\Python26. You should isolate the part of your code that produces the path names. We don't need the part that creates buttons, or writes CSV files, or prints messages to the user. As it stands now, I can't even tell which part of the code generates "C:/\Python26", let alone how to fix it. You should have a small function, no more than ten or twenty lines, that handles the path names, and nothing else. -- Steven From susana.delgado_s at utzmg.edu.mx Tue Sep 13 19:12:08 2011 From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez) Date: Tue, 13 Sep 2011 12:12:08 -0500 Subject: [Tutor] Unusual pathfile In-Reply-To: <4E6F8C42.4070709@pearwood.info> References: <CAFEP6HtuBrHnK3P1zXzneEhO1WMp-yj-EVV+2A6gD0N70=mVCQ@mail.gmail.com> <j4lkvq$v0t$1@dough.gmane.org> <CAFEP6HvmfmEfsm8w5+g-95iZuDnZPcbiFJVV0crtzeqEWVeR_A@mail.gmail.com> <4E6F8C42.4070709@pearwood.info> Message-ID: <CAFEP6Hu6+CPjELAGuSN5kDQyY3dwFShHU5kt3BQcBHcpr0hv2Q@mail.gmail.com> I think I've received many complains for my questions and messages, I know you're great programmers and this is for helping beginners or any level of Python users. I tried to correct the code I sent the best I could, than you for your time, I'll try to manage it myself. 2011/9/13 Steven D'Aprano <steve at pearwood.info> > Susana Iraiis Delgado Rodriguez wrote: > >> Hi! >> >> I just want to look the pathfile like this: C:\Python26 instead of >> C:/\Python26, I feel the loop repeats its walking with this pathfile >> structure. About the indention for the code, I tried my best to make it >> clear ande neat. But the mi e-mail editor it's mixing-up spaces. >> Here's again: >> > > Susana, you are showing too much code that is unrelated to your problem. > Your problem is that your code gives the wrong result for the file name: you > want C:\Python26 but get C:/\Python26. > > You should isolate the part of your code that produces the path names. We > don't need the part that creates buttons, or writes CSV files, or prints > messages to the user. As it stands now, I can't even tell which part of the > code generates "C:/\Python26", let alone how to fix it. > > You should have a small function, no more than ten or twenty lines, that > handles the path names, and nothing else. > > > > -- > Steven > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor> > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110913/03058990/attachment.html> From marc.tompkins at gmail.com Tue Sep 13 19:37:58 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 13 Sep 2011 10:37:58 -0700 Subject: [Tutor] Unusual pathfile In-Reply-To: <CAFEP6Hu6+CPjELAGuSN5kDQyY3dwFShHU5kt3BQcBHcpr0hv2Q@mail.gmail.com> References: <CAFEP6HtuBrHnK3P1zXzneEhO1WMp-yj-EVV+2A6gD0N70=mVCQ@mail.gmail.com> <j4lkvq$v0t$1@dough.gmane.org> <CAFEP6HvmfmEfsm8w5+g-95iZuDnZPcbiFJVV0crtzeqEWVeR_A@mail.gmail.com> <4E6F8C42.4070709@pearwood.info> <CAFEP6Hu6+CPjELAGuSN5kDQyY3dwFShHU5kt3BQcBHcpr0hv2Q@mail.gmail.com> Message-ID: <CAKK8jXanFavEK9B9enWJLY_TL2r13KkW0jx2MmQu8hVY4iMEKA@mail.gmail.com> On Tue, Sep 13, 2011 at 10:12 AM, Susana Iraiis Delgado Rodriguez < susana.delgado_s at utzmg.edu.mx> wrote: > I think I've received many complains for my questions and messages, I know > you're great programmers and this is for helping beginners or any level of > Python users. I tried to correct the code I sent the best I could, than you > for your time, I'll try to manage it myself. > Susana - I think I speak for everyone when I say: don't go away! Nobody's complaining about your question; that's what the list is for. However, we're all human beings, and all doing this voluntarily. So it's in your best interest to make your questions easy for us to read. So many lines all run together, with only one space of indentation, makes my head hurt when I try to read it; I'm ashamed to admit that I simply skipped over your question when you first posted it. Others put more effort into it, and have told you why it was hard for them. Don't be offended! At least they took the trouble, which is more than I did. Two things you can do to make this better: - Set your text editor to convert tabs to spaces, preferably four spaces. This is a Good Thing To Do anyway, because some of the hardest bugs to find - for you as well as for us - happen when Python gets confused about levels of indentation. If you're not sure how to change that setting, just tell us which editor you use and someone can help with that. - When you ask a question - and we WANT you to ask questions! - try to narrow down your program to just the part that's giving you trouble. It makes it MUCH easier for us to help you, and quite often it helps you to find the problem yourself. As Steven said above, at the moment I can't even see which part of your code is generating "C:\/Python26", let alone help you to correct it. Just remember: we all want to help; speaking for myself, I started out asking questions on this list and have stuck around to answer them. But we're all human too - and speaking for myself, sometimes we're a little lazy. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110913/e8c8ee94/attachment.html> From di.marvellous at gmail.com Tue Sep 13 19:57:46 2011 From: di.marvellous at gmail.com (Dinara Vakhitova) Date: Tue, 13 Sep 2011 21:57:46 +0400 Subject: [Tutor] cmd window Message-ID: <CABGnxkugAj64iFiUZ9rUc6O9NaG5fZHWJyY6kVrJ4xPL0hm2aw@mail.gmail.com> Hello, Excuse me for my stupid question, but I'm an absolute beginner in programming. I just would like to know what should I do in such case: when I run my program by clicking on the file itself, rather than from IDLE, the cmd window disappears just immediately after the output printing, so that I can't even see it. The solution must be very simple, but I can't find it in tutorials... Thank you! -- *Yours faithfully, Dinara Vakhitova* -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110913/6e9eb87f/attachment.html> From steve at pearwood.info Tue Sep 13 20:20:40 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 14 Sep 2011 04:20:40 +1000 Subject: [Tutor] Unusual pathfile In-Reply-To: <CAFEP6Hu6+CPjELAGuSN5kDQyY3dwFShHU5kt3BQcBHcpr0hv2Q@mail.gmail.com> References: <CAFEP6HtuBrHnK3P1zXzneEhO1WMp-yj-EVV+2A6gD0N70=mVCQ@mail.gmail.com> <j4lkvq$v0t$1@dough.gmane.org> <CAFEP6HvmfmEfsm8w5+g-95iZuDnZPcbiFJVV0crtzeqEWVeR_A@mail.gmail.com> <4E6F8C42.4070709@pearwood.info> <CAFEP6Hu6+CPjELAGuSN5kDQyY3dwFShHU5kt3BQcBHcpr0hv2Q@mail.gmail.com> Message-ID: <4E6F9EF8.8060202@pearwood.info> Susana Iraiis Delgado Rodriguez wrote: > I think I've received many complains for my questions and messages Please don't be upset! We're not angry at your, and we are trying to help you. In English, we have a saying: "Give a man a fish, and you feed him for one day. Teach a man how to catch fish, and you feed him forever." We are happy to help solve your problems, but just as important is to teach you how to solve your problems without our help. Also, sometimes your questions are too hard for us to answer without spending many hours of work. We are volunteers who do this for free. We are not being paid for this. We do this as a way to pay back to the community that helped us when we were beginners. But help has to go both ways: you help us by asking good questions, and we help you by teaching you the answers. Lastly, remember that some of us use Apple Macs, or Linux, and do not have Windows. If this problem is specific to Windows pathnames, it might be impossible for us to help except by guessing. So have patience that we can't solve everything easily. Let us start with a simple part: you have this function: from Tkinter import * root = Tk() import tkFileDialog dir = "" def directorio(): global dir print 'Seleccione directorio donde empezar' dirname1 = tkFileDialog.askdirectory( parent=root, initialdir="/", title='Selecciona la ruta a escanear' ) if len(dirname1 ) > 0: print "You chose %s" % dirname1 dir = dirname1 If I run this function, I get this: >>> directorio() Seleccione directorio donde empezar You chose /usr/bin (I am using Linux, so I have no C: drive.) What do you get if you run it? -- Steven From waynejwerner at gmail.com Tue Sep 13 20:25:05 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Tue, 13 Sep 2011 13:25:05 -0500 Subject: [Tutor] cmd window In-Reply-To: <CABGnxkugAj64iFiUZ9rUc6O9NaG5fZHWJyY6kVrJ4xPL0hm2aw@mail.gmail.com> References: <CABGnxkugAj64iFiUZ9rUc6O9NaG5fZHWJyY6kVrJ4xPL0hm2aw@mail.gmail.com> Message-ID: <CAPM86Neyrx2vHP6NGRA0cqbriF5jVsZbunv3gkotruZPoL=jHQ@mail.gmail.com> On Tue, Sep 13, 2011 at 12:57 PM, Dinara Vakhitova <di.marvellous at gmail.com>wrote: > Hello, > > Excuse me for my stupid question, but I'm an absolute beginner in > programming. > I just would like to know what should I do in such case: when I run my > program by clicking on the file itself, rather than from IDLE, the cmd > window disappears just immediately after the output printing, so that I > can't even see it. The solution must be very simple, but I can't find it in > tutorials... > This is mainly because in later versions of Windows (XP onward, I believe) they changed a setting so that the command window would close after a program has executed. There are probably some more complicated settings to fix it on a global basis, but you'll find that most people add this line to the end of their programs: raw_input("Press <Enter> to continue") # Use input() with Python 3.x HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110913/70c58e71/attachment.html> From di.marvellous at gmail.com Tue Sep 13 20:55:29 2011 From: di.marvellous at gmail.com (Dinara Vakhitova) Date: Tue, 13 Sep 2011 22:55:29 +0400 Subject: [Tutor] cmd window In-Reply-To: <CAPM86Neyrx2vHP6NGRA0cqbriF5jVsZbunv3gkotruZPoL=jHQ@mail.gmail.com> References: <CABGnxkugAj64iFiUZ9rUc6O9NaG5fZHWJyY6kVrJ4xPL0hm2aw@mail.gmail.com> <CAPM86Neyrx2vHP6NGRA0cqbriF5jVsZbunv3gkotruZPoL=jHQ@mail.gmail.com> Message-ID: <CABGnxkuvLD0jUw0_y6j0ofJSs5tPt-D7uEXpNQpN-oiArBJmeg@mail.gmail.com> Thank you a lot, it helped! 2011/9/13 Wayne Werner <waynejwerner at gmail.com> > On Tue, Sep 13, 2011 at 12:57 PM, Dinara Vakhitova < > di.marvellous at gmail.com> wrote: > >> Hello, >> >> Excuse me for my stupid question, but I'm an absolute beginner in >> programming. >> I just would like to know what should I do in such case: when I run my >> program by clicking on the file itself, rather than from IDLE, the cmd >> window disappears just immediately after the output printing, so that I >> can't even see it. The solution must be very simple, but I can't find it in >> tutorials... >> > > This is mainly because in later versions of Windows (XP onward, I believe) > they changed a setting so that the command window would close after a > program has executed. There are probably some more complicated settings to > fix it on a global basis, but you'll find that most people add this line to > the end of their programs: > > raw_input("Press <Enter> to continue") # Use input() with Python 3.x > > HTH, > Wayne > -- *Yours faithfully, Dinara Vakhitova* -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110913/9d87f325/attachment.html> From alan.gauld at btinternet.com Tue Sep 13 21:01:56 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 13 Sep 2011 20:01:56 +0100 Subject: [Tutor] Unusual pathfile In-Reply-To: <CAFEP6HvmfmEfsm8w5+g-95iZuDnZPcbiFJVV0crtzeqEWVeR_A@mail.gmail.com> References: <CAFEP6HtuBrHnK3P1zXzneEhO1WMp-yj-EVV+2A6gD0N70=mVCQ@mail.gmail.com> <j4lkvq$v0t$1@dough.gmane.org> <CAFEP6HvmfmEfsm8w5+g-95iZuDnZPcbiFJVV0crtzeqEWVeR_A@mail.gmail.com> Message-ID: <j4o94i$qvu$1@dough.gmane.org> On 13/09/11 16:41, Susana Iraiis Delgado Rodriguez wrote: > Hi! > I just want to look the pathfile like this: C:\Python26 instead of > C:/\Python26, OK, Let's see how you might debug that. > I feel the loop repeats its walking with this pathfile I'm not sure what you mean by that but I do have some comments below that might be relevant... > structure. About the indention for the code, I tried my best to make it > clear ande neat. But the mi e-mail editor it's mixing-up spaces. OK, That's unfortunate. Which editor/email tool are you using? We may be able to suggest alternate settings. > dir = "" > extn = "" > csv_name = "" > filesystemencoding = sys.getfilesystemencoding() > > def directorio(): > global dir > print 'Seleccione directorio donde empezar' > dirname1 = > tkFileDialog.askdirectory(parent=root,initialdir="/",title='Selecciona > la ruta a escanear') Does changing the '/' here have any affect on your final result? Is this why you get the /\ maybe? > if len(dirname1 ) > 0: > print "You chose %s" % dirname1 > dir = dirname1 What gets printed here? Does it have the same /\ structure? > def extension():... I don't think the above function is relevant so we can ignore the code for now. > def csv_w():.... Same here, it just gets a filename - we could substitute a dummy one while testing... But this next function is way too big! Try breaking it into chunks each in their own function. It will make it easier to read and thus to understand and to debug. > def buscar(): > print 'Iniciando...' > gdal.AllRegister() > file_list = [] > folders = None > for root, folders, files in os.walk(dir): > file_list.extend(os.path.join(root,fi) for fi in files if > fi.endswith(extn)) This could be put in a function to build the file list. Also you don't need the assignment to folders since os.walk will do that for you and you don't use it anywhere anyway. > f = open(csv_name, 'wb') > log = open ('log_errores.txt','w') > writer = csv.writer(f) > ruta = 'Ruta' > archivo = 'archivo' > x_min = 'x_min' > x_max = 'x_max' > y_min = 'y_min' > y_max = 'y_max' > geometria = 'geometria' > num_elem = 'num_elem' > prj = '.prj' > proyeccion = 'proyeccion' > fecha = 'fecha_modificacion' > creacion = 'fecha_creacion' > ultimo = 'ultimo_acceso' > tamanio = 'tamanio_aprox' > maq = 'maquina_host' > usu = 'usuario' Frankly there is no real advantage putting these strings in variables. You only use them in one place so just use the literal strings in the code there. It will make the code much shorter and therefore easier to read! > campos = > [ruta,archivo,x_min,x_max,y_min,y_max,geometria,num_elem,prj,proyeccion,creacion,fecha,ultimo,tamanio,maq,usu] > writer.writerow(campos) > for row, filepath in enumerate(file_list, start=1): Since you don't seem to use row anywhere you could just make this: for filepath in file_list: > directorio = os.path.dirname(filepath) > filename = os.path.basename(filepath) > shapeData = ogr.Open(filepath.encode(filesystemencoding)) > if shapeData is None: > shp = 'Error al abrir el archivo ' + filepath.encode(filesystemencoding) Since the rest of this is irrelevant to your problem we can delete it for now... > def sizeof_fmt(num): > for x in ['bytes','KB','MB','GB','TB']: > if num < 1024.0: > return "%3.1f%s" % (num, x) > num /= 1024.0 > #Obtener usuario It's generally better to define all functions outside of other functions unless you plan on returning them as function objects. And if you are going to define a function inside another one please do it at the top and not in the middle of the function code. > usuario = os.environ.get("USERNAME") > user = ''+usuario+'' > host = socket.gethostname() > maquina = ''+host+'' I don't understand what this is trying to do? It adds an empty string to the user and host names? You might also want to check that you get valid values for these variables before using them... > if os.path.exists(shx): > print '.' > shx1 = os.path.getsize(shx) > #kb2 = sizeof_fmt(shx1) > else: > log.write('No existe el archivo ' +shx+"\n") > if os.path.exists(dbf): > print '.' > else: > log.write('No existe el archivo ' +dbf+"\n") I'm not sure what this is for? The paths don't exist so you log the error but then continue with the function anyway? > if os.path.exists(p): > #Si existe, asignar 1 > p1 = os.path.getsize(p) > total = sizeof_fmt(s+shx1+p1) If shx didn't exist shx1 will not exist and the code will fail here I think. > aRow= [ directorio, filename, x1, x2, y1, y2, geo, cuenta, 1, > prjtext, crea, modificacion, acceso, total, maquina, user] > writer.writerow(aRow) Could you simplify what you write to get rid of the extra data and see if the fault remains? > else: > #Sino asignar 0 > #no_prj = 'Sin prj, no se puede determinar la > proyeccion' > total = sizeof_fmt(s+shx1) > aRow1= [ directorio, filename, x1, x2, y1, y2, geo, cuenta, 0, > prjtext, crea, modificacion, acceso, total, maquina, user] > writer.writerow(aRow1) > log.close() > f.close() > print "El archivo esta listo" I doubt the rest of the code contributes to the error so I didn't read it... > root = Tk() > top = Toplevel() #Llamo una nueva ventana #Dimensiones de la ventana > root.minsize(400,200) #Barra de herramientas > toolbar = Frame(root) #Botones > b = Button(toolbar, text="Selecciona ruta", width=15, command=directorio) > b.pack(side=LEFT, padx=2, pady=2) > b = Button(toolbar, text="Escriba extension", width=15, command=extension) > b.pack(side=LEFT, padx=2, pady=2) > b = Button(toolbar, text="Nombre de csv", width=15, command=csv_w) > b.pack(side=LEFT, padx=2, pady=2) > b = Button(toolbar, text="Aceptar", width=6, command=buscar) > b.pack(side=LEFT, padx=2, pady=2) > toolbar.pack(side=TOP, fill=X) > root.mainloop() HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From sander.sweers at gmail.com Tue Sep 13 21:05:53 2011 From: sander.sweers at gmail.com (Sander Sweers) Date: Tue, 13 Sep 2011 21:05:53 +0200 Subject: [Tutor] Unusual pathfile In-Reply-To: <j4o94i$qvu$1@dough.gmane.org> References: <CAFEP6HtuBrHnK3P1zXzneEhO1WMp-yj-EVV+2A6gD0N70=mVCQ@mail.gmail.com> <j4lkvq$v0t$1@dough.gmane.org> <CAFEP6HvmfmEfsm8w5+g-95iZuDnZPcbiFJVV0crtzeqEWVeR_A@mail.gmail.com> <j4o94i$qvu$1@dough.gmane.org> Message-ID: <1315940753.1480.11.camel@Nokia-N900> On Tue, 13 Sep 2011, 21:01:56 CEST, Alan Gauld <alan.gauld at btinternet.com> wrote: > On 13/09/11 16:41, Susana Iraiis Delgado Rodriguez wrote: > > structure. About the indention for the code, I tried my best to make it > > clear ande neat. But the mi e-mail editor it's mixing-up spaces. > > OK, That's unfortunate. Which editor/email tool are you using? > We may be able to suggest alternate settings. Then use a pastebin like pastebin.com. It also can do proper python syntax highlighting which make reviewing much easier. Greets sander -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110913/c86b88ae/attachment.html> From alan.gauld at btinternet.com Tue Sep 13 21:15:15 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 13 Sep 2011 20:15:15 +0100 Subject: [Tutor] cmd window In-Reply-To: <CABGnxkugAj64iFiUZ9rUc6O9NaG5fZHWJyY6kVrJ4xPL0hm2aw@mail.gmail.com> References: <CABGnxkugAj64iFiUZ9rUc6O9NaG5fZHWJyY6kVrJ4xPL0hm2aw@mail.gmail.com> Message-ID: <j4o9tg$1q0$1@dough.gmane.org> On 13/09/11 18:57, Dinara Vakhitova wrote: > Hello, > > Excuse me for my stupid question, but I'm an absolute beginner in > programming. Its not stupid and many have asked it before you :-) > can't even see it. The solution must be very simple, but I can't find it > in tutorials... You're obviously reading the wrong tutorials :-) It's covered in the "Add a Little style" topic in my tutorial. Its near the bottom of the page, in the box "Note for Windows Users"... It offers several different ways to deal with it depending on what you want to do. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From ramit.prasad at jpmorgan.com Tue Sep 13 21:09:02 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 13 Sep 2011 15:09:02 -0400 Subject: [Tutor] cmd window In-Reply-To: <CABGnxkuvLD0jUw0_y6j0ofJSs5tPt-D7uEXpNQpN-oiArBJmeg@mail.gmail.com> References: <CABGnxkugAj64iFiUZ9rUc6O9NaG5fZHWJyY6kVrJ4xPL0hm2aw@mail.gmail.com> <CAPM86Neyrx2vHP6NGRA0cqbriF5jVsZbunv3gkotruZPoL=jHQ@mail.gmail.com> <CABGnxkuvLD0jUw0_y6j0ofJSs5tPt-D7uEXpNQpN-oiArBJmeg@mail.gmail.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16BB4213@EMARC112VS01.exchad.jpmchase.net> From: tutor-bounces+ramit.prasad=jpmorgan.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of Dinara Vakhitova Sent: Tuesday, September 13, 2011 1:55 PM To: Wayne Werner Cc: tutor at python.org Subject: Re: [Tutor] cmd window Thank you a lot, it helped! 2011/9/13 Wayne Werner <waynejwerner at gmail.com<mailto:waynejwerner at gmail.com>> On Tue, Sep 13, 2011 at 12:57 PM, Dinara Vakhitova <di.marvellous at gmail.com<mailto:di.marvellous at gmail.com>> wrote: Hello, Excuse me for my stupid question, but I'm an absolute beginner in programming. I just would like to know what should I do in such case: when I run my program by clicking on the file itself, rather than from IDLE, the cmd window disappears just immediately after the output printing, so that I can't even see it. The solution must be very simple, but I can't find it in tutorials... This is mainly because in later versions of Windows (XP onward, I believe) they changed a setting so that the command window would close after a program has executed. There are probably some more complicated settings to fix it on a global basis, but you'll find that most people add this line to the end of their programs: raw_input("Press <Enter> to continue") # Use input() with Python 3.x HTH, Wayne -- Yours faithfully, Dinara Vakhitova You can also run from command line. Start->run-> type "cmd" ->hit enter -> navigate to directory "cd c:\directory\with\python\filename.py" (substitute the path you need) -> run script "python filename.py" Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110913/83d45fa8/attachment.html> From ramit.prasad at jpmorgan.com Tue Sep 13 21:01:09 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 13 Sep 2011 15:01:09 -0400 Subject: [Tutor] Unusual pathfile In-Reply-To: <CAKK8jXanFavEK9B9enWJLY_TL2r13KkW0jx2MmQu8hVY4iMEKA@mail.gmail.com> References: <CAFEP6HtuBrHnK3P1zXzneEhO1WMp-yj-EVV+2A6gD0N70=mVCQ@mail.gmail.com> <j4lkvq$v0t$1@dough.gmane.org> <CAFEP6HvmfmEfsm8w5+g-95iZuDnZPcbiFJVV0crtzeqEWVeR_A@mail.gmail.com> <4E6F8C42.4070709@pearwood.info> <CAFEP6Hu6+CPjELAGuSN5kDQyY3dwFShHU5kt3BQcBHcpr0hv2Q@mail.gmail.com> <CAKK8jXanFavEK9B9enWJLY_TL2r13KkW0jx2MmQu8hVY4iMEKA@mail.gmail.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16BB41D4@EMARC112VS01.exchad.jpmchase.net> From: tutor-bounces+ramit.prasad=jpmorgan.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of Marc Tompkins Sent: Tuesday, September 13, 2011 12:38 PM To: tutor at python.org Subject: Re: [Tutor] Unusual pathfile Susana - I think I speak for everyone when I say: don't go away! Nobody's complaining about your question; that's what the list is for. However, we're all human beings, and all doing this voluntarily. So it's in your best interest to make your questions easy for us to read. So many lines all run together, with only one space of indentation, makes my head hurt when I try to read it; I'm ashamed to admit that I simply skipped over your question when you first posted it. Others put more effort into it, and have told you why it was hard for them. Don't be offended! At least they took the trouble, which is more than I did. Two things you can do to make this better: - Set your text editor to convert tabs to spaces, preferably four spaces. This is a Good Thing To Do anyway, because some of the hardest bugs to find - for you as well as for us - happen when Python gets confused about levels of indentation. If you're not sure how to change that setting, just tell us which editor you use and someone can help with that. - When you ask a question - and we WANT you to ask questions! - try to narrow down your program to just the part that's giving you trouble. It makes it MUCH easier for us to help you, and quite often it helps you to find the problem yourself. As Steven said above, at the moment I can't even see which part of your code is generating "C:\/Python26", let alone help you to correct it. Just remember: we all want to help; speaking for myself, I started out asking questions on this list and have stuck around to answer them. But we're all human too - and speaking for myself, sometimes we're a little lazy. ======================================================================================= Not to mention, all of us have different levels of understanding for languages. I understand English, but little else. :) I think I can narrow down the problem section. (And this is my third try. As I was indenting, I saw that I could continue narrowing down the section). def buscar(): print 'Iniciando...' gdal.AllRegister() file_list = [] folders = None for root, folders, files in os.walk(dir): ### Add print statement here ## file_list.extend(os.path.join(root,fi) for fi in files if fi.endswith(extn)) I am not very familiar with the os module, but I would suggesting adding a print/debug statement in the loop to print root, folders, files so that you can see if something incorrect is happening. This will also give you a much better "stack trace" to see the progress of your application. Small sample of what I got: <snip> c:\tmp\m2\localrepo\saxpath ['saxpath'] [] c:\tmp\m2\localrepo\saxpath\saxpath ['1.0-FCS'] [] c:\tmp\m2\localrepo\saxpath\saxpath\1.0-FCS [] ['saxpath-1.0-FCS.jar', 'saxpath-1.0-FCS.jar.sha1', 'saxpath-1.0-FCS.pom', 'saxpath-1.0-FCS.pom.sha1', '_maven.repositories'] <snip> This does not show the behavior you are suggesting. Is there somewhere else that you were referring to? Is it possible you are changing directory or something in the middle of the os.walk command and that is causing it to re-execute the walk? (Python 2.6 / Win7) Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110913/56a0a95b/attachment-0001.html> From di.marvellous at gmail.com Tue Sep 13 21:30:31 2011 From: di.marvellous at gmail.com (Dinara Vakhitova) Date: Tue, 13 Sep 2011 23:30:31 +0400 Subject: [Tutor] cmd window In-Reply-To: <j4o9tg$1q0$1@dough.gmane.org> References: <CABGnxkugAj64iFiUZ9rUc6O9NaG5fZHWJyY6kVrJ4xPL0hm2aw@mail.gmail.com> <j4o9tg$1q0$1@dough.gmane.org> Message-ID: <CABGnxksMYzbcAh-vdj1aF4iFx5vSaX4+O=M0MM6p2iCnsAxZ+Q@mail.gmail.com> Thank you, Ramit and thank you, Alan! I have so many tutorials around me that I'm a little bit lost in the materials! Now I'll be focusing on "Learning to Program" by Alan Gauld. :) 2011/9/13 Alan Gauld <alan.gauld at btinternet.com> > On 13/09/11 18:57, Dinara Vakhitova wrote: > >> Hello, >> >> Excuse me for my stupid question, but I'm an absolute beginner in >> programming. >> > > Its not stupid and many have asked it before you :-) > > > can't even see it. The solution must be very simple, but I can't find it >> in tutorials... >> > > You're obviously reading the wrong tutorials :-) > > It's covered in the "Add a Little style" topic in my tutorial. > Its near the bottom of the page, in the box "Note for Windows Users"... > > It offers several different ways to deal with it depending > on what you want to do. > > HTH, > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor> > -- *Yours faithfully, Dinara Vakhitova* -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110913/061ee92d/attachment.html> From jjhartley at gmail.com Wed Sep 14 21:44:06 2011 From: jjhartley at gmail.com (James Hartley) Date: Wed, 14 Sep 2011 12:44:06 -0700 Subject: [Tutor] telnetlib's read_very_eager() method? Message-ID: <CAKeNXXvZEw5PrQ+3hKim3=9SPJ2vxfUbnauObhSUb-j3FZ6Ggg@mail.gmail.com> I'm trying to programmatically create a telnet session. Within the interactive environment, this appears to work very well as server messages can be saved as strings: $ python Python 2.7.1 (r271:86832, Sep 3 2011, 01:32:33) [GCC 4.2.1 20070719 ] on openbsd5 Type "help", "copyright", "credits" or "license" for more information. >>> import telnetlib >>> tn = telnetlib.Telnet('gmail-smtp-in.l.google.com', 25) >>> s = tn.read_very_eager() >>> print s 220 mx.google.com ESMTP r70si1582241yhm.54 >>> tn.write("helo\n") >>> s = tn.read_very_eager() >>> print s 250 mx.google.com at your service >>> tn.write("quit\n") >>> s = tn.read_very_eager() >>> print s 221 2.0.0 closing connection r70si1582241yhm.54 >>> $ These server response can then be parsed to determine what commands need to be provided next. Yet when I execute the same methods in a script, I am getting nothing in response: $ cat script.py #!/usr/bin/env python import telnetlib if __name__ == '__main__': print 'begin' tn = telnetlib.Telnet('gmail-smtp-in.l.google.com', 25) s = tn.read_very_eager() print s tn.write("helo\n") s = tn.read_very_eager() print s tn.write("quit\n") s = tn.read_very_eager() print s print 'end' $ python script.py begin end $ What do I need to do to emulate the IDE environment? If I am needing to capture stdout, it isn't readily apparent. Any insight you can share would be greatly appreciated. Jim -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110914/a466c68a/attachment.html> From wprins at gmail.com Wed Sep 14 21:54:17 2011 From: wprins at gmail.com (Walter Prins) Date: Wed, 14 Sep 2011 20:54:17 +0100 Subject: [Tutor] telnetlib's read_very_eager() method? In-Reply-To: <CAKeNXXvZEw5PrQ+3hKim3=9SPJ2vxfUbnauObhSUb-j3FZ6Ggg@mail.gmail.com> References: <CAKeNXXvZEw5PrQ+3hKim3=9SPJ2vxfUbnauObhSUb-j3FZ6Ggg@mail.gmail.com> Message-ID: <CANLXbfAfic=NWCzPt+TKtdWLqrU9f1Z6HmARf_ZuagBHSYazjg@mail.gmail.com> On 14 September 2011 20:44, James Hartley <jjhartley at gmail.com> wrote: > #!/usr/bin/env python > > import telnetlib > > if __name__ == '__main__': > print 'begin' > tn = telnetlib.Telnet('gmail-smtp-in.l.google.com', 25) > s = tn.read_very_eager() > print s > tn.write("helo\n") > s = tn.read_very_eager() > print s > tn.write("quit\n") > s = tn.read_very_eager() > print s > print 'end' > $ python script.py > begin > > > > end > $ > > What do I need to do to emulate the IDE environment? If I am needing to > capture stdout, it isn't readily apparent. > Make it go slower or force it to read *some* data at least. Interactively there's plenty of time for data to arrive for read_very_eager() to read. When run as a batch your computer tries to read and continue before any data's been returned from google. Hence, try using read_some() instead of read_very_eager(). Aside: If you want to interact with a mail server there's probably better modules to be using than the telnet module. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110914/52b1ad61/attachment.html> From jjhartley at gmail.com Wed Sep 14 22:03:30 2011 From: jjhartley at gmail.com (James Hartley) Date: Wed, 14 Sep 2011 13:03:30 -0700 Subject: [Tutor] telnetlib's read_very_eager() method? In-Reply-To: <CANLXbfAfic=NWCzPt+TKtdWLqrU9f1Z6HmARf_ZuagBHSYazjg@mail.gmail.com> References: <CAKeNXXvZEw5PrQ+3hKim3=9SPJ2vxfUbnauObhSUb-j3FZ6Ggg@mail.gmail.com> <CANLXbfAfic=NWCzPt+TKtdWLqrU9f1Z6HmARf_ZuagBHSYazjg@mail.gmail.com> Message-ID: <CAKeNXXu-h5yQTQQYaDMUCjM4AggXMQW6EmPbS=wFq3GdEhHcMA@mail.gmail.com> On Wed, Sep 14, 2011 at 12:54 PM, Walter Prins <wprins at gmail.com> wrote: > Hence, try using read_some() instead of read_very_eager(). > read_some() captures what I was hoping to catch. Thanks! > > Aside: If you want to interact with a mail server there's probably better > modules to be using than the telnet module. > > Do you have any suggestions? Thank you again for your quick reply. Jim -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110914/2c3b797a/attachment.html> From wprins at gmail.com Wed Sep 14 22:13:38 2011 From: wprins at gmail.com (Walter Prins) Date: Wed, 14 Sep 2011 21:13:38 +0100 Subject: [Tutor] telnetlib's read_very_eager() method? In-Reply-To: <CAKeNXXu-h5yQTQQYaDMUCjM4AggXMQW6EmPbS=wFq3GdEhHcMA@mail.gmail.com> References: <CAKeNXXvZEw5PrQ+3hKim3=9SPJ2vxfUbnauObhSUb-j3FZ6Ggg@mail.gmail.com> <CANLXbfAfic=NWCzPt+TKtdWLqrU9f1Z6HmARf_ZuagBHSYazjg@mail.gmail.com> <CAKeNXXu-h5yQTQQYaDMUCjM4AggXMQW6EmPbS=wFq3GdEhHcMA@mail.gmail.com> Message-ID: <CANLXbfDyHWdkVbTuc8oui7gs+Y_6aGCEtcHuSk5CUVtqcrwMZQ@mail.gmail.com> On 14 September 2011 21:03, James Hartley <jjhartley at gmail.com> wrote: > On Wed, Sep 14, 2011 at 12:54 PM, Walter Prins <wprins at gmail.com> wrote: > >> Hence, try using read_some() instead of read_very_eager(). >> > > read_some() captures what I was hoping to catch. Thanks! > > >> >> Aside: If you want to interact with a mail server there's probably better >> modules to be using than the telnet module. >> >> > Do you have any suggestions? > The smtplib module: http://docs.python.org/library/smtplib.html Cheers, Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110914/ff1670a6/attachment.html> From jjhartley at gmail.com Wed Sep 14 22:40:18 2011 From: jjhartley at gmail.com (James Hartley) Date: Wed, 14 Sep 2011 13:40:18 -0700 Subject: [Tutor] telnetlib's read_very_eager() method? In-Reply-To: <CANLXbfDyHWdkVbTuc8oui7gs+Y_6aGCEtcHuSk5CUVtqcrwMZQ@mail.gmail.com> References: <CAKeNXXvZEw5PrQ+3hKim3=9SPJ2vxfUbnauObhSUb-j3FZ6Ggg@mail.gmail.com> <CANLXbfAfic=NWCzPt+TKtdWLqrU9f1Z6HmARf_ZuagBHSYazjg@mail.gmail.com> <CAKeNXXu-h5yQTQQYaDMUCjM4AggXMQW6EmPbS=wFq3GdEhHcMA@mail.gmail.com> <CANLXbfDyHWdkVbTuc8oui7gs+Y_6aGCEtcHuSk5CUVtqcrwMZQ@mail.gmail.com> Message-ID: <CAKeNXXsyu3=V3anAnTPG31_Wmn3yy9GrBRehPaJbjCp14_L4Ng@mail.gmail.com> On Wed, Sep 14, 2011 at 1:13 PM, Walter Prins <wprins at gmail.com> wrote: > On 14 September 2011 21:03, James Hartley <jjhartley at gmail.com> wrote: > >> On Wed, Sep 14, 2011 at 12:54 PM, Walter Prins <wprins at gmail.com> wrote: >> > Aside: If you want to interact with a mail server there's probably better >> modules to be using than the telnet module. >> >>> >>> >> Do you have any suggestions? >> > > The smtplib module: http://docs.python.org/library/smtplib.html > Wow, I wasn't aware this existed. It appears to have what I was looking for, too. My goal was to validate email addresses in bulk, so this reduces the code I need to write. I also see that VRFY is disabled on some MX servers, so I may have to resort to telnetlib's read_some() yet. :-) Thanks, again for your comments. Jim -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110914/869fe6b6/attachment-0001.html> From illusiontechniques at gmail.com Thu Sep 15 04:01:16 2011 From: illusiontechniques at gmail.com (c smith) Date: Wed, 14 Sep 2011 22:01:16 -0400 Subject: [Tutor] making lists of prime numbers Message-ID: <CAL2Y8-TRn6t-rK30xEDhgFtHGmEOrLKQ6YYUrWxwyqRJNON3vA@mail.gmail.com> hi list, i am trying the MIT opencourseware assignments. one was to find the 1000th prime. since this isn't actually my homework, I modified the solution as I would like to collect lists of primes and non-primes up to N, also some log() ratio to one comparison. here is what I came up with on paper: #!/usr/bin/env python import sys, os, math def main(a): notprime = [] primelist = [2,3] nprime = sys.argv[1] numcheck = 4 while len(primelist) < nprime: for i in range(2,numcheck-1): if numcheck % i == 0: print numcheck,'is not prime' notprime.append(numcheck) numcheck += 1 break if i == numcheck and numcheck % i !=0: print numcheck, 'is prime' primelist.append(numcheck) numcheck += 1 break TwotoN = 0 for j in primelist: TwotoN += log(j) print 'sum of logs of primes from 2 to', nprime,'is',TwotoN print 'the ratio of this sum to 1 is' %f % (float(TwotoN)/nprime) if __name__=='__main__': main(sys.argv[1]) my questions would be: am I passing arguments from the command line correctly? this seems to count by twos (going through both 'if statements' maybe?) I thought the 'break' would send control back to the 'while' basically, is there an obvious problem here or is it just completely wrong? -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110914/8c18eeee/attachment.html> From andreengels at gmail.com Thu Sep 15 04:35:24 2011 From: andreengels at gmail.com (Andre Engels) Date: Thu, 15 Sep 2011 04:35:24 +0200 Subject: [Tutor] making lists of prime numbers In-Reply-To: <CAL2Y8-TRn6t-rK30xEDhgFtHGmEOrLKQ6YYUrWxwyqRJNON3vA@mail.gmail.com> References: <CAL2Y8-TRn6t-rK30xEDhgFtHGmEOrLKQ6YYUrWxwyqRJNON3vA@mail.gmail.com> Message-ID: <CAGzCZ0odVOVwY5c-zE_BVBWJhSiLt+HJ7epZAFAdH9kJkq-OcA@mail.gmail.com> On Thu, Sep 15, 2011 at 4:01 AM, c smith <illusiontechniques at gmail.com>wrote: > hi list, i am trying the MIT opencourseware assignments. > one was to find the 1000th prime. > since this isn't actually my homework, I modified the solution as I would > like to collect lists of primes and non-primes up to N, also some log() > ratio to one comparison. > here is what I came up with on paper: > #!/usr/bin/env python > import sys, os, math > > def main(a): > notprime = [] > primelist = [2,3] > nprime = sys.argv[1] > numcheck = 4 > while len(primelist) < nprime: > for i in range(2,numcheck-1): > if numcheck % i == 0: > print numcheck,'is not prime' > notprime.append(numcheck) > numcheck += 1 > break > if i == numcheck and numcheck % i !=0: > print numcheck, 'is prime' > primelist.append(numcheck) > numcheck += 1 > break > TwotoN = 0 > for j in primelist: > TwotoN += log(j) > print 'sum of logs of primes from 2 to', nprime,'is',TwotoN > print 'the ratio of this sum to 1 is' %f % (float(TwotoN)/nprime) > if __name__=='__main__': > main(sys.argv[1]) > > my questions would be: > am I passing arguments from the command line correctly? > this seems to count by twos (going through both 'if statements' maybe?) > I thought the 'break' would send control back to the 'while' > basically, is there an obvious problem here or is it just completely wrong? > I'd say the obvious problem is your second if statement. Its guard will never be true. i goes through range(2,numcheck-1). The highest number in that range in numcheck-2, so i==numcheck will never be true. Even if you'd get i to equal numcheck somehow, numcheck % i would then ber equal to numcheck % numcheck, which equals 0, so numcheck % i != 0 would not be true. The obvious thing to do seems to be to get this code out of the for loop, without and if statement guarding it. Another thing that goes wrong is: nprime = sys.argv[1] You use nprime as an integer, but sys.argv[1] is a string. You should thus change this into nprime = int(sys.argv[1]) However, for the sake of reusability, it's better to have a function that gets the first n primes for n decided by the caller than to have a function that gets the first n primes for n always being the first argument, thus I would change it to: nprime = int(a) -- Andr? Engels, andreengels at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110915/c88f3e4e/attachment.html> From alan.gauld at btinternet.com Thu Sep 15 10:36:11 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 15 Sep 2011 09:36:11 +0100 Subject: [Tutor] making lists of prime numbers In-Reply-To: <CAL2Y8-TRn6t-rK30xEDhgFtHGmEOrLKQ6YYUrWxwyqRJNON3vA@mail.gmail.com> References: <CAL2Y8-TRn6t-rK30xEDhgFtHGmEOrLKQ6YYUrWxwyqRJNON3vA@mail.gmail.com> Message-ID: <j4sdds$tei$1@dough.gmane.org> On 15/09/11 03:01, c smith wrote: > am I passing arguments from the command line correctly? Yes, although not converting to an int. > this seems to count by twos (going through both 'if statements' maybe?) > I thought the 'break' would send control back to the 'while' > basically, is there an obvious problem here or is it just completely wrong? It might work once you iron out the bugs but it's horribly inefficient. It will take a very long time to run for large numbers. Did you try searching for prime number algorithms? There are several that will be much faster than this. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From d at davea.name Thu Sep 15 14:20:25 2011 From: d at davea.name (Dave Angel) Date: Thu, 15 Sep 2011 08:20:25 -0400 Subject: [Tutor] making lists of prime numbers In-Reply-To: <CAGzCZ0odVOVwY5c-zE_BVBWJhSiLt+HJ7epZAFAdH9kJkq-OcA@mail.gmail.com> References: <CAL2Y8-TRn6t-rK30xEDhgFtHGmEOrLKQ6YYUrWxwyqRJNON3vA@mail.gmail.com> <CAGzCZ0odVOVwY5c-zE_BVBWJhSiLt+HJ7epZAFAdH9kJkq-OcA@mail.gmail.com> Message-ID: <4E71ED89.6090807@davea.name> On 09/14/2011 10:35 PM, Andre Engels wrote: > On Thu, Sep 15, 2011 at 4:01 AM, c smith<illusiontechniques at gmail.com>wrote: > >> hi list, i am trying the MIT opencourseware assignments. >> one was to find the 1000th prime. >> since this isn't actually my homework, I modified the solution as I would >> like to collect lists of primes and non-primes up to N, also some log() >> ratio to one comparison. >> here is what I came up with on paper: >> #!/usr/bin/env python >> import sys, os, math >> >> def main(a): >> notprime = [] >> primelist = [2,3] >> nprime = sys.argv[1] >> numcheck = 4 >> while len(primelist)< nprime: >> for i in range(2,numcheck-1): >> if numcheck % i == 0: >> print numcheck,'is not prime' >> notprime.append(numcheck) >> numcheck += 1 >> break >> if i == numcheck and numcheck % i !=0: >> print numcheck, 'is prime' >> primelist.append(numcheck) >> numcheck += 1 >> break >> TwotoN = 0 >> for j in primelist: >> TwotoN += log(j) >> print 'sum of logs of primes from 2 to', nprime,'is',TwotoN >> print 'the ratio of this sum to 1 is' %f % (float(TwotoN)/nprime) >> if __name__=='__main__': >> main(sys.argv[1]) >> >> my questions would be: >> am I passing arguments from the command line correctly? >> this seems to count by twos (going through both 'if statements' maybe?) >> I thought the 'break' would send control back to the 'while' >> basically, is there an obvious problem here or is it just completely wrong? >> > I'd say the obvious problem is your second if statement. Its guard will > never be true. i goes through range(2,numcheck-1). The highest number in > that range in numcheck-2, so i==numcheck will never be true. Even if you'd > get i to equal numcheck somehow, numcheck % i would then ber equal to > numcheck % numcheck, which equals 0, so numcheck % i != 0 would not be true. > > The obvious thing to do seems to be to get this code out of the for loop, > without and if statement guarding it. > > Another thing that goes wrong is: > > nprime = sys.argv[1] > > You use nprime as an integer, but sys.argv[1] is a string. You should thus > change this into > > nprime = int(sys.argv[1]) > > However, for the sake of reusability, it's better to have a function that > gets the first n primes for n decided by the caller than to have a function > that gets the first n primes for n always being the first argument, thus I > would change it to: > > nprime = int(a) > As Andre and Alan have said, there are some problems with your code. However, the basic concept is reasonable. I wouldn't worry much about efficiency, yet. Get it to work reliably, then figure how to tune it. And if you have a source control system (like git, svn, mercurial), check in each version that works, so you can always compare to what you currently have. Your specific questions: 1) you're passing the (one) argument from the command line reasonably, though I'd convert it to int before passing it, and I'd change the formal parameter name of it in your function to nprime. Then you don't need any additional assignment in the function. 2) it seems to count by twos because of the problems with your second if, as Andre has said. Start by fixing the second if statement. There are two ways to fix it. a) change the condition so it detects the end of the loop, which in your case is numcheck-2. Catch to that is that when you realize you can optimize the loop, you'll have to remember to change the if to match. b) move the code outside of the loop. However, you'd also have to make sure it *didn't* get executed if the first if statement did. That could be a real pain, except that Python has a nice "else" clause you can attach to a loop, that only gets executed if the loop completes normally. That else is exactly what you want, so it makes it straightforward. Once you see it generating the correct primes, you may notice that it sails right past the nprimes value. That'll get fixed when you add the int() function when calling main(). Comparing int to string usually doesn't do what you'd want. next problem you'll have is the log function, which is defined in math. So you want to call math.log() next problem is the misplaced quotes on the last print statement. You'll get an error when you hit that one. Finally, the wording of those two prints is all wrong, so you might want to fix it so it matches what the code does. HTH -- DaveA From rdmoores at gmail.com Thu Sep 15 20:19:11 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Thu, 15 Sep 2011 11:19:11 -0700 Subject: [Tutor] What's the keyword for the Python creed? Message-ID: <CALMxxxn-DO0ExDA6S=H+wPaUvGT5s2Wx2vYHm6whomAw5JkS3Q@mail.gmail.com> You know, at the interactive prompt you enter some Monty Python word that I can't remember, and you get a small list of pithy pythonic advice such as "explicit is better than implicit", etc. Thanks, Dick Moores From sirgnip at gmail.com Thu Sep 15 20:24:57 2011 From: sirgnip at gmail.com (Scott Nelson) Date: Thu, 15 Sep 2011 13:24:57 -0500 Subject: [Tutor] What's the keyword for the Python creed? In-Reply-To: <CALMxxxn-DO0ExDA6S=H+wPaUvGT5s2Wx2vYHm6whomAw5JkS3Q@mail.gmail.com> References: <CALMxxxn-DO0ExDA6S=H+wPaUvGT5s2Wx2vYHm6whomAw5JkS3Q@mail.gmail.com> Message-ID: <CAH30xawZfWtmq9_a47rC9zXCKK_o6pAo0UYqk8E2JPCyf8B25g@mail.gmail.com> On Thu, Sep 15, 2011 at 1:19 PM, Richard D. Moores <rdmoores at gmail.com>wrote: > You know, at the interactive prompt you enter some Monty Python word > that I can't remember, and you get a small list of pithy pythonic > advice such as "explicit is better than implicit", etc. > import this You can also do... import antigravity ...for another Pythonic easter egg... Though I think this one requires Python 3? 2.7? Can't remember. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110915/1a92b8e8/attachment.html> From wolfrage8765 at gmail.com Thu Sep 15 20:25:33 2011 From: wolfrage8765 at gmail.com (Jordan) Date: Thu, 15 Sep 2011 11:25:33 -0700 Subject: [Tutor] What's the keyword for the Python creed? In-Reply-To: <CALMxxxn-DO0ExDA6S=H+wPaUvGT5s2Wx2vYHm6whomAw5JkS3Q@mail.gmail.com> References: <CALMxxxn-DO0ExDA6S=H+wPaUvGT5s2Wx2vYHm6whomAw5JkS3Q@mail.gmail.com> Message-ID: <4E72431D.90902@gmail.com> I think you mean the Zen of Python: http://www.python.org/dev/peps/pep-0020/ The command is >>> import this -- Jordan On 09/15/2011 11:19 AM, Richard D. Moores wrote: > You know, at the interactive prompt you enter some Monty Python word > that I can't remember, and you get a small list of pithy pythonic > advice such as "explicit is better than implicit", etc. > > Thanks, > > Dick Moores > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From ramit.prasad at jpmorgan.com Thu Sep 15 20:30:09 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 15 Sep 2011 14:30:09 -0400 Subject: [Tutor] What's the keyword for the Python creed? In-Reply-To: <CAH30xawZfWtmq9_a47rC9zXCKK_o6pAo0UYqk8E2JPCyf8B25g@mail.gmail.com> References: <CALMxxxn-DO0ExDA6S=H+wPaUvGT5s2Wx2vYHm6whomAw5JkS3Q@mail.gmail.com> <CAH30xawZfWtmq9_a47rC9zXCKK_o6pAo0UYqk8E2JPCyf8B25g@mail.gmail.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16CEFC98@EMARC112VS01.exchad.jpmchase.net> >import antigravity >...for another Pythonic easter egg... ?Though I think this one requires Python 3? ?2.7? ?Can't remember. Works in 2.7 but not 2.6.4 Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From rdmoores at gmail.com Thu Sep 15 20:57:36 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Thu, 15 Sep 2011 11:57:36 -0700 Subject: [Tutor] What's the keyword for the Python creed? In-Reply-To: <61310E38B60C8F4AB59757E88A3C967723F3020CD5@UMDAC-CCR2.ad.umu.se> References: <CALMxxxn-DO0ExDA6S=H+wPaUvGT5s2Wx2vYHm6whomAw5JkS3Q@mail.gmail.com> <61310E38B60C8F4AB59757E88A3C967723F3020CD5@UMDAC-CCR2.ad.umu.se> Message-ID: <CALMxxxmqX6O5S3qcroji-03Cjm0LY39L-jA8EbOZwws272irTw@mail.gmail.com> Thanks, all. Good to have that at hand. antigravity: any more? Dick From emekamicro at gmail.com Fri Sep 16 01:50:31 2011 From: emekamicro at gmail.com (Emeka) Date: Fri, 16 Sep 2011 01:50:31 +0200 Subject: [Tutor] Please review my code Message-ID: <CAOypoo6MkkbAwHiZUp8jiEwwjABxiePafcDaS2frwC7H=OW1zw@mail.gmail.com> Hello All, While trying to learn Python I developed a small game, Text Text. It has rough edges and may not meet your class. However, by reviewing it you'll be helping me to advance. It was only tested on a Windows Box, but I see no reason why it would not work on Unix family. https://github.com/janus/Text-Twist I need you comments. -- *Regards, Emeka * -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110916/251dd497/attachment-0001.html> From cjreynol13 at aol.com Fri Sep 16 04:22:09 2011 From: cjreynol13 at aol.com (Chad Reynolds) Date: Thu, 15 Sep 2011 22:22:09 -0400 Subject: [Tutor] help importing pygame Message-ID: <A6C68E5E-D99B-4A46-BFC5-22E36CEEAC28@aol.com> For starters, I am a newish python programmer, far enough along to have my feet wet. Running Mac OSX Lion (10.7), and python 2.7.2. I am trying to expand my knowledge and use some packages outside of the base python library. Games are interesting so I decided I'd try pygame after reading many good things about it. Now I have been to the site and downloaded the install package for OSX Lion, and run it successfully. But when I try to run the example on the site (line by line chimp example) I get this error message: Traceback (most recent call last): File "/private/var/folders/j4/10dtxgh14hl6vdvzzhbbqzdc0000gn/T/Cleanup At Startup/untitled text 4-337832000.071", line 11, in <module> import os, pygame File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/__init__.py", line 95, in <module> from pygame.base import * ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/base.so, 2): no suitable image found. Did find: /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/base.so: no matching architecture in universal wrapper The program hasn't even made it anywhere else in the code, and I really don't understand what the problem is. Help would be much appreciated, thank you all From swiftone at swiftone.org Fri Sep 16 04:35:37 2011 From: swiftone at swiftone.org (Brett Ritter) Date: Thu, 15 Sep 2011 22:35:37 -0400 Subject: [Tutor] Strange zip syntax Message-ID: <CAMb349w7UeHVAAAwx2gbimC46w1dCUfuWZ_5Pw9Z-KwH_KxTpA@mail.gmail.com> I ran into this article ( http://blog.adku.com/2011/09/hodgepodge-of-python.html ) and found myself temporarily stymied by one line it in: zip(*[iter(a)]*2) Used like this: >>> a = ['a','1','b','2','c','3'] >>> zip(*[iter(a)]*2) [('a', '1'), ('b', '2'), ('c', '3')] While I'm unlikely to use such a construct (if I can't easily follow it now, I or my successor likely won't follow it should it need to be debugged sometime in the future), I found the education I got in deciphering it was worth the effort. I'm sharing it here so others can benefit from my puzzlement. iter(a) returns a list iterator for a. See help(iter) for more. [iter(a)] is a list containing one element, an iterator. This is created only so we can do the below: [iter(a)]*2 is a list containing two elements, each the SAME list iterator. For simplicity, let's break this out for further analysis: >>> b = iter(a) >>> c = [b,b] *[iter(a)]*2 flattens the list when passed into a function call. Using our more verbose but simple syntax: *c. This only works when passed to a function. zip() creates tuples each holding the Nth elements from a number of sequences. See help(zip) for more. Thus, zip(a) or zip(a,a) would return: >>> zip(a) [('a',), ('1',), ('b',), ('2',), ('c',), ('3',)] >>> zip(a,a) [('a', 'a'), ('1', '1'), ('b', 'b'), ('2', '2'), ('c', 'c'), ('3', '3')] What happens when we pass an iterator to zip? That's not mentioned in the docstring blurb. >>> zip(iter(a)) [('a',), ('1',), ('b',), ('2',), ('c',), ('3',)] Answer: It works as intended. Now we come to the magic of this little snippet. zip(iter(a),iter(a)) wouldn't work, because each call to iter(a) returns a DIFFERENT iterator. >>> zip(iter(a), iter(a)) [('a', 'a'), ('1', '1'), ('b', 'b'), ('2', '2'), ('c', 'c'), ('3', '3')] But by creating the list of two elements each of which is the SAME iterator, as each is asked to iterate it advances the common element indicator: >>> zip(*c) [('a', '1'), ('b', '2'), ('c', '3')] Notice that the flattening is required, because zip needs to get multiple arguments: >>> b = iter(a) #our original iterator is spent, so we're assigning a new one >>> c = [b,b] >>> zip(c) #Not flattened, is just a single list, like a. [(<listiterator object at 0x024E32D0>,), (<listiterator object at 0x024E32D0>,)] >>> zip(b,b) # here it is two iterators sent to zip() (though they happen to be the SAME iterator) [('a', '1'), ('b', '2'), ('c', '3')] I hope some of you enjoy playing with this, and hopefully someone learned something useful! While I'm not likely to use the listed form, I can very well see myself saying: >>> a = ['a','1','b','2','c','3'] #well, I can see myself using this with meaningful variable names >>> b = iter(a) >>> zip(b,b) # Group in sets of 2 elements -- Brett Ritter / SwiftOne swiftone at swiftone.org From cwitts at compuscan.co.za Fri Sep 16 08:47:05 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Fri, 16 Sep 2011 08:47:05 +0200 Subject: [Tutor] What's the keyword for the Python creed? In-Reply-To: <CALMxxxmqX6O5S3qcroji-03Cjm0LY39L-jA8EbOZwws272irTw@mail.gmail.com> References: <CALMxxxn-DO0ExDA6S=H+wPaUvGT5s2Wx2vYHm6whomAw5JkS3Q@mail.gmail.com> <61310E38B60C8F4AB59757E88A3C967723F3020CD5@UMDAC-CCR2.ad.umu.se> <CALMxxxmqX6O5S3qcroji-03Cjm0LY39L-jA8EbOZwws272irTw@mail.gmail.com> Message-ID: <4E72F0E9.5080504@compuscan.co.za> On 2011/09/15 08:57 PM, Richard D. Moores wrote: > Thanks, all. Good to have that at hand. > > antigravity: any more? > > Dick > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > from __future__ import braces :) -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110916/49a05cdf/attachment.html> From rdmoores at gmail.com Fri Sep 16 09:12:40 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Fri, 16 Sep 2011 00:12:40 -0700 Subject: [Tutor] What's the keyword for the Python creed? In-Reply-To: <4E72F0E9.5080504@compuscan.co.za> References: <CALMxxxn-DO0ExDA6S=H+wPaUvGT5s2Wx2vYHm6whomAw5JkS3Q@mail.gmail.com> <61310E38B60C8F4AB59757E88A3C967723F3020CD5@UMDAC-CCR2.ad.umu.se> <CALMxxxmqX6O5S3qcroji-03Cjm0LY39L-jA8EbOZwws272irTw@mail.gmail.com> <4E72F0E9.5080504@compuscan.co.za> Message-ID: <CALMxxxnCXhbwwzDK2sNL3kk0BBdKff4TiDLPSngP9FnRj6KqFg@mail.gmail.com> On Thu, Sep 15, 2011 at 23:47, Christian Witts <cwitts at compuscan.co.za> wrote: > from __future__ import braces Ha! (2.7 and 3.x) Dick From bodsda at googlemail.com Fri Sep 16 09:41:23 2011 From: bodsda at googlemail.com (bodsda at googlemail.com) Date: Fri, 16 Sep 2011 07:41:23 +0000 Subject: [Tutor] If statement optimization Message-ID: <606259109-1316158883-cardhu_decombobulator_blackberry.rim.net-486964431-@b28.c12.bise7.blackberry> Hi, In a normal if,elif,elif,...,else statement, are the conditions checked in a linear fashion? I am wondering if I should be making an effort to put the most likely true condition at the beginning of the block Thanks, Bodsda Sent from my BlackBerry? wireless device From steve at pearwood.info Fri Sep 16 12:43:45 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 16 Sep 2011 20:43:45 +1000 Subject: [Tutor] If statement optimization In-Reply-To: <606259109-1316158883-cardhu_decombobulator_blackberry.rim.net-486964431-@b28.c12.bise7.blackberry> References: <606259109-1316158883-cardhu_decombobulator_blackberry.rim.net-486964431-@b28.c12.bise7.blackberry> Message-ID: <4E732861.1000306@pearwood.info> bodsda at googlemail.com wrote: > Hi, > > In a normal if,elif,elif,...,else statement, are the conditions checked in a linear fashion? Yes. > I am wondering if I should be making an effort to put the most likely true condition at the beginning of the block Probably not. The amount of time used in the average if...elif is unlikely to be significant itself. Don't waste your time trying to optimize something like this: if n < 0: ... elif n == 0: ... else: ... However, there are exceptions. If the tests are very expensive, then it might be worthwhile putting the most likely case first. Or at least, put the cheapest cases first, leave the expensive ones for last: if sum(mylist[1:]) > 1000 and mylist.count(42) == 3 and min(mylist) < 0: ... elif len(mylist) < 5: ... I probably should swap the order there, get the cheap len() test out of the way, and only perform the expensive test if that fails. If you have LOTS of elif cases, like *dozens*, then firstly you should think very hard about re-writing your code, because that's pretty poor design... but if you can't change the design, then maybe it is worthwhile to rearrange the cases. If you have something like this: if s == "spam": func_spam(x) elif s == "ham": func_ham(x) elif s == "cheese": func_cheese(x) you can often turn this into a dispatch table: table = {"spam": func_spam, "ham": func_ham, "cheese": func_cheese} func = table[s] # lookup in the dispatch table func(x) # finally call the function Note that inside table, you don't call the functions. This pattern is especially useful, as lookup in a table in this manner takes close enough to constant time, whether there is one item or a million. -- Steven From bodsda at googlemail.com Fri Sep 16 13:17:17 2011 From: bodsda at googlemail.com (bodsda at googlemail.com) Date: Fri, 16 Sep 2011 11:17:17 +0000 Subject: [Tutor] If statement optimization In-Reply-To: <4E732861.1000306@pearwood.info> References: <606259109-1316158883-cardhu_decombobulator_blackberry.rim.net-486964431-@b28.c12.bise7.blackberry><4E732861.1000306@pearwood.info> Message-ID: <1468017522-1316171837-cardhu_decombobulator_blackberry.rim.net-196998180-@b28.c12.bise7.blackberry> Thanks for the explanation - very clear. Cheers, Bodsda Sent from my BlackBerry? wireless device -----Original Message----- From: Steven D'Aprano <steve at pearwood.info> Sender: tutor-bounces+bodsda=googlemail.com at python.org Date: Fri, 16 Sep 2011 20:43:45 To: Tutor - python List<tutor at python.org> Subject: Re: [Tutor] If statement optimization bodsda at googlemail.com wrote: > Hi, > > In a normal if,elif,elif,...,else statement, are the conditions checked in a linear fashion? Yes. > I am wondering if I should be making an effort to put the most likely true condition at the beginning of the block Probably not. The amount of time used in the average if...elif is unlikely to be significant itself. Don't waste your time trying to optimize something like this: if n < 0: ... elif n == 0: ... else: ... However, there are exceptions. If the tests are very expensive, then it might be worthwhile putting the most likely case first. Or at least, put the cheapest cases first, leave the expensive ones for last: if sum(mylist[1:]) > 1000 and mylist.count(42) == 3 and min(mylist) < 0: ... elif len(mylist) < 5: ... I probably should swap the order there, get the cheap len() test out of the way, and only perform the expensive test if that fails. If you have LOTS of elif cases, like *dozens*, then firstly you should think very hard about re-writing your code, because that's pretty poor design... but if you can't change the design, then maybe it is worthwhile to rearrange the cases. If you have something like this: if s == "spam": func_spam(x) elif s == "ham": func_ham(x) elif s == "cheese": func_cheese(x) you can often turn this into a dispatch table: table = {"spam": func_spam, "ham": func_ham, "cheese": func_cheese} func = table[s] # lookup in the dispatch table func(x) # finally call the function Note that inside table, you don't call the functions. This pattern is especially useful, as lookup in a table in this manner takes close enough to constant time, whether there is one item or a million. -- Steven _______________________________________________ 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 Fri Sep 16 13:20:33 2011 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Fri, 16 Sep 2011 07:20:33 -0400 Subject: [Tutor] Please review my code In-Reply-To: <CAOypoo6MkkbAwHiZUp8jiEwwjABxiePafcDaS2frwC7H=OW1zw@mail.gmail.com> References: <CAOypoo6MkkbAwHiZUp8jiEwwjABxiePafcDaS2frwC7H=OW1zw@mail.gmail.com> Message-ID: <281138045873.20110916072033@columbus.rr.com> > It was only tested on a Windows Box, but I see no reason why it would not > work on Unix family. https://github.com/janus/Text-Twist > I need you comments. I think you forgot to upload some needed images along with the python code: ['abase', 'abased', 'abed', 'ads', 'baa', 'baas', 'bad', 'bade', 'bas', 'base', 'based', 'bead', 'beads', 'bed', 'beds', 'dab', 'dab s', 'debs', 'sad', 'sea'] Traceback (most recent call last): File "haPu3.py", line 36, in <module> IMAGE = PhotoImage(file=doom_image) #'C:\Python_way\doom2.gif') File "c:\python25\lib\lib-tk\Tkinter.py", line 3294, in __init__ Image.__init__(self, 'photo', name, cnf, master, **kw) File "c:\python25\lib\lib-tk\Tkinter.py", line 3250, in __init__ self.tk.call(('image', 'create', imgtype, name,) + options) _tkinter.TclError: couldn't open ".\doom2.gif": no such file or directory Alan From fomcl at yahoo.com Fri Sep 16 15:16:17 2011 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Fri, 16 Sep 2011 06:16:17 -0700 (PDT) Subject: [Tutor] Strange zip syntax In-Reply-To: <CAMb349w7UeHVAAAwx2gbimC46w1dCUfuWZ_5Pw9Z-KwH_KxTpA@mail.gmail.com> References: <CAMb349w7UeHVAAAwx2gbimC46w1dCUfuWZ_5Pw9Z-KwH_KxTpA@mail.gmail.com> Message-ID: <1316178977.44515.YahooMailNeo@web110701.mail.gq1.yahoo.com> Hi, ? I would write the slightly longer, but more readable (for me at least) code: >>> a = ['a','1','b','2','c','3'] >>> [(a[i], a[i+1]) for i in range(0, len(a), 2)] [('a', '1'), ('b', '2'), ('c', '3')] >>> zip(*[iter(a)]*2) [('a', '1'), ('b', '2'), ('c', '3')] ? And it's also faster: ? >>> import timeit >>> t = timeit.Timer("zip(*[iter(['a', '1', 'b', '2', 'c', '3'])]*2)") >>> t.timeit() 5.1758860413823555 >>> t = timeit.Timer("a=['a', '1', 'b', '2', 'c', '3']; [(a[i], a[i+1]) for i in range(0, len(a), 2)]") >>> t.timeit() 2.5330216549868823 >>> 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: Brett Ritter <swiftone at swiftone.org> >To: *tutor python <tutor at python.org> >Sent: Friday, September 16, 2011 4:35 AM >Subject: [Tutor] Strange zip syntax > >I ran into this article ( >http://blog.adku.com/2011/09/hodgepodge-of-python.html ) and found >myself temporarily stymied by one line it in: > >zip(*[iter(a)]*2) > >Used like this: > >>>> a = ['a','1','b','2','c','3'] >>>> zip(*[iter(a)]*2) >[('a', '1'), ('b', '2'), ('c', '3')] > >While I'm unlikely to use such a construct (if I can't easily follow >it now, I or my successor likely won't follow it should it need to be >debugged sometime in the future), I found the education I got in >deciphering it was worth the effort.? I'm sharing it here so others >can benefit from my puzzlement. > >iter(a) returns a list iterator for a.? See help(iter) for more. >[iter(a)] is a list containing one element, an iterator.? This is >created only so we can do the below: >[iter(a)]*2 is a list containing two elements, each the SAME list iterator. >For simplicity, let's break this out for further analysis: > >>>> b = iter(a) >>>> c = [b,b] > >*[iter(a)]*2 flattens the list when passed into a function call. >Using our more verbose but simple syntax: *c.? This only works when >passed to a function. >zip() creates tuples each holding the Nth elements from a number of >sequences.? See help(zip) for more. >Thus, zip(a) or zip(a,a) would return: >>>> zip(a) >[('a',), ('1',), ('b',), ('2',), ('c',), ('3',)] >>>> zip(a,a) >[('a', 'a'), ('1', '1'), ('b', 'b'), ('2', '2'), ('c', 'c'), ('3', '3')] > >What happens when we pass an iterator to zip?? That's not mentioned in >the docstring blurb. >>>> zip(iter(a)) >[('a',), ('1',), ('b',), ('2',), ('c',), ('3',)] >Answer: It works as intended. > >Now we come to the magic of this little snippet. >zip(iter(a),iter(a)) wouldn't work, because each call to iter(a) >returns a DIFFERENT iterator. >>>> zip(iter(a), iter(a)) >[('a', 'a'), ('1', '1'), ('b', 'b'), ('2', '2'), ('c', 'c'), ('3', '3')] > >But by creating the list of two elements each of which is the SAME >iterator, as each is asked to iterate it advances the common element >indicator: >>>> zip(*c) >[('a', '1'), ('b', '2'), ('c', '3')] >Notice that the flattening is required, because zip needs to get >multiple arguments: >>>> b = iter(a)? #our original iterator is spent, so we're assigning a new one >>>> c = [b,b] >>>> zip(c)? #Not flattened, is just a single list, like a. >[(<listiterator object at 0x024E32D0>,), (<listiterator object at 0x024E32D0>,)] >>>> zip(b,b)? # here it is two iterators sent to zip() (though they happen to be the SAME iterator) >[('a', '1'), ('b', '2'), ('c', '3')] > >I hope some of you enjoy playing with this, and hopefully someone >learned something useful!? While I'm not likely to use the listed >form, I can very well see myself saying: > >>>> a = ['a','1','b','2','c','3']? #well, I can see myself using this with meaningful variable names >>>> b = iter(a) >>>> zip(b,b)? # Group in sets of 2 elements > >-- >Brett Ritter / SwiftOne >swiftone at swiftone.org >_______________________________________________ >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: <http://mail.python.org/pipermail/tutor/attachments/20110916/9acc3e1b/attachment-0001.html> From emekamicro at gmail.com Fri Sep 16 18:18:44 2011 From: emekamicro at gmail.com (Emeka) Date: Fri, 16 Sep 2011 17:18:44 +0100 Subject: [Tutor] Strange zip syntax In-Reply-To: <CAMb349w7UeHVAAAwx2gbimC46w1dCUfuWZ_5Pw9Z-KwH_KxTpA@mail.gmail.com> References: <CAMb349w7UeHVAAAwx2gbimC46w1dCUfuWZ_5Pw9Z-KwH_KxTpA@mail.gmail.com> Message-ID: <CAOypoo4RJCyBFFkC=aiNkBMKE8Tp=Dj6o=9=FURT_q+5=1cBgw@mail.gmail.com> iBrett, iter On Fri, Sep 16, 2011 at 3:35 AM, Brett Ritter <swiftone at swiftone.org> wrote: > I ran into this article ( > http://blog.adku.com/2011/09/hodgepodge-of-python.html ) and found > myself temporarily stymied by one line it in: > > zip(*[iter(a)]*2) > > Used like this: > > >>> a = ['a','1','b','2','c','3'] > >>> zip(*[iter(a)]*2) > [('a', '1'), ('b', '2'), ('c', '3')] > > While I'm unlikely to use such a construct (if I can't easily follow > it now, I or my successor likely won't follow it should it need to be > debugged sometime in the future), I found the education I got in > deciphering it was worth the effort. I'm sharing it here so others > can benefit from my puzzlement. > > iter(a) returns a list iterator for a. See help(iter) for more. > [iter(a)] is a list containing one element, an iterator. This is > created only so we can do the below: > [iter(a)]*2 is a list containing two elements, each the SAME list iterator. > For simplicity, let's break this out for further analysis: > > >>> b = iter(a) > >>> c = [b,b] > iter(c) returns listiterator > > *[iter(a)]*2 flattens the list when passed into a function call. > Using our more verbose but simple syntax: *c. This only works when > passed to a function. > zip() creates tuples each holding the Nth elements from a number of > sequences. See help(zip) for more. > Thus, zip(a) or zip(a,a) would return: > >>> zip(a) > [('a',), ('1',), ('b',), ('2',), ('c',), ('3',)] > >>> zip(a,a) > [('a', 'a'), ('1', '1'), ('b', 'b'), ('2', '2'), ('c', 'c'), ('3', '3')] > > What happens when we pass an iterator to zip? That's not mentioned in > the docstring blurb. > >>> zip(iter(a)) > [('a',), ('1',), ('b',), ('2',), ('c',), ('3',)] > Answer: It works as intended. > > Now we come to the magic of this little snippet. > zip(iter(a),iter(a)) wouldn't work, because each call to iter(a) > returns a DIFFERENT iterator. > >>> zip(iter(a), iter(a)) > [('a', 'a'), ('1', '1'), ('b', 'b'), ('2', '2'), ('c', 'c'), ('3', '3')] > > But by creating the list of two elements each of which is the SAME > iterator, as each is asked to iterate it advances the common element > indicator: > >>> zip(*c) > [('a', '1'), ('b', '2'), ('c', '3')] > Notice that the flattening is required, because zip needs to get > multiple arguments: > >>> b = iter(a) #our original iterator is spent, so we're assigning a new > one > >>> c = [b,b] > >>> zip(c) #Not flattened, is just a single list, like a. > [(<listiterator object at 0x024E32D0>,), (<listiterator object at > 0x024E32D0>,)] > >>> zip(b,b) # here it is two iterators sent to zip() (though they happen > to be the SAME iterator) > [('a', '1'), ('b', '2'), ('c', '3')] > > I hope some of you enjoy playing with this, and hopefully someone > learned something useful! While I'm not likely to use the listed > form, I can very well see myself saying: > > >>> a = ['a','1','b','2','c','3'] #well, I can see myself using this with > meaningful variable names > >>> b = iter(a) > >>> zip(b,b) # Group in sets of 2 elements > > -- > Brett Ritter / SwiftOne > swiftone at swiftone.org > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- *Satajanus Nig. Ltd * -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110916/af4c6b7d/attachment.html> From emekamicro at gmail.com Sat Sep 17 00:09:00 2011 From: emekamicro at gmail.com (Emeka) Date: Sat, 17 Sep 2011 00:09:00 +0200 Subject: [Tutor] Please review my code In-Reply-To: <281138045873.20110916072033@columbus.rr.com> References: <CAOypoo6MkkbAwHiZUp8jiEwwjABxiePafcDaS2frwC7H=OW1zw@mail.gmail.com> <281138045873.20110916072033@columbus.rr.com> Message-ID: <CAOypoo5SSSE-uHC=UzqCwd1BxJNYGybBjsXe=WUEf_djfbbrQw@mail.gmail.com> Hello Alan, My bad, I have added the missing folder. To all, please make out time and review my code. I would like to have your comments. https://github.com/janus/Text-Twist Regards, emeka On Fri, Sep 16, 2011 at 1:20 PM, R. Alan Monroe <amonroe at columbus.rr.com>wrote: > > > It was only tested on a Windows Box, but I see no reason why it would not > > work on Unix family. https://github.com/janus/Text-Twist > > I need you comments. > > I think you forgot to upload some needed images along with the python > code: > > ['abase', 'abased', 'abed', 'ads', 'baa', 'baas', 'bad', 'bade', 'bas', > 'base', 'based', 'bead', 'beads', 'bed', 'beds', 'dab', 'dab > s', 'debs', 'sad', 'sea'] > Traceback (most recent call last): > File "haPu3.py", line 36, in <module> > IMAGE = PhotoImage(file=doom_image) #'C:\Python_way\doom2.gif') > File "c:\python25\lib\lib-tk\Tkinter.py", line 3294, in __init__ > Image.__init__(self, 'photo', name, cnf, master, **kw) > File "c:\python25\lib\lib-tk\Tkinter.py", line 3250, in __init__ > self.tk.call(('image', 'create', imgtype, name,) + options) > _tkinter.TclError: couldn't open ".\doom2.gif": no such file or directory > > Alan > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- *Satajanus Nig. Ltd * -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110917/7cbd420e/attachment.html> From lists at justuber.com Sat Sep 17 13:08:36 2011 From: lists at justuber.com (lists) Date: Sat, 17 Sep 2011 12:08:36 +0100 Subject: [Tutor] Using xml.etree Message-ID: <CANkcPmSGMG4My=wFBN+6OPP9-ABHyef7rxLj1a6zfDtbjjB80w@mail.gmail.com> Hi Tutors, I have been trying to learn how to parse XML with Python and learn how to use xml.etree. Lots of the tutorials seem to be very long winded. I'm trying to access a UK postcode API at www.uk-postcodes.com to take a UK postcode and return the lat/lng of the postcode. This is what the XML looks like: http://www.uk-postcodes.com/postcode/HU11AA.xml The function below returns a dict with the xml tag as a key and the text as a value. Is this a correct way to use xml.etree? Thanks in advance! Chris def ukpostcodesapi(postcode): import urllib import xml.etree.ElementTree as etree baseURL='http://www.uk-postcodes.com/' geocodeRequest='postcode/'+postcode+'.xml' #grab the xml tree=etree.parse(urllib.urlopen(baseURL+geocodeRequest)) root=tree.getroot() results={} for child in root[1]: #here's the geo tag results.update({child.tag:child.text}) #build a dict containing the geocode data return results #example usage (testing the function) results = ukpostcodesapi('hu11aa') print results['lat']+' '+results['lng'] From matthewpirritano at sbcglobal.net Sun Sep 18 01:51:19 2011 From: matthewpirritano at sbcglobal.net (Matthew Pirritano) Date: Sat, 17 Sep 2011 16:51:19 -0700 Subject: [Tutor] string formatting Message-ID: <001101cc7594$b37bdaf0$1a7390d0$@net> All, I know that I can do this: "the %s is %s" % ('sky', 'blue') But I have very large blocks of text and I thought there was another way like X = "sky" Y = "blue" "the %(X)s is %(Y)s" But I've tried this and it is not working. I'm just trying to get it to work in the interpreter right now. I'm using python 2.6.5. I need to use this version because it is compatible with the software that it is working with (SPSS). What am I missing? Thanks Matt -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110917/540c6d4e/attachment.html> From joel.goldstick at gmail.com Sun Sep 18 02:03:18 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sat, 17 Sep 2011 20:03:18 -0400 Subject: [Tutor] string formatting In-Reply-To: <001101cc7594$b37bdaf0$1a7390d0$@net> References: <001101cc7594$b37bdaf0$1a7390d0$@net> Message-ID: <CAPM-O+y=pb5m9N5tF8E49Hsszacqv3BhYLmDd_Edm-Wu+si2cg@mail.gmail.com> On Sat, Sep 17, 2011 at 7:51 PM, Matthew Pirritano < matthewpirritano at sbcglobal.net> wrote: > All,**** > > ** ** > > I know that I can do this:**** > > ** ** > > "the %s is %s" % ('sky', 'blue')**** > > ** ** > > But I have very large blocks of text and I thought there was another way > like**** > > ** ** > > X = ?sky?**** > > Y = ?blue?**** > > ** ** > > "the %(X)s is %(Y)s" > Try this: "the %s is %s" % (X,Y) > **** > > ** ** > > But I?ve tried this and it is not working. I?m just trying to get it to > work in the interpreter right now.**** > > ** ** > > I?m using python 2.6.5. I need to use this version because it is compatible > with the software that it is working with (SPSS).**** > > ** ** > > What am I missing?**** > > ** ** > > Thanks**** > > Matt**** > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110917/7ec0a359/attachment.html> From sivanorkin at gmail.com Sun Sep 18 02:06:26 2011 From: sivanorkin at gmail.com (Sivan Orkin) Date: Sun, 18 Sep 2011 02:06:26 +0200 Subject: [Tutor] string formatting In-Reply-To: <001101cc7594$b37bdaf0$1a7390d0$@net> References: <001101cc7594$b37bdaf0$1a7390d0$@net> Message-ID: <CANSEC=9t3x_GKd0W_=7XbkBZopEKfyNwso2ZkXfbN2qhck6pFQ@mail.gmail.com> On Sun, Sep 18, 2011 at 01:51, Matthew Pirritano < matthewpirritano at sbcglobal.net> wrote: > All,**** > > ** ** > > I know that I can do this:**** > > ** ** > > "the %s is %s" % ('sky', 'blue')**** > > ** ** > > But I have very large blocks of text and I thought there was another way > like**** > > ** ** > > X = ?sky?**** > > Y = ?blue?**** > > ** ** > > "the %(X)s is %(Y)s"**** > > ** ** > > But I?ve tried this and it is not working. I?m just trying to get it to > work in the interpreter right now.**** > > ** ** > > I?m using python 2.6.5. I need to use this version because it is compatible > with the software that it is working with (SPSS).**** > > ** ** > > What am I missing?**** > > ** ** > > Thanks**** > > Matt > Hello Matt, Your problem lies in that Python doesn't know with what to replace the %(name)s. If you use plain %s (with no name in parentheses), Python will use the order of the tuple you give as argument to % to replace the %s in the string. However, if you want to use argument names (like %(x)s), Python needs to know what to replace these with. A hint: % either takes a tuple () as argument, or a dictionary {}. A dictionary has key-value pairs; what would be the key, and what the value? Hope that helps! Sivan -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110918/b15d3bd8/attachment.html> From steve at pearwood.info Sun Sep 18 03:57:56 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 18 Sep 2011 11:57:56 +1000 Subject: [Tutor] string formatting In-Reply-To: <001101cc7594$b37bdaf0$1a7390d0$@net> References: <001101cc7594$b37bdaf0$1a7390d0$@net> Message-ID: <4E755024.3060501@pearwood.info> Matthew Pirritano wrote: > But I have very large blocks of text and I thought there was another way > like > > X = "sky" > Y = "blue" > "the %(X)s is %(Y)s" Unless you use the string formatting operator %, strings containing "%" are just strings. Large or small, the way you do string formatting is with the % operator. Python will never do string formatting without an explicit command to do so: text % value # Single non-tuple argument text % (value, value, ...) # Multiple arguments They don't have to be string literals, they can be variables: text = "Hello, I'd like to have an %s" value = "argument" print text % value You can also use named arguments by using a dictionary: text = "Hello, I'd like to have an %(X)s" values = {"X": "argument"} print text % values More details in the Fine Manual: http://docs.python.org/library/stdtypes.html#string-formatting Alternatives include the new advanced formatting method: text.format() http://docs.python.org/library/string.html#formatstrings and "$" substitutions with the string module: import string string.Template http://docs.python.org/library/string.html#template-strings -- Steven From emailkgnow at gmail.com Sun Sep 18 11:57:22 2011 From: emailkgnow at gmail.com (Khalid Al-Ghamdi) Date: Sun, 18 Sep 2011 12:57:22 +0300 Subject: [Tutor] why is this so? Message-ID: <CABM2kurBwBaj=5UTimqXdpNpm1GsRGT+Yx1D7j=tqHLHWFqRYg@mail.gmail.com> Hi All, why is this so? >>> type('love') <class 'str'> >>> "love" is str False >>> -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110918/8bc0ef86/attachment.html> From rafadurancastaneda at gmail.com Sun Sep 18 13:13:28 2011 From: rafadurancastaneda at gmail.com (=?ISO-8859-1?Q?Rafael_Dur=E1n_Casta=F1eda?=) Date: Sun, 18 Sep 2011 13:13:28 +0200 Subject: [Tutor] why is this so? In-Reply-To: <CABM2kurBwBaj=5UTimqXdpNpm1GsRGT+Yx1D7j=tqHLHWFqRYg@mail.gmail.com> References: <CABM2kurBwBaj=5UTimqXdpNpm1GsRGT+Yx1D7j=tqHLHWFqRYg@mail.gmail.com> Message-ID: <CAH+GN=0RvCSWmQFExL+=guNDX1Pmmv=TOur=FE1c7USmWL-Ahw@mail.gmail.com> You are comparing a string value with string class, so they can't be compared. You can do: >>> type("love") is str True >>> so you compare types 2011/9/18 Khalid Al-Ghamdi <emailkgnow at gmail.com> > Hi All, > > why is this so? > > >>> type('love') > <class 'str'> > >>> "love" is str > False > >>> > > _______________________________________________ > 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: <http://mail.python.org/pipermail/tutor/attachments/20110918/9ae6fce0/attachment.html> From steve at pearwood.info Sun Sep 18 14:46:51 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 18 Sep 2011 22:46:51 +1000 Subject: [Tutor] why is this so? In-Reply-To: <CABM2kurBwBaj=5UTimqXdpNpm1GsRGT+Yx1D7j=tqHLHWFqRYg@mail.gmail.com> References: <CABM2kurBwBaj=5UTimqXdpNpm1GsRGT+Yx1D7j=tqHLHWFqRYg@mail.gmail.com> Message-ID: <4E75E83B.9080303@pearwood.info> Khalid Al-Ghamdi wrote: > Hi All, > > why is this so? > >>>> type('love') > <class 'str'> >>>> "love" is str > False The "is" operator tests for object identity. The line "love" is str tests whether the instance "love" is the same object as the class str. Obviously that is not the case. You might be thinking of an "is-a" test: "love" is a string? For that, you want: isinstance("love", str) which returns True. (That's better than type("love") is str, since it will work for subclasses as well.) But before getting too used to isinstance, you should read this article: http://www.canonical.org/~kragen/isinstance/ -- Steven From lists at justuber.com Mon Sep 19 11:46:13 2011 From: lists at justuber.com (lists) Date: Mon, 19 Sep 2011 10:46:13 +0100 Subject: [Tutor] Using xml.etree In-Reply-To: <CANkcPmSGMG4My=wFBN+6OPP9-ABHyef7rxLj1a6zfDtbjjB80w@mail.gmail.com> References: <CANkcPmSGMG4My=wFBN+6OPP9-ABHyef7rxLj1a6zfDtbjjB80w@mail.gmail.com> Message-ID: <CANkcPmQER_Vv=kU4O1wtekQL5uWwbJqSkes2nYSWRfV1gULaaQ@mail.gmail.com> Hello again. So, any xml.etree experts out there who might have missed this over the weekend? Thanks in advance! Chris From mail at timgolden.me.uk Mon Sep 19 12:01:00 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 19 Sep 2011 11:01:00 +0100 Subject: [Tutor] Using xml.etree In-Reply-To: <CANkcPmQER_Vv=kU4O1wtekQL5uWwbJqSkes2nYSWRfV1gULaaQ@mail.gmail.com> References: <CANkcPmSGMG4My=wFBN+6OPP9-ABHyef7rxLj1a6zfDtbjjB80w@mail.gmail.com> <CANkcPmQER_Vv=kU4O1wtekQL5uWwbJqSkes2nYSWRfV1gULaaQ@mail.gmail.com> Message-ID: <4E7712DC.3070507@timgolden.me.uk> On 19/09/2011 10:46, lists wrote: > Hello again. > > So, any xml.etree experts out there who might have missed this over the weekend? Not me, I'm afraid, but might I suggest that you ask on the mail Python list: http://mail.python.org/mailman/listinfo/python-list There's nothing wrong with asking here, but since this question is more specific to a particular library than to Python-the-language you're more likely to find people familiar with the package (including its maintainer in fact...) TJG From mail at timgolden.me.uk Mon Sep 19 12:05:57 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 19 Sep 2011 11:05:57 +0100 Subject: [Tutor] Using xml.etree In-Reply-To: <4E7712DC.3070507@timgolden.me.uk> References: <CANkcPmSGMG4My=wFBN+6OPP9-ABHyef7rxLj1a6zfDtbjjB80w@mail.gmail.com> <CANkcPmQER_Vv=kU4O1wtekQL5uWwbJqSkes2nYSWRfV1gULaaQ@mail.gmail.com> <4E7712DC.3070507@timgolden.me.uk> Message-ID: <4E771405.6000202@timgolden.me.uk> On 19/09/2011 11:01, Tim Golden wrote: > you're more likely to find people familiar with the package (including > its maintainer in fact...) Sorry, I misread your post and thought you were referring lxml.etree (which is a 3rd-party lib). My basic point still stands, though: you'll get more library-specific help on python-list. TJG From lists at justuber.com Mon Sep 19 13:47:51 2011 From: lists at justuber.com (lists) Date: Mon, 19 Sep 2011 12:47:51 +0100 Subject: [Tutor] Using xml.etree In-Reply-To: <4E771405.6000202@timgolden.me.uk> References: <CANkcPmSGMG4My=wFBN+6OPP9-ABHyef7rxLj1a6zfDtbjjB80w@mail.gmail.com> <CANkcPmQER_Vv=kU4O1wtekQL5uWwbJqSkes2nYSWRfV1gULaaQ@mail.gmail.com> <4E7712DC.3070507@timgolden.me.uk> <4E771405.6000202@timgolden.me.uk> Message-ID: <CANkcPmQ8HYq=kXdQ6zLJCcbJkoF310DXuJNcuG-qa61LorT-+w@mail.gmail.com> Thanks Tim, Will do. Chris On Mon, Sep 19, 2011 at 11:05 AM, Tim Golden <mail at timgolden.me.uk> wrote: > On 19/09/2011 11:01, Tim Golden wrote: >> >> you're more likely to find people familiar with the package (including >> its maintainer in fact...) > > Sorry, I misread your post and thought you were referring lxml.etree > (which is a 3rd-party lib). My basic point still stands, though: > you'll get more library-specific help on python-list. > > TJG > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From ashish.gec at gmail.com Mon Sep 19 15:27:26 2011 From: ashish.gec at gmail.com (Ashish Gaonker) Date: Mon, 19 Sep 2011 18:57:26 +0530 Subject: [Tutor] How it is better than java Message-ID: <CAC88qxfnUOCorLUOpYZXZXycT2OZXBPUztx9iJoO7rLuC1Yjuw@mail.gmail.com> My obvious thinking is : Java being compiled language , must be faster then a interpreted language. I know couple of points : Development time is less + easy to learn + python is expressive. Can you share some more especially as compared to Java / .net (two primarily used languages in enterprise language & web based applications) -- Thanks & Regards Ashish Gaonker -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110919/333f652c/attachment.html> From cwitts at compuscan.co.za Mon Sep 19 15:53:53 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Mon, 19 Sep 2011 15:53:53 +0200 Subject: [Tutor] How it is better than java In-Reply-To: <CAC88qxfnUOCorLUOpYZXZXycT2OZXBPUztx9iJoO7rLuC1Yjuw@mail.gmail.com> References: <CAC88qxfnUOCorLUOpYZXZXycT2OZXBPUztx9iJoO7rLuC1Yjuw@mail.gmail.com> Message-ID: <4E774971.4020306@compuscan.co.za> On 2011/09/19 03:27 PM, Ashish Gaonker wrote: > My obvious thinking is : Java being compiled language , must be faster > then a interpreted language. > > I know couple of points : Development time is less + easy to learn + > python is expressive. > > Can you share some more especially as compared to Java / .net (two > primarily used languages in enterprise language & web based applications) > > -- > Thanks & Regards > Ashish Gaonker > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor I would suggest reading `Python is not Java` [1] and `Java is not Python, either` [2], old but good reads. And then ask what is your focus for development. Better is extremely subjective and can be liable to induce flame-wars, although this list is quite friendly. To me, I started using Python as a glue language, controlling process flows and the like, with still heavy uses of C and PL/SQL for what I do. Over time Python has taken center-stage for my projects due to ease-of-use and rapid application development and only moving time critical work that "needs" to be faster to C but in most cases that is not needed for me anymore. Add to that the great work on PyPy [3] which is extremely efficient, I hardly ever have to write in another language if I don't wish. [1] http://dirtsimple.org/2004/12/python-is-not-java.html [2] http://dirtsimple.org/2004/12/java-is-not-python-either.html [3] http://pypy.org/ -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110919/739dfb17/attachment.html> From wprins at gmail.com Mon Sep 19 16:13:16 2011 From: wprins at gmail.com (Walter Prins) Date: Mon, 19 Sep 2011 15:13:16 +0100 Subject: [Tutor] How it is better than java In-Reply-To: <CAC88qxfnUOCorLUOpYZXZXycT2OZXBPUztx9iJoO7rLuC1Yjuw@mail.gmail.com> References: <CAC88qxfnUOCorLUOpYZXZXycT2OZXBPUztx9iJoO7rLuC1Yjuw@mail.gmail.com> Message-ID: <CANLXbfB38m6znLAu9Po8+cj9jK1viZvBJ1F6Xc2199_B6o2XHw@mail.gmail.com> Hi Ashish, On 19 September 2011 14:27, Ashish Gaonker <ashish.gec at gmail.com> wrote: > My obvious thinking is : Java being compiled language , must be faster then > a interpreted language. > > I know couple of points : Development time is less + easy to learn + python > is expressive. > > Can you share some more especially as compared to Java / .net (two > primarily used languages in enterprise language & web based applications) > There's many pages on the internet comparing Python, Java and other languages. I suggest you check them out. Having said that, I'll point out that Python has several implementations, including one called "Jython", which actually targets the Java runtime and so should have comparable performance to Java on the same runtime. Additionally there's projects like PyPy which in some cases is faster even than C/C++. This page (from my bookmarks) has some interesting points of comparison for consideration: http://pythonconquerstheuniverse.wordpress.com/category/java-and-python/ Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110919/c02255d1/attachment.html> From MPirritano at ochca.com Mon Sep 19 17:46:27 2011 From: MPirritano at ochca.com (Pirritano, Matthew) Date: Mon, 19 Sep 2011 08:46:27 -0700 Subject: [Tutor] string formatting In-Reply-To: <4E755024.3060501@pearwood.info> References: <001101cc7594$b37bdaf0$1a7390d0$@net> <4E755024.3060501@pearwood.info> Message-ID: <A715D7E005BF1C4D8505CA3CABB748F205609FC3@HCAMAIL03.ochca.com> Pythonistas, This is the resolution of a question I asked over the weekend. The method I was thinking of was in a program I wrote on my work computer but couldn't remember. Now I'm at work and I see. It is not including the tuple at the end of the string nor using a dictionary. There is another way using locals(). I was trying to remember this method: You some variables say: X = "sky" Y = "blue" Print "the %(x)s is %(y)s" % locals() the sky is blue That works! And in cases where I'm replacing over 20 strings it's much easier than having to include a tuple at the end. Especially when there's only two or three variables I'm replacing repeatedly, in which case a dictionary seems like overkill. Thanks Matt Matthew Pirritano, Ph.D. Research Analyst IV Medical Services Initiative (MSI) Orange County Health Care Agency (714) 568-5648 -----Original Message----- From: tutor-bounces+mpirritano=ochca.com at python.org [mailto:tutor-bounces+mpirritano=ochca.com at python.org] On Behalf Of Steven D'Aprano Sent: Saturday, September 17, 2011 6:58 PM To: tutor at python.org Subject: Re: [Tutor] string formatting Matthew Pirritano wrote: > But I have very large blocks of text and I thought there was another way > like > > X = "sky" > Y = "blue" > "the %(X)s is %(Y)s" Unless you use the string formatting operator %, strings containing "%" are just strings. Large or small, the way you do string formatting is with the % operator. Python will never do string formatting without an explicit command to do so: text % value # Single non-tuple argument text % (value, value, ...) # Multiple arguments They don't have to be string literals, they can be variables: text = "Hello, I'd like to have an %s" value = "argument" print text % value You can also use named arguments by using a dictionary: text = "Hello, I'd like to have an %(X)s" values = {"X": "argument"} print text % values More details in the Fine Manual: http://docs.python.org/library/stdtypes.html#string-formatting Alternatives include the new advanced formatting method: text.format() http://docs.python.org/library/string.html#formatstrings and "$" substitutions with the string module: import string string.Template http://docs.python.org/library/string.html#template-strings -- Steven _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From waynejwerner at gmail.com Mon Sep 19 19:47:01 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Mon, 19 Sep 2011 12:47:01 -0500 Subject: [Tutor] string formatting In-Reply-To: <A715D7E005BF1C4D8505CA3CABB748F205609FC3@HCAMAIL03.ochca.com> References: <001101cc7594$b37bdaf0$1a7390d0$@net> <4E755024.3060501@pearwood.info> <A715D7E005BF1C4D8505CA3CABB748F205609FC3@HCAMAIL03.ochca.com> Message-ID: <CAPM86NekyT6txmaHJ5_ZMh3Vg_QCVvZsEGrfaMyxL5Z3yWoGVg@mail.gmail.com> On Mon, Sep 19, 2011 at 10:46 AM, Pirritano, Matthew <MPirritano at ochca.com>wrote: > <snip> You some variables say: > > X = "sky" > Y = "blue" > > Print "the %(x)s is %(y)s" % locals() > > the sky is blue > > That works! And in cases where I'm replacing over 20 strings it's much > easier than having to include a tuple at the end. Especially when > there's only two or three variables I'm replacing repeatedly, in which > case a dictionary seems like overkill. > I suspect your email program auto-capitalized the initial X and Y, and P for you, as that code would actually create a syntax and KeyError (or two). Technically speaking, locals() is already dictionary: >>> type(locals()) <class 'dict'> and just for the sake of completeness, in newer (2.6(?) or greater) versions of Python, you can use the format() method: x = 'sky' y = 'blue' print('The {x} is {y}.'.format(locals())) HTH, -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110919/d5d91ca9/attachment.html> From bodsda at googlemail.com Mon Sep 19 20:11:00 2011 From: bodsda at googlemail.com (bodsda at googlemail.com) Date: Mon, 19 Sep 2011 18:11:00 +0000 Subject: [Tutor] string formatting In-Reply-To: <CAPM86NekyT6txmaHJ5_ZMh3Vg_QCVvZsEGrfaMyxL5Z3yWoGVg@mail.gmail.com> References: <001101cc7594$b37bdaf0$1a7390d0$@net><4E755024.3060501@pearwood.info><A715D7E005BF1C4D8505CA3CABB748F205609FC3@HCAMAIL03.ochca.com><CAPM86NekyT6txmaHJ5_ZMh3Vg_QCVvZsEGrfaMyxL5Z3yWoGVg@mail.gmail.com> Message-ID: <1299425079-1316455860-cardhu_decombobulator_blackberry.rim.net-1619700894-@b28.c12.bise7.blackberry> Is there any additional overhead of using the locals() or format(locals()) instead of a tuple? - the format option is a double function call so I would expect that to be considerably slower Thanks, Bodsda -- my phone won't let me bottom post, sorry Sent from my BlackBerry? wireless device -----Original Message----- From: Wayne Werner <waynejwerner at gmail.com> Sender: tutor-bounces+bodsda=googlemail.com at python.org Date: Mon, 19 Sep 2011 12:47:01 To: Pirritano, Matthew<MPirritano at ochca.com> Cc: <tutor at python.org> Subject: Re: [Tutor] string formatting _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From waynejwerner at gmail.com Mon Sep 19 20:43:42 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Mon, 19 Sep 2011 13:43:42 -0500 Subject: [Tutor] string formatting In-Reply-To: <1299425079-1316455860-cardhu_decombobulator_blackberry.rim.net-1619700894-@b28.c12.bise7.blackberry> References: <001101cc7594$b37bdaf0$1a7390d0$@net> <4E755024.3060501@pearwood.info> <A715D7E005BF1C4D8505CA3CABB748F205609FC3@HCAMAIL03.ochca.com> <CAPM86NekyT6txmaHJ5_ZMh3Vg_QCVvZsEGrfaMyxL5Z3yWoGVg@mail.gmail.com> <1299425079-1316455860-cardhu_decombobulator_blackberry.rim.net-1619700894-@b28.c12.bise7.blackberry> Message-ID: <CAPM86NcHg=b2S5pNaoD-BddUN89xC3VUR+X6_UCYnGyd==vwZQ@mail.gmail.com> On Mon, Sep 19, 2011 at 1:11 PM, <bodsda at googlemail.com> wrote: > Is there any additional overhead of using the locals() or format(locals()) > instead of a tuple? - the format option is a double function call so I would > expect that to be considerably slower > Using the following code and timeit, it appears that there is a difference, but unless you call 0.3-6 ns considerable (assuming I got my math correct: The difference was ~1.2 or ~1.3 seconds for the classic, ~1.9 for the % locals version, and timeit runs 1,000,000 times with the default settings), then the difference isn't terrible. -Wayne from __future__ import print_function import timeit def classicwithlocals(): x = 'hello' from __future__ import print_function import timeit def classicwithlocals(): x = 'hello' y = 'goodbye' combined = 'You say %(x)s, and I say %(y)s' % locals() def classicwithtuple(): x = 'hello' y = 'goodbye' combined = 'You say %s, and I say %s' % (x, y) def withargs(): x = 'hello' y = 'goodbye' combined = 'You say {0}, and I say {1}'.format(x, y) for f in [withargs, classicwithtuple, classicwithlocals]: t = timeit.Timer(f) print(t.timeit()) -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110919/2a034615/attachment.html> From nozarm at triumf.ca Mon Sep 19 20:22:30 2011 From: nozarm at triumf.ca (Mina Nozar) Date: Mon, 19 Sep 2011 11:22:30 -0700 Subject: [Tutor] OptionParser Message-ID: <4E778866.9040905@triumf.ca> Hello, I am trying to use OptionParser (my first time) to set a variable (cvs_output). i.e. if --csv is given in the list of options, then cvs_output = True. Then I check, if cvs_output == True: [...] I have the following so far but something is missing. from optparse import OptionParser usage = "usage: %prog [options]" parser = OptionParser(usage=usage) parser.add_option("-cvs", dest="output", default=True, help="outputs the csv file for plotting activites") python dUCx_ActivityPlots.py python dUCx_ActivityPlots.2.py -h Usage: dUCx_ActivityPlots.2.py [options] Options: -h, --help show this help message and exit --cvs=OUTPUT_FLAG outputs the csv file for plotting activities I don't really understand what dest and action in the arguments to parser.add_option mean. Any help is appreciated. Mina -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110919/3c570d04/attachment.html> From waynejwerner at gmail.com Mon Sep 19 21:05:57 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Mon, 19 Sep 2011 14:05:57 -0500 Subject: [Tutor] OptionParser In-Reply-To: <4E778866.9040905@triumf.ca> References: <4E778866.9040905@triumf.ca> Message-ID: <CAPM86Ne-ULUvD2_+oK=y8EbfMN5TmJPC1jocU-j-w9bLvv=hkg@mail.gmail.com> On Mon, Sep 19, 2011 at 1:22 PM, Mina Nozar <nozarm at triumf.ca> wrote: > ** > I don't really understand what dest and action in the arguments to > parser.add_option mean. > Any help is appreciated. > Have you read the fine manual, specifically the sections here: http://docs.python.org/library/optparse.html#optparse-standard-option-actions and here: http://docs.python.org/library/optparse.html#option-attributes Additionaly, I'm not sure you copied your code correctly, because after a copy and paste I get this: $ python localtest.py Traceback (most recent call last): File "localtest.py", line 5, in <module> parser.add_option("-cvs", dest="output", default=True, help="outputs the csv file for plotting activites") File "/usr/lib/python2.6/optparse.py", line 1012, in add_option option = self.option_class(*args, **kwargs) File "/usr/lib/python2.6/optparse.py", line 566, in __init__ self._set_opt_strings(opts) File "/usr/lib/python2.6/optparse.py", line 606, in _set_opt_strings self) optparse.OptionError: invalid long option string '-cvs': must start with --, followed by non-dash and when I correct that: $ python localtest.py -h uwwerne at WWERNER /c $ I get no output. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110919/a107a762/attachment-0001.html> From sander.sweers at gmail.com Mon Sep 19 22:20:12 2011 From: sander.sweers at gmail.com (Sander Sweers) Date: Mon, 19 Sep 2011 22:20:12 +0200 Subject: [Tutor] Using xml.etree In-Reply-To: <CANkcPmSGMG4My=wFBN+6OPP9-ABHyef7rxLj1a6zfDtbjjB80w@mail.gmail.com> References: <CANkcPmSGMG4My=wFBN+6OPP9-ABHyef7rxLj1a6zfDtbjjB80w@mail.gmail.com> Message-ID: <4E77A3FC.4080103@gmail.com> On 17/09/11 13:08, lists wrote: > I have been trying to learn how to parse XML with Python and learn how > to use xml.etree. Lots of the tutorials seem to be very long winded. > > I'm trying to access a UK postcode API at www.uk-postcodes.com to take > a UK postcode and return the lat/lng of the postcode. This is what the > XML looks like: http://www.uk-postcodes.com/postcode/HU11AA.xml > > The function below returns a dict with the xml tag as a key and the > text as a value. Is this a correct way to use xml.etree? Define correct, does it give the desired result? Then I would say yes it is correct. There may be alternative ways to get to the same result though. > def ukpostcodesapi(postcode): > import urllib Why do the import here, for speed? You are reading an xml file from the internet, guess where most of the time is spend in your function ;-). > import xml.etree.ElementTree as etree > > baseURL='http://www.uk-postcodes.com/' > geocodeRequest='postcode/'+postcode+'.xml' You could use string formatting here. url = 'http://www.uk-postcodes.com/postcode/%s.xml' % postcode Also what would happen if postcode includes a space? > > #grab the xml > tree=etree.parse(urllib.urlopen(baseURL+geocodeRequest)) What happens if you get an error (a 404 error perhaps)? You might want to add a try/except block around reading the xml from the internet. > root=tree.getroot() > results={} > for child in root[1]: #here's the geo tag > results.update({child.tag:child.text}) #build a dict containing the > geocode data > return results As you only get 1 set of long/lat tags in the xml you could use find(). See below an example. from xml.etree import ElementTree as ET import urllib2 url = 'http://www.uk-postcodes.com/postcode/HU11AA.xml' xml = urllib2.urlopen(url).read() tree = ET.XML(xml) geo = {} for leaf in tree.find('geo'): geo[leaf.tag] = leaf.text Greets Sander From lists at justuber.com Tue Sep 20 00:33:10 2011 From: lists at justuber.com (lists) Date: Mon, 19 Sep 2011 23:33:10 +0100 Subject: [Tutor] Using xml.etree In-Reply-To: <4E77A3FC.4080103@gmail.com> References: <CANkcPmSGMG4My=wFBN+6OPP9-ABHyef7rxLj1a6zfDtbjjB80w@mail.gmail.com> <4E77A3FC.4080103@gmail.com> Message-ID: <CANkcPmRk9GBmoBggDC46Jdo4w1jRAyU7qze5pAZd4sioz2GrKg@mail.gmail.com> On Mon, Sep 19, 2011 at 9:20 PM, Sander Sweers <sander.sweers at gmail.com> wrote: > On 17/09/11 13:08, lists wrote: >> >> I have been trying to learn how to parse XML with Python and learn how >> to use xml.etree. Lots of the tutorials seem to be very long winded. >> >> I'm trying to access a UK postcode API at www.uk-postcodes.com to take >> a UK postcode and return the lat/lng of the postcode. This is what the >> XML looks like: http://www.uk-postcodes.com/postcode/HU11AA.xml >> >> The function below returns a dict with the xml tag as a key and the >> text as a value. Is this a correct way to use xml.etree? > > Define correct, does it give the desired result? Then I would say yes it is > correct. There may be alternative ways to get to the same result though. > >> def ukpostcodesapi(postcode): >> ? ? ? ?import urllib > > Why do the import here, for speed? You are reading an xml file from the > internet, guess where most of the time is spend in your function ;-). > >> ? ? ? ?import xml.etree.ElementTree as etree >> >> ? ? ? ?baseURL='http://www.uk-postcodes.com/' >> ? ? ? ? geocodeRequest='postcode/'+postcode+'.xml' > > You could use string formatting here. > ?url = 'http://www.uk-postcodes.com/postcode/%s.xml' % postcode > > Also what would happen if postcode includes a space? > >> >> ? ? ? ?#grab the xml >> ? ? ? ?tree=etree.parse(urllib.urlopen(baseURL+geocodeRequest)) > > What happens if you get an error (a 404 error perhaps)? You might want to > add a try/except block around reading the xml from the internet. > >> ? ? ? ?root=tree.getroot() >> ? ? ? ?results={} >> ? ? ? ?for child in root[1]: #here's the geo tag >> ? ? ? ? ? ? ? ?results.update({child.tag:child.text}) #build a dict >> containing the >> geocode data >> ? ? ? ?return results > > As you only get 1 set of long/lat tags in the xml you could use find(). See > below an example. > > from xml.etree import ElementTree as ET > import urllib2 > > url = 'http://www.uk-postcodes.com/postcode/HU11AA.xml' > xml = urllib2.urlopen(url).read() > tree = ET.XML(xml) > > geo = {} > > for leaf in tree.find('geo'): > ? ?geo[leaf.tag] = leaf.text > > Greets > Sander Thank you I've been working on this and ended up with http://pastebin.com/Y9keC9tB Chris From g.nius.ck at gmail.com Tue Sep 20 00:55:19 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Mon, 19 Sep 2011 18:55:19 -0400 Subject: [Tutor] iretator.send Message-ID: <CAKBg9Z0unB1XBJD9vPxM4AVo+Ywcp+s5QHMXjT84RQ1h9G0RaQ@mail.gmail.com> Dear tutor dudes, I know that a for loop uses a an iterators next method in this way for variable in iterator: execute_code(variable) is equivalent to while True: try: variable = iterator.next() except StopIteration: break else: execute_code(variable) Is there any syntax that uses the send method of an iterator? -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110919/568727e0/attachment.html> From steve at pearwood.info Tue Sep 20 02:30:02 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 20 Sep 2011 10:30:02 +1000 Subject: [Tutor] iretator.send In-Reply-To: <CAKBg9Z0unB1XBJD9vPxM4AVo+Ywcp+s5QHMXjT84RQ1h9G0RaQ@mail.gmail.com> References: <CAKBg9Z0unB1XBJD9vPxM4AVo+Ywcp+s5QHMXjT84RQ1h9G0RaQ@mail.gmail.com> Message-ID: <4E77DE8A.5060905@pearwood.info> Christopher King wrote: > Is there any syntax that uses the send method of an iterator? No. -- Steven From steve at pearwood.info Tue Sep 20 02:27:12 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 20 Sep 2011 10:27:12 +1000 Subject: [Tutor] How it is better than java In-Reply-To: <CAC88qxfnUOCorLUOpYZXZXycT2OZXBPUztx9iJoO7rLuC1Yjuw@mail.gmail.com> References: <CAC88qxfnUOCorLUOpYZXZXycT2OZXBPUztx9iJoO7rLuC1Yjuw@mail.gmail.com> Message-ID: <4E77DDE0.2020906@pearwood.info> Ashish Gaonker wrote: > My obvious thinking is : Java being compiled language , must be faster then > a interpreted language. There are three misunderstandings with that statement. Firstly: Languages are neither "compiled" or "interpreted". Languages are syntax and grammar. Implementations are either compiled, or interpreted, or both: for example, there are C interpreters and C compilers. And the quality of both can vary significantly. Asking which language is faster is like asking which is faster, Ford or Toyota? That depends on the particular model, and the conditions, and the skill of the driver. It is ironic that you contrast Java as "compiled" and Python as "interpreted", because that is *marketing*. When Java first came out, Sun didn't want people describing it as "interpreted", which it was, so they popularized the term "byte-code compiler" just so that they could talk about Java being compiled. Java would compile your Java source code to byte-code which was then interpreted by a virtual machine. That is *exactly* what Python does: it compiles Python source code to byte-code which is interpreted by a virtual machine, just like Java. What do you think the .pyc files contain, and what the compile() function does? And yet, even back in the 1980s, everybody swallowed Sun's marketing and called Java a compiled language and Python an interpreted language. This is a testament to Sun spending millions in advertising. Byte-code compilation is a lot older than Java. Pascal used something similar in the early 1970s, called a p-machine. Even Apple's Hypertalk did the same thing, only they called it "tokenized" code instead of compiled. Java's big innovation was to convince people to use the term "compiler" for what was functionally identical to an interpreter. Of course, Sun (now owned by Oracle) put in a lot of money into Java. Millions. Today, Java does have implementations which compile source code to machine code. But there are Python implementations that do the same, such as Nuitka and Compyler. (I don't know how successful or good they are.) Secondly, what do you mean by "faster"? Faster to write? Faster to compile? Faster to run? Faster for the engine to start up? Even today, after Sun has spent tens of millions on Java development, the Java Runtime Environment is a big, heavyweight machine that takes a long time to start up: cold starts can easily take 30 seconds. That makes Java completely unsuitable for small, lightweight tasks: in the time it takes for a *single* Java program just to start up, you could possibly run a dozen Python programs or a hundred interpreted bash scripts. But again, that's an *implementation*, not a hard rule about Java. There is at least one third-party JRE which claims to have startup times twice as fast as the Sun/Oracle JRE. Either way, once you take startup time into account, sometimes Python scripts are not only faster to write and faster to maintain, but faster to run as well. Thirdly, there is no rule of nature that a compiled program to do a job must be faster than an interpreted program to do the same thing. This depends entirely on the quality of implementation of both: a poor compiler may easily generate bad, slow code that takes longer to run than a wickedly fast and efficient interpreter. E.g. a compiled version of bubblesort will still be slower than an interpreted version of quicksort. Nothing drives this home more than PyPy, a Just In Time optimizing version of Python. PyPy uses a JIT compiler to run code sometimes FASTER than the equivalent program in optimized C. Yes. Faster than C. You read that right. http://morepypy.blogspot.com/2008/01/rpython-can-be-faster-than-c.html http://morepypy.blogspot.com/2011/02/pypy-faster-than-c-on-carefully-crafted.html http://morepypy.blogspot.com/2011/08/pypy-is-faster-than-c-again-string.html Of course, benchmarks are notoriously flawed, especially micro- benchmarks. What they *really* answer is not "which language is faster?" (a nonsense question, as I have tried to explain) but "which implementation is faster with these particular settings on this particular task?", a much more practical question. As exciting as it is to see Python code run faster than C code, it shouldn't really surprise anyone that a JIT dynamic compiler with cross module optimization beats a static compiler without it. What *is* surprising is that a small group of open-source developers have been able to build an optimizing JIT compiler for Python of such quality. Or at least, it is surprising to people who think that quality code can only come from big proprietary companies with huge budgets. What's really exciting though is that now PyPy can be fast enough for large programs that traditionally needed to be written in C can now be (sometimes!) written in Python: http://morepypy.blogspot.com/2011/07/realtime-image-processing-in-python.html Who cares whether Java, or C, is "faster" than Python? The important question should be, is Python fast enough for the job I have to do? > Can you share some more especially as compared to Java / .net (two primarily > used languages in enterprise language & web based applications) You can look at Jython (Python for the JRE) and IronPython (Python for .Net). There is also an older implementation, Python For .Net, which runs the standard CPython implementation on .Net, but I don't think it is still maintained -- IronPython has taken over its niche. There's also JPype, which claims to give full access to Java libraries in Python. -- Steven From steve at pearwood.info Tue Sep 20 03:11:42 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 20 Sep 2011 11:11:42 +1000 Subject: [Tutor] string formatting In-Reply-To: <CAPM86NcHg=b2S5pNaoD-BddUN89xC3VUR+X6_UCYnGyd==vwZQ@mail.gmail.com> References: <001101cc7594$b37bdaf0$1a7390d0$@net> <4E755024.3060501@pearwood.info> <A715D7E005BF1C4D8505CA3CABB748F205609FC3@HCAMAIL03.ochca.com> <CAPM86NekyT6txmaHJ5_ZMh3Vg_QCVvZsEGrfaMyxL5Z3yWoGVg@mail.gmail.com> <1299425079-1316455860-cardhu_decombobulator_blackberry.rim.net-1619700894-@b28.c12.bise7.blackberry> <CAPM86NcHg=b2S5pNaoD-BddUN89xC3VUR+X6_UCYnGyd==vwZQ@mail.gmail.com> Message-ID: <4E77E84E.9040708@pearwood.info> Wayne Werner wrote: > On Mon, Sep 19, 2011 at 1:11 PM, <bodsda at googlemail.com> wrote: > >> Is there any additional overhead of using the locals() or format(locals()) >> instead of a tuple? - the format option is a double function call so I would >> expect that to be considerably slower >> > > Using the following code and timeit, it appears that there is a difference, > but unless you call 0.3-6 ns considerable (assuming I got my math correct: > The difference was ~1.2 or ~1.3 seconds for the classic, ~1.9 for the % > locals version, and timeit runs 1,000,000 times with the default settings), > then the difference isn't terrible. I get similar speeds with Python 2.7: >>> for f in [withargs, classicwithtuple, classicwithlocals]: ... t = timeit.Timer(f) ... print(t.timeit()) ... 1.72170519829 1.18233394623 1.96000385284 However, a single reading with timeit is subject to a lot of noise. Trying again: >>> for f in [withargs, classicwithtuple, classicwithlocals]: ... t = timeit.Timer(f) ... print(min(t.repeat(repeat=5))) # Best of five runs. ... 1.19279980659 1.01878404617 1.56821203232 So, roughly speaking, it looks like the format method is about 20% slower than % with a tuple, and using locals is about 60% slower. -- Steven From quasipedia at gmail.com Tue Sep 20 10:21:06 2011 From: quasipedia at gmail.com (Mac Ryan) Date: Tue, 20 Sep 2011 10:21:06 +0200 Subject: [Tutor] How it is better than java In-Reply-To: <4E77DDE0.2020906@pearwood.info> References: <CAC88qxfnUOCorLUOpYZXZXycT2OZXBPUztx9iJoO7rLuC1Yjuw@mail.gmail.com> <4E77DDE0.2020906@pearwood.info> Message-ID: <20110920102106.5c34d212@jabbar> On Tue, 20 Sep 2011 10:27:12 +1000 Steven D'Aprano <steve at pearwood.info> wrote: > There are three misunderstandings with that statement. > [snip] > There's also JPype, which claims to give full access to Java > libraries in Python. Now: this was one of the best write-ups on the subject I read. Concise, clear, documented. Nice way to start the day! :o /mac From waynejwerner at gmail.com Tue Sep 20 16:04:17 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Tue, 20 Sep 2011 09:04:17 -0500 Subject: [Tutor] How it is better than java In-Reply-To: <20110920102106.5c34d212@jabbar> References: <CAC88qxfnUOCorLUOpYZXZXycT2OZXBPUztx9iJoO7rLuC1Yjuw@mail.gmail.com> <4E77DDE0.2020906@pearwood.info> <20110920102106.5c34d212@jabbar> Message-ID: <CAPM86Ne+pDTa75bPzJSTvtnK9dyiKf96OTH2iv06yjrBTvUUkA@mail.gmail.com> On Tue, Sep 20, 2011 at 3:21 AM, Mac Ryan <quasipedia at gmail.com> wrote: > On Tue, 20 Sep 2011 10:27:12 +1000 > Steven D'Aprano <steve at pearwood.info> wrote: > > > > There are three misunderstandings with that statement. > > [snip] > > There's also JPype, which claims to give full access to Java > > libraries in Python. > > Now: this was one of the best write-ups on the subject I read. Concise, > clear, documented. Nice way to start the day! :o Ditto - and as a slight aside, it's interesting to note that .NET languages (VB, C# specifically) are also compiled into the MSIL which can't run without the .NET runtime. To my understanding, this is quite similar (or the same thing) as other "interpreted" languages. -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110920/49d3bd28/attachment.html> From ramit.prasad at jpmorgan.com Tue Sep 20 23:27:15 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 20 Sep 2011 17:27:15 -0400 Subject: [Tutor] OptionParser In-Reply-To: <4E778866.9040905@triumf.ca> References: <4E778866.9040905@triumf.ca> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16F338A3@EMARC112VS01.exchad.jpmchase.net> > from optparse import OptionParser I am not sure what version of Python you are using but from 2.7+ optparse is deprercated. You may want to use that if you can. > I don't really understand what dest and action in the arguments to parser.add_option mean. Here is your usage: >>> parser = OptionParser(usage="blahblahblah") >>> parser.add_option("-f", "--file", dest="filename") <Option at 0x8332eb8: -f/--file> >>> (options, args) = parser.parse_args(['-f filename.csv']) # test in interpreter >>> options.filename ' filename.csv' # Note the space before filename >>> print options.filename filename.csv See the documentation: http://docs.python.org/library/optparse.html Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From nozarm at triumf.ca Tue Sep 20 23:33:38 2011 From: nozarm at triumf.ca (Mina Nozar) Date: Tue, 20 Sep 2011 14:33:38 -0700 Subject: [Tutor] OptionParser In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16F338A3@EMARC112VS01.exchad.jpmchase.net> References: <4E778866.9040905@triumf.ca> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16F338A3@EMARC112VS01.exchad.jpmchase.net> Message-ID: <4E7906B2.7090905@triumf.ca> Thank you Parsad. I am using Python 2.7.1+ You are right, looks like optparse is replaced by argparse. My problem was that I was checking output and not options.output. cheers, Mina On 11-09-20 02:27 PM, Prasad, Ramit wrote: >> from optparse import OptionParser > I am not sure what version of Python you are using but from 2.7+ optparse is deprercated. You may want to use that if you can. > >> I don't really understand what dest and action in the arguments to parser.add_option mean. > Here is your usage: >>>> parser = OptionParser(usage="blahblahblah") >>>> parser.add_option("-f", "--file", dest="filename") > <Option at 0x8332eb8: -f/--file> >>>> (options, args) = parser.parse_args(['-f filename.csv']) # test in interpreter >>>> options.filename > ' filename.csv' # Note the space before filename >>>> print options.filename > filename.csv > > See the documentation: http://docs.python.org/library/optparse.html > > Ramit > > > Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology > 712 Main Street | Houston, TX 77002 > work phone: 713 - 216 - 5423 > > > This email is confidential and subject to important disclaimers and > conditions including on offers for the purchase or sale of > securities, accuracy and completeness of information, viruses, > confidentiality, legal privilege, and legal entity disclaimers, > available at http://www.jpmorgan.com/pages/disclosures/email. > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110920/46fba7df/attachment.html> From ramit.prasad at jpmorgan.com Tue Sep 20 23:36:43 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 20 Sep 2011 17:36:43 -0400 Subject: [Tutor] OptionParser In-Reply-To: <4E7906B2.7090905@triumf.ca> References: <4E778866.9040905@triumf.ca> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16F338A3@EMARC112VS01.exchad.jpmchase.net> <4E7906B2.7090905@triumf.ca> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16F338D0@EMARC112VS01.exchad.jpmchase.net> We are glad to help! If you do have future problems feel free to post again, but would you mind posting in plain text (or at least without a background)? Thanks. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From bayespokerguy at gmail.com Wed Sep 21 05:28:43 2011 From: bayespokerguy at gmail.com (Fred G) Date: Tue, 20 Sep 2011 23:28:43 -0400 Subject: [Tutor] quick data structures question Message-ID: <CAMg+7ma2evNVGSsHu8NOODY9v1w6m=Go6tOhhqCW4v_FR=E9Vw@mail.gmail.com> Hey guys, I want to write a short script that takes from an input excel file w/ a bunch of rows and columns. The two columns I'm interested in are "high gains" and "genes." I want the user to write: >>>Which genes are associated with gains over 20%? and then I want the script to search through the excel file, find in the "high gains" column when the number is greater than 20%, and then store the corresponding genes in that row (but in the "genes" column). I know this should be super simple, but I'm having trouble breaking the problem into smaller, manageable pieces. For instance, the "high gains" column does not have just integers, it is in the format YYYY%. Also, I'd like for the final script to be usable in R if possible, too. pseudocode is something like this: for line in lines: if item in "high gains" > 20 create new dictionary store genes from "genes" into new dictionary Much thanks in advance! -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110920/c8de2c19/attachment-0001.html> From delegbede at dudupay.com Wed Sep 21 08:31:26 2011 From: delegbede at dudupay.com (delegbede at dudupay.com) Date: Wed, 21 Sep 2011 06:31:26 +0000 Subject: [Tutor] quick data structures question In-Reply-To: <CAMg+7ma2evNVGSsHu8NOODY9v1w6m=Go6tOhhqCW4v_FR=E9Vw@mail.gmail.com> References: <CAMg+7ma2evNVGSsHu8NOODY9v1w6m=Go6tOhhqCW4v_FR=E9Vw@mail.gmail.com> Message-ID: <666962387-1316586687-cardhu_decombobulator_blackberry.rim.net-2147346729-@b5.c12.bise7.blackberry> Hi Fred, Here is my attempt to solve your task. import xlrd def extract(file_name): choice_file = xlrd.open_workbook(file_name) choice_sheet = choice_file.sheet_by_index(0) gene_dict = {} for row_num in range(1,choice_sheet.nrows): row_vals = choice_sheet.row_values(row_num) if int(row_vals[0] * 100) > 20: gene_dict[row_vals[1]] = row_vals[0] * 100 return gene_dict Here are few assumptions I made. 1. The your excel file has just two column with headers. Column 1 is High gain written in YYYY% format and column 2 is the gene. 2. that excel returns YYYY% format as decimals which is float in python; hence my conversion to int. Try this out and let me know how it goes. Watch the indents carefully. I typed from my blackberry. HTH. Sent from my BlackBerry wireless device from MTN -----Original Message----- From: Fred G <bayespokerguy at gmail.com> Sender: tutor-bounces+delegbede=dudupay.com at python.org Date: Tue, 20 Sep 2011 23:28:43 To: <tutor at python.org> Subject: [Tutor] quick data structures question _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From delegbede at dudupay.com Wed Sep 21 08:41:51 2011 From: delegbede at dudupay.com (delegbede at dudupay.com) Date: Wed, 21 Sep 2011 06:41:51 +0000 Subject: [Tutor] quick data structures question In-Reply-To: <CAMg+7ma2evNVGSsHu8NOODY9v1w6m=Go6tOhhqCW4v_FR=E9Vw@mail.gmail.com> References: <CAMg+7ma2evNVGSsHu8NOODY9v1w6m=Go6tOhhqCW4v_FR=E9Vw@mail.gmail.com> Message-ID: <7874331-1316587315-cardhu_decombobulator_blackberry.rim.net-512015402-@b5.c12.bise7.blackberry> As a follow up Fred, you have to install the xlrd package to use it. It helps you interact with an excel file even if you don't have excel installed on your pc. Sent from my BlackBerry wireless device from MTN -----Original Message----- From: Fred G <bayespokerguy at gmail.com> Sender: tutor-bounces+delegbede=dudupay.com at python.org Date: Tue, 20 Sep 2011 23:28:43 To: <tutor at python.org> Subject: [Tutor] quick data structures question _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From robert.layne at rockets.utoledo.edu Wed Sep 21 23:23:54 2011 From: robert.layne at rockets.utoledo.edu (Robert Layne) Date: Wed, 21 Sep 2011 21:23:54 +0000 (UTC) Subject: [Tutor] Running .py files in shell References: <4C4F2D49.2030201@digikev.co.uk> Message-ID: <loom.20110921T232009-859@post.gmane.org> Well everybody, sorry for the incomplete sentences and overall poor English but I wanted to make this simple to read and understand for someone who is completely inexperienced in any sort of programming, as I am (very first day messing with this stuff, e.g., terminal). This is the result of hours of Googling that was all done in one day. Perhaps someone who is familiar with the commands below (in bold) wouldn?t mind explaining what exactly is taking place. Additionally, this was all done in terminal on a MacBook Pro running Mac OS Lion. 1. Install macport binary (comes with installer; easy) 2. sudo port install py-game a. not sure if this is necessary, as it doesn?t appear to cause pygame to be functional for python version 2.7.1 (stock python on lion) 3. sudo port select --set python python 2.7 a. I believe this set the default python version to 2.7.2 which I also believe was downloaded during step 2 (therefore why I think this ends up being a necessary step) 4. Download setuptools-0.6c11-py2.7.tar 5. In folder gasp-0.3.4, which appears after clicking on the .tar, place setup.py in the gasp folder 6. sudo python gasp/setup.py install a. make sure your directory is the folder gasp-0.3.4 7. sudo port ?v install py27-gtk a. takes about an hour for this step to complete 8. sudo port uninstall py-game a. this step is not necessary for gasp to work; I simply didn?t want any unnecessary stuff on my computer that was downloaded during the second step; however, this step put python 2.7.2 on my computer; could install 2.7.2 separately I guess but this way worked for me; a lot of other unnecessary stuff is installed during this step too but I think it?ll remain even after this command, oh well From mukundc at hotmail.com Wed Sep 21 23:57:06 2011 From: mukundc at hotmail.com (Mukund Chavan) Date: Wed, 21 Sep 2011 21:57:06 +0000 Subject: [Tutor] List of Classes with a dictionary within the Class. Message-ID: <COL124-W4742A3641F0FFC837E9032A00D0@phx.gbl> Hi, I was trying to get a list of Class Objects. The Class itself has string fields and a dictionary that is initialized as a part of the "__init__" However the fields of the dictionary for each object in the list of class objects seems to be the same. I took an example from the following site: "http://www.daniweb.com/software-development/python/code/216631" and modified it. The code is cut/pasted below with the result of the run immediately following. I expected the 4th and 5th column in the output to be unique, but they seem to get the value of the last item in the iter range. I am running "Python 2.6.5" on Ubuntu 10.04 TLS-64bit. Thanks in advance. - Mukund Code: ----<snip>---- #!/usr/bin/python #a list of class objects to mimic a C type array of structures # tested with Python24 vegaseat 30sep2005 class Person(object): """__init__() functions as the class constructor""" personAttrs={"'num1":"","num1":""} def __init__(self, name=None, job=None, quote=None, num1=None, num2=None): self.name = name self.job = job self.quote = quote self.personAttrs["num1"]=num1 self.personAttrs["num2"]=num2 print # make a list of class Person(s) personList = [] for i in range(4): personList.append(Person("M",i,"XYZ",-i,i)) print "Show one particular item:" print personList[0].name print print "... then show all quotes and who said so:" for person in personList: print "\"%s\" %s (%s) %s %s" % (person.quote, person.name, person.job,str(person.personAttrs['num1']),str(person.personAttrs['num2'])) print print "What the heck did the person named Sanosi say?" look = "Sanosi" for person in personList: if look in person.name: print "%s: \"%s\"" % (person.name, person.quote) ----<snip>---- Output: ----<snip>---- Show one particular item: M ... then show all quotes and who said so: "XYZ" M (0) -3 3 "XYZ" M (1) -3 3 "XYZ" M (2) -3 3 "XYZ" M (3) -3 3 What the heck did the person named Sanosi say? ----<snip>---- -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110921/2226435e/attachment.html> From steve at pearwood.info Thu Sep 22 02:49:47 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 22 Sep 2011 10:49:47 +1000 Subject: [Tutor] quick data structures question In-Reply-To: <CAMg+7ma2evNVGSsHu8NOODY9v1w6m=Go6tOhhqCW4v_FR=E9Vw@mail.gmail.com> References: <CAMg+7ma2evNVGSsHu8NOODY9v1w6m=Go6tOhhqCW4v_FR=E9Vw@mail.gmail.com> Message-ID: <4E7A862B.1090405@pearwood.info> Fred G wrote: > Hey guys, > > I want to write a short script that takes from an input excel file w/ a > bunch of rows and columns. The two columns I'm interested in are "high > gains" and "genes." I want the user to write: > >>>> Which genes are associated with gains over 20%? Depending on your requirements, the simplest data structure would be just a sorted list of (high gain, genes): data = [ (1, "GAT"), (3, "CCT"), ... (99, "TTG")] Then you can answer questions like: "Which genes are associated with gains between 17% and 48%?" with a simple helper function: # untested def extract_genes(data, low=0, high=100): """Get the genes between low% and high% high gain.""" for gain, genes in data: if gain < low: continue if gain > high: break yield genes genes = list(extract_genes(data, 17, 48) > and then I want the script to search through the excel file, find in the > "high gains" column when the number is greater than 20%, and then store the > corresponding genes in that row (but in the "genes" column). Unless you have hundreds of megabytes of data, you certainly don't want to be reading from the Excel file every single time you do a query. That will be very slow. Does it have to be an .xls file? If so, you will need to install and use a third-part package to read data from the file. Google on "python excel" for more: https://duckduckgo.com/html/?q=python+excel Otherwise, a simple CSV file is 100% Excel compatible: use Excel to do a Save As and choose Comma Separated Values. You can use the csv module to read the data into a list, and then do all your processing in memory instead of on disk, which is like a thousand times faster. To get the data out of the CSV file into a list, something like this (again, untested) will work: import csv f = open("my data file.csv", "r") reader = csv.reader(f) # Skip the first line, if it is a header. header = next(reader) # or f.next() if using Python 2.5 data = [] for row in reader: # I don't know the format of your data file, so I'll make it up. # Ignore everything except high_gain and genes. colour, truth, beauty, strangeness, low_gain, high_gain, genes = row pair = convert(high_gain), genes data.append(pair) f.close() data.sort() You have to write your own "convert" function to turn the gains into numbers. Something like this might do it: def convert(s): """Convert strings like '0.42' or '42%' to floats.""" if s.endswith("%"): num = float(s[:-1]) return num/100 return float(s) -- Steven From steve at pearwood.info Thu Sep 22 02:58:09 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 22 Sep 2011 10:58:09 +1000 Subject: [Tutor] List of Classes with a dictionary within the Class. In-Reply-To: <COL124-W4742A3641F0FFC837E9032A00D0@phx.gbl> References: <COL124-W4742A3641F0FFC837E9032A00D0@phx.gbl> Message-ID: <4E7A8821.8060606@pearwood.info> Mukund Chavan wrote: > Hi, > > I was trying to get a list of Class Objects. > The Class itself has string fields and a dictionary that is initialized as a part of the "__init__" No it doesn't. It has a dictionary that is initialised *once*, when the class is defined. From that point on, every instance just modifies the same shared dictionary: > class Person(object): > """__init__() functions as the class constructor""" > personAttrs={"'num1":"","num1":""} This is a "class attribute", stored in the class itself, and shared between all instances. > def __init__(self, name=None, job=None, quote=None, num1=None, num2=None): > self.name = name > self.job = job > self.quote = quote > self.personAttrs["num1"]=num1 > self.personAttrs["num2"]=num2 This merely modifies the existing class attribute. You want something like this instead: class Person(object): def __init__(self, name=None, job=None, quote=None, num1=None, num2=None ): self.name = name self.job = job self.quote = quote self.personAttrs = {'num1': num1, 'num2': num2} This creates a new dictionary for each Person instance. But why are you doing it that way? Each Person instance *already* has its own instance dictionary for storing attributes. You don't need to manage it yourself -- just use ordinary attributes, exactly as you do for name, job, and quote. class Person(object): def __init__(self, name=None, job=None, quote=None, num1=None, num2=None ): self.name = name self.job = job self.quote = quote self.num1 = num1 self.num2 = num2 -- Steven From mukundc at hotmail.com Thu Sep 22 07:11:25 2011 From: mukundc at hotmail.com (Mukund Chavan) Date: Thu, 22 Sep 2011 05:11:25 +0000 Subject: [Tutor] List of Classes with a dictionary within the Class. In-Reply-To: <4E7A8821.8060606@pearwood.info> References: <COL124-W4742A3641F0FFC837E9032A00D0@phx.gbl>, <4E7A8821.8060606@pearwood.info> Message-ID: <COL124-W778F51C5775E57A268B97A00C0@phx.gbl> That worked. Thank you for the explanation. I was trying to take a list of these objects and insert it as a part of a mongo document using the pymongo package. But based on what your input and little more reading up, I can use the "__dict__" method to accomplish the same. Thanks again. - Mukund > Date: Thu, 22 Sep 2011 10:58:09 +1000 > From: steve at pearwood.info > To: tutor at python.org > Subject: Re: [Tutor] List of Classes with a dictionary within the Class. > > Mukund Chavan wrote: > > Hi, > > > > I was trying to get a list of Class Objects. > > The Class itself has string fields and a dictionary that is initialized as a part of the "__init__" > > No it doesn't. It has a dictionary that is initialised *once*, when the > class is defined. From that point on, every instance just modifies the > same shared dictionary: > > > class Person(object): > > """__init__() functions as the class constructor""" > > personAttrs={"'num1":"","num1":""} > > This is a "class attribute", stored in the class itself, and shared > between all instances. > > > > def __init__(self, name=None, job=None, quote=None, num1=None, num2=None): > > self.name = name > > self.job = job > > self.quote = quote > > self.personAttrs["num1"]=num1 > > self.personAttrs["num2"]=num2 > > This merely modifies the existing class attribute. You want something > like this instead: > > class Person(object): > def __init__(self, name=None, job=None, quote=None, > num1=None, num2=None > ): > self.name = name > self.job = job > self.quote = quote > self.personAttrs = {'num1': num1, 'num2': num2} > > This creates a new dictionary for each Person instance. > > But why are you doing it that way? Each Person instance *already* has > its own instance dictionary for storing attributes. You don't need to > manage it yourself -- just use ordinary attributes, exactly as you do > for name, job, and quote. > > class Person(object): > def __init__(self, name=None, job=None, quote=None, > num1=None, num2=None > ): > self.name = name > self.job = job > self.quote = quote > self.num1 = num1 > self.num2 = num2 > > > > -- > 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: <http://mail.python.org/pipermail/tutor/attachments/20110922/61506b5d/attachment-0001.html> From steve at pearwood.info Thu Sep 22 15:22:39 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 22 Sep 2011 23:22:39 +1000 Subject: [Tutor] Running .py files in shell In-Reply-To: <loom.20110921T232009-859@post.gmane.org> References: <4C4F2D49.2030201@digikev.co.uk> <loom.20110921T232009-859@post.gmane.org> Message-ID: <4E7B369F.4060609@pearwood.info> Robert Layne wrote: > Well everybody, sorry for the incomplete sentences > and overall poor English but I wanted to make this > simple to read and understand for someone who > is completely inexperienced in any sort of programming, Generally speaking, incomplete sentences and overall poor English make things HARDER to read and understand rather than easier. Or to put it another way: Generally speaking, incomplete overall poor make things HARDER read understand than easier. <wink> > as I am (very first day messing with this stuff, e.g., > terminal). This is the result of hours of Googling that > was all done in one day. Perhaps someone who is > familiar with the commands below (in bold) wouldn?t Many of your readers -- including me -- prefer plain text email rather than HTML (what Outlook wrongly calls "rich text"), for various reasons including security. So you should not assume that colours and bold text will be coloured or bold. If you want to emphasis text, writing it like *this* is a good way. This *especially* holds true for programmers, who tend to be very suspicious of fancy colourful fonts and dancing paperclips and prefer good old plain text that you could read over telnet using a 28K modem to a computer in Siberia over a flaky link at 3 in the morning. > mind explaining what exactly is taking place. Additionally, > this was all done in terminal on a MacBook Pro > running Mac OS Lion. Unfortunately, I haven't used a Mac since about 1999 or thereabouts, so I can't answer any Mac specific questions. However, I will say one thing: you seem to have made a really complicated job out of something as simple as "be able to run Python programs from the shell". For starters, I'm pretty sure Mac OS X comes with Python automatically. Perhaps not the most recent version, but I'm sure it will be there. Just try running "python" from the shell, and it should Just Work. If you want to install the most recent version, you shouldn't need to install pygame, then uninstall pygame. It shouldn't take eight steps to install the latest version of Python! (Even installing from source code under Linux, it only takes five: download, extract, configure, make, install.) My suggestion is you try something like the Mac installer for ActivePython: http://www.activestate.com/activepython/downloads The instructions here are pretty old, but they should give you some hints: http://diveintopython.org/installing_python/macosx.html Or just use the Mac installer from here: http://www.python.org/download/ -- Steven From steve at pearwood.info Thu Sep 22 15:41:40 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 22 Sep 2011 23:41:40 +1000 Subject: [Tutor] How it is better than java In-Reply-To: <20110920102106.5c34d212@jabbar> References: <CAC88qxfnUOCorLUOpYZXZXycT2OZXBPUztx9iJoO7rLuC1Yjuw@mail.gmail.com> <4E77DDE0.2020906@pearwood.info> <20110920102106.5c34d212@jabbar> Message-ID: <4E7B3B14.5080009@pearwood.info> Mac Ryan wrote: > On Tue, 20 Sep 2011 10:27:12 +1000 > Steven D'Aprano <steve at pearwood.info> wrote: > > >> There are three misunderstandings with that statement. >> [snip] >> There's also JPype, which claims to give full access to Java >> libraries in Python. > > Now: this was one of the best write-ups on the subject I read. Concise, > clear, documented. Nice way to start the day! :o I'm glad it was helpful and interesting. Thank you to everyone for the kind words. -- Steven From mindarson at live.com Thu Sep 22 16:27:59 2011 From: mindarson at live.com (Joel Knoll) Date: Thu, 22 Sep 2011 10:27:59 -0400 Subject: [Tutor] range question Message-ID: <COL104-W6219F99AF51AEB0D8C136CCC0C0@phx.gbl> Given a range of integers (1,n), how might I go about printing them in the following patterns: 1 2 3 4 ... n2 3 4 5 ... n 13 4 5 6 ... n 1 2 etc., e.g. for a "magic square". So that for the range (1,5) for example I would get 1 2 3 42 3 4 13 4 1 24 1 2 3 I just cannot figure out how to make the sequence "start over" within a row, i.e. to go from 4 down to 1 in this example. I have been grappling with this problem for 2.5 days and have gotten nowhere! -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110922/0def7bb9/attachment.html> From eire1130 at gmail.com Thu Sep 22 16:37:47 2011 From: eire1130 at gmail.com (James Reynolds) Date: Thu, 22 Sep 2011 10:37:47 -0400 Subject: [Tutor] range question In-Reply-To: <COL104-W6219F99AF51AEB0D8C136CCC0C0@phx.gbl> References: <COL104-W6219F99AF51AEB0D8C136CCC0C0@phx.gbl> Message-ID: <CAE0jAboSOSEfcSp_OQ7wKanUMKoRobQeP4JX29QJxv5GAzEzUw@mail.gmail.com> On Thu, Sep 22, 2011 at 10:27 AM, Joel Knoll <mindarson at live.com> wrote: > Given a range of integers (1,n), how might I go about printing them in the > following patterns: > > 1 2 3 4 ... n > 2 3 4 5 ... n 1 > 3 4 5 6 ... n 1 2 > > etc., e.g. for a "magic square". So that for the range (1,5) for example I > would get > > 1 2 3 4 > 2 3 4 1 > 3 4 1 2 > 4 1 2 3 > > I just cannot figure out how to make the sequence "start over" within a > row, i.e. to go from 4 down to 1 in this example. > > I have been grappling with this problem for 2.5 days and have gotten > nowhere! > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > I would probably do something like this: a = [1,2,3,4] > print a > b = a.pop(0) > a.append(b) > print a Probably an easier way of doing it though. If you wanted to do that four times: for item in a: > print a > b = a.pop(0) > a.append(b) You just need to think of it as a register and shifting bits left or right -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110922/e52bc297/attachment.html> From d at davea.name Thu Sep 22 16:37:27 2011 From: d at davea.name (Dave Angel) Date: Thu, 22 Sep 2011 10:37:27 -0400 Subject: [Tutor] range question In-Reply-To: <COL104-W6219F99AF51AEB0D8C136CCC0C0@phx.gbl> References: <COL104-W6219F99AF51AEB0D8C136CCC0C0@phx.gbl> Message-ID: <4E7B4827.2080904@davea.name> On 09/22/2011 10:27 AM, Joel Knoll wrote: > Given a range of integers (1,n), how might I go about printing them in the following patterns: > 1 2 3 4 ... n2 3 4 5 ... n 13 4 5 6 ... n 1 2 > etc., e.g. for a "magic square". So that for the range (1,5) for example I would get > 1 2 3 42 3 4 13 4 1 24 1 2 3 > I just cannot figure out how to make the sequence "start over" within a row, i.e. to go from 4 down to 1 in this example. > I have been grappling with this problem for 2.5 days and have gotten nowhere! > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Seems like the easiest way would be to duplicate the range once (so you have a list twice as long), and then use various slices of it. x = list(range(1, 5)) #could omit the list() function in python 2.x x2 = x+x for the nth row, use row = x2[n:n+n] -- DaveA -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110922/e27bf138/attachment.html> From hugo.yoshi at gmail.com Thu Sep 22 16:43:40 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Thu, 22 Sep 2011 16:43:40 +0200 Subject: [Tutor] range question In-Reply-To: <CAJmBOfmo9sRaYSeF+YHKewnG2D3oJJZHZV_ZPMMgprL+=bB7ag@mail.gmail.com> References: <COL104-W6219F99AF51AEB0D8C136CCC0C0@phx.gbl> <4E7B4827.2080904@davea.name> <CAJmBOfmo9sRaYSeF+YHKewnG2D3oJJZHZV_ZPMMgprL+=bB7ag@mail.gmail.com> Message-ID: <CAJmBOfnL3hMiVd2SkB5fVW_a-YFxoofDbuLFKK9EvmbRzewyXw@mail.gmail.com> forgot to forward to list: From: Hugo Arts <hugo.yoshi at gmail.com> Date: Thu, Sep 22, 2011 at 4:42 PM Subject: Re: [Tutor] range question To: d at davea.name On Thu, Sep 22, 2011 at 4:37 PM, Dave Angel <d at davea.name> wrote: > On 09/22/2011 10:27 AM, Joel Knoll wrote: > > Given a range of integers (1,n), how might I go about printing them in the > following patterns: > 1 2 3 4 ... n2 3 4 5 ... n 13 4 5 6 ... n 1 2 > etc., e.g. for a "magic square". So that for the range (1,5) for example I > would get > 1 2 3 42 3 4 13 4 1 24 1 2 3 > I just cannot figure out how to make the sequence "start over" within a row, > i.e. to go from 4 down to 1 in this example. > I have been grappling with this problem for 2.5 days and have gotten > nowhere! > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > Seems like the easiest way would be to duplicate the range once (so you have > a list twice as long), and then use various slices of it. > > x = list(range(1, 5))?? #could omit the list() function in python 2.x > x2 = x+x > > for the nth row, use > ?? row = x2[n:n+n] > Surely you meant to type: x = list(range(1, 6)) x2 = x + x row ?= x[n:n+len(x)] From joel.goldstick at gmail.com Thu Sep 22 16:56:05 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 22 Sep 2011 10:56:05 -0400 Subject: [Tutor] range question In-Reply-To: <4E7B4827.2080904@davea.name> References: <COL104-W6219F99AF51AEB0D8C136CCC0C0@phx.gbl> <4E7B4827.2080904@davea.name> Message-ID: <CAPM-O+xjKsSK0BY48-S7XQtuq=Lh9DaqwBXzhHuO36q9QC_a7g@mail.gmail.com> On Thu, Sep 22, 2011 at 10:37 AM, Dave Angel <d at davea.name> wrote: > ** > On 09/22/2011 10:27 AM, Joel Knoll wrote: > > Given a range of integers (1,n), how might I go about printing them in the following patterns: > 1 2 3 4 ... n2 3 4 5 ... n 13 4 5 6 ... n 1 2 > etc., e.g. for a "magic square". So that for the range (1,5) for example I would get > 1 2 3 42 3 4 13 4 1 24 1 2 3 > I just cannot figure out how to make the sequence "start over" within a row, i.e. to go from 4 down to 1 in this example. > I have been grappling with this problem for 2.5 days and have gotten nowhere! > > > _______________________________________________ > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options:http://mail.python.org/mailman/listinfo/tutor > > Seems like the easiest way would be to duplicate the range once (so you > have a list twice as long), and then use various slices of it. > > x = list(range(1, 5)) #could omit the list() function in python 2.x > x2 = x+x > > for the nth row, use > row = x2[n:n+n] > > > > -- > > DaveA > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > I did it like this: The trick when cycling through numbers is to use the modulo operator (%) which gives the integer remainder after division #!/usr/bin/env python """ Print magic square give range n like so: If n is 5 1234 2341 3412 4123 """ n = 5 for row in range(n): for col in range(n): print (row + col) % n + 1, print -- 1 2 3 4 5 2 3 4 5 1 3 4 5 1 2 4 5 1 2 3 5 1 2 3 4 Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110922/94a5aeb6/attachment.html> From d at davea.name Thu Sep 22 16:56:57 2011 From: d at davea.name (Dave Angel) Date: Thu, 22 Sep 2011 10:56:57 -0400 Subject: [Tutor] range question In-Reply-To: <CAJmBOfnL3hMiVd2SkB5fVW_a-YFxoofDbuLFKK9EvmbRzewyXw@mail.gmail.com> References: <COL104-W6219F99AF51AEB0D8C136CCC0C0@phx.gbl> <4E7B4827.2080904@davea.name> <CAJmBOfmo9sRaYSeF+YHKewnG2D3oJJZHZV_ZPMMgprL+=bB7ag@mail.gmail.com> <CAJmBOfnL3hMiVd2SkB5fVW_a-YFxoofDbuLFKK9EvmbRzewyXw@mail.gmail.com> Message-ID: <4E7B4CB9.6070008@davea.name> On 09/22/2011 10:43 AM, Hugo Arts wrote: > forgot to forward to list: > > From: Hugo Arts<hugo.yoshi at gmail.com> > Date: Thu, Sep 22, 2011 at 4:42 PM > Subject: Re: [Tutor] range question > To: d at davea.name > > > On Thu, Sep 22, 2011 at 4:37 PM, Dave Angel<d at davea.name> wrote: >> On 09/22/2011 10:27 AM, Joel Knoll wrote: >> >> Given a range of integers (1,n), how might I go about printing them in the >> following patterns: >> 1 2 3 4 ... n2 3 4 5 ... n 13 4 5 6 ... n 1 2 >> etc., e.g. for a "magic square". So that for the range (1,5) for example I >> would get >> 1 2 3 42 3 4 13 4 1 24 1 2 3 >> I just cannot figure out how to make the sequence "start over" within a row, >> i.e. to go from 4 down to 1 in this example. >> I have been grappling with this problem for 2.5 days and have gotten >> nowhere! >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> Seems like the easiest way would be to duplicate the range once (so you have >> a list twice as long), and then use various slices of it. >> >> x = list(range(1, 5)) #could omit the list() function in python 2.x >> x2 = x+x >> >> for the nth row, use >> row = x2[n:n+n] >> > Surely you meant to type: > > x = list(range(1, 6)) > x2 = x + x > row = x[n:n+len(x)] > The second correction is important, the first one wrong. The OP's example was looking for the numbers 1 through 4, so range(1,5) was correct. -- DaveA From hugo.yoshi at gmail.com Thu Sep 22 17:08:00 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Thu, 22 Sep 2011 17:08:00 +0200 Subject: [Tutor] range question In-Reply-To: <4E7B4CB9.6070008@davea.name> References: <COL104-W6219F99AF51AEB0D8C136CCC0C0@phx.gbl> <4E7B4827.2080904@davea.name> <CAJmBOfmo9sRaYSeF+YHKewnG2D3oJJZHZV_ZPMMgprL+=bB7ag@mail.gmail.com> <CAJmBOfnL3hMiVd2SkB5fVW_a-YFxoofDbuLFKK9EvmbRzewyXw@mail.gmail.com> <4E7B4CB9.6070008@davea.name> Message-ID: <CAJmBOfmt6p7p+fHH+QeHA44pHQDdoGWu+hKEBJAVXWW_eixStw@mail.gmail.com> On Thu, Sep 22, 2011 at 4:56 PM, Dave Angel <d at davea.name> wrote: > > The second correction is important, the first one wrong. ?The OP's example > was looking for the numbers 1 through 4, so range(1,5) was correct. > -- > > DaveA > > Ah, apologies. I misread the OP From steve at pearwood.info Thu Sep 22 17:08:27 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 23 Sep 2011 01:08:27 +1000 Subject: [Tutor] range question In-Reply-To: <COL104-W6219F99AF51AEB0D8C136CCC0C0@phx.gbl> References: <COL104-W6219F99AF51AEB0D8C136CCC0C0@phx.gbl> Message-ID: <4E7B4F6B.1010604@pearwood.info> Joel Knoll wrote: > Given a range of integers (1,n), how might I go about printing them in the following patterns: > 1 2 3 4 ... n2 3 4 5 ... n 13 4 5 6 ... n 1 2 > etc., e.g. for a "magic square". So that for the range (1,5) for example I would get > 1 2 3 42 3 4 13 4 1 24 1 2 3 I'm not sure what you want, because the formatting is all broken in Thunderbird. Your "magic square" looks more like a straight line. I'm going to take a wild stab in the dark and *guess* that you want something like this: 1 2 3 4 2 3 4 1 3 4 1 2 4 1 2 3 Look at the pattern: each row is the same as the previous row, except the first item is moved to the end. You can move an item from the front to the end with pop() to delete it, and append() to re-add it. There are the same number of rows as columns. Putting this together: n = 4 # number of columns row = range(1, n+1) for row_number in range(n): # print the row without commas and [] for item in row: print item, # note the comma at the end print # start a new line # Pop the first item from the list, then add it to the end. x = row.pop(0) row.append(x) -- Steven From eire1130 at gmail.com Thu Sep 22 17:20:41 2011 From: eire1130 at gmail.com (James Reynolds) Date: Thu, 22 Sep 2011 11:20:41 -0400 Subject: [Tutor] range question In-Reply-To: <4E7B4F6B.1010604@pearwood.info> References: <COL104-W6219F99AF51AEB0D8C136CCC0C0@phx.gbl> <4E7B4F6B.1010604@pearwood.info> Message-ID: <CAE0jAbr3cDyGHPyWpV7qPu8w6kXGWHbY6hAAXt4Zc0h6-1wzfQ@mail.gmail.com> On Thu, Sep 22, 2011 at 11:08 AM, Steven D'Aprano <steve at pearwood.info>wrote: > Joel Knoll wrote: > >> Given a range of integers (1,n), how might I go about printing them in the >> following patterns: >> 1 2 3 4 ... n2 3 4 5 ... n 13 4 5 6 ... n 1 2 etc., e.g. for a "magic >> square". So that for the range (1,5) for example I would get >> >> 1 2 3 42 3 4 13 4 1 24 1 2 3 >> > > > I'm not sure what you want, because the formatting is all broken in > Thunderbird. Your "magic square" looks more like a straight line. > > I'm going to take a wild stab in the dark and *guess* that you want > something like this: > > > 1 2 3 4 > 2 3 4 1 > 3 4 1 2 > 4 1 2 3 > > Look at the pattern: each row is the same as the previous row, except the > first item is moved to the end. You can move an item from the front to the > end with pop() to delete it, and append() to re-add it. > > There are the same number of rows as columns. Putting this together: > > > n = 4 # number of columns > row = range(1, n+1) > for row_number in range(n): > # print the row without commas and [] > for item in row: > print item, # note the comma at the end > print # start a new line > # Pop the first item from the list, then add it to the end. > x = row.pop(0) > row.append(x) > > > > -- > Steven > > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor> > An easier way to print without the comma, assuming 2.6 or 2.7 is to add this: from __future__ import print_function and then print like this: print(*a) or if you are already using python 3.0+ you just print like that without the import. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110922/f0900a8b/attachment-0001.html> From joeyshakespeare at gmail.com Thu Sep 22 19:04:58 2011 From: joeyshakespeare at gmail.com (Joseph Shakespeare) Date: Thu, 22 Sep 2011 12:04:58 -0500 Subject: [Tutor] Help! In-Reply-To: <CAB=+OuQ87oJVD-x526Up-VhJvgzRj5+sNJ6JVF1+t5eCKzOUvg@mail.gmail.com> References: <CAB=+OuQ87oJVD-x526Up-VhJvgzRj5+sNJ6JVF1+t5eCKzOUvg@mail.gmail.com> Message-ID: <CAB=+OuRApEEGLsNLtfqfRQ0KTA-6qNfxSCxuiRnsVWXQ73Znvw@mail.gmail.com> Hello, I am new Python (about 2 weeks) and need some help. I am making a rock paper scissors game that a user can play with the computer by using a while loop and if elif else statements. It needs to keep score of the amount of losses and wins, and give the user the option to play again after each round. I've tried so many different options and I don't know what else to try. My problem is making the program loop back around when the user selects y(yes) to play again and defining the variables at the beginning. Here's my program: import random print"Welcome to Rock,Paper, Scissors! This is a game of chance; the computer randomly picks one of three throws." print"" print"Rock beats Scissors, but is beaten by Paper." print"Scissors beat Paper, but are beaten by Rock." print"Paper beats Rock, but is beaten by Scissors." print"" print"r for Rock" print"s for Scissors" wins=0 loses=0 print"p for Paper" player=raw_input("Please pick your throw: (r,s,p):") computer= random.choice(['r','s','p']) print "Computer throw:", computer y="something" play=y while play==y: if player=='r': if computer== 'r': print "Tie! Throw again." elif computer=='s': print "You win! r beats s" wins=wins+1 elif computer == 'p': print "You lose! p beats r" loses=loses+1 else: pass elif player=='s': if computer== 's': print "Tie! Throw again." elif computer=='p': print "You win! s beats p" wins=wins+1 elif computer == 'r': print "You lose! r beats s" loses=loses+1 else: pass elif player=='p': if computer== 'p': print "Tie! Throw again." elif computer=='r': print "You win! p beats r" wins=wins+1 elif computer == 's': print "You lose! s beats p" loses=loses+1 else: pass else: print "Invalid entry" print"" print"Game Summary" print"Wins:", wins print"Loses:",loses play=raw_input("Play again? y (yes) or n (no):" print"Thanks for playing!" Thanks! Joey -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110922/8be64fec/attachment.html> From ramit.prasad at jpmorgan.com Thu Sep 22 21:14:41 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 22 Sep 2011 15:14:41 -0400 Subject: [Tutor] Help! In-Reply-To: <CAB=+OuRApEEGLsNLtfqfRQ0KTA-6qNfxSCxuiRnsVWXQ73Znvw@mail.gmail.com> References: <CAB=+OuQ87oJVD-x526Up-VhJvgzRj5+sNJ6JVF1+t5eCKzOUvg@mail.gmail.com> <CAB=+OuRApEEGLsNLtfqfRQ0KTA-6qNfxSCxuiRnsVWXQ73Znvw@mail.gmail.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F1707B2AD@EMARC112VS01.exchad.jpmchase.net> From: tutor-bounces+ramit.prasad=jpmorgan.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of Joseph Shakespeare Sent: Thursday, September 22, 2011 12:05 PM To: tutor at python.org Subject: [Tutor] Help! Hello, I am new Python (about?2 weeks) and need some help. I am making a rock paper scissors game that a user can play with the computer by using a while loop and if elif else statements. It needs to keep score of the amount of losses and wins, and give the user the option to play again after each round. I've tried so many different options and I don't know what else to try. My problem is making the program loop back around when the user selects y(yes) to play again and defining the variables at the beginning. Here's my program: import random print"Welcome to Rock,Paper, Scissors! This is a game of chance; the computer randomly picks one of three throws." print"" print"Rock beats Scissors, but is beaten by Paper." print"Scissors beat Paper, but are beaten by Rock." print"Paper beats Rock, but is beaten by Scissors." print"" print"r for Rock" print"s for Scissors" wins=0 loses=0 print"p for Paper" player=raw_input("Please pick your throw: (r,s,p):") computer= random.choice(['r','s','p']) print "Computer throw:", computer y="something" play=y while play==y: ? ? if player=='r': ? ? ? ? if computer== 'r': ? ? ? ? ? ? print "Tie! Throw again." ? ? ? ? elif computer=='s': ? ? ? ? ? ? print "You win! r beats s" ? ? ? ? ? ? wins=wins+1 ? ? ? ? elif computer == 'p': ? ? ? ? ? ? print "You lose! p beats r" ? ? ? ? ? ? loses=loses+1 ? ? ? ? else: ? ? ? ? ? ? pass ? ? elif player=='s': ? ? ? ? if computer== 's': ? ? ? ? ? ? print "Tie! Throw again." ? ? ? ? elif computer=='p': ? ? ? ? ? ? print "You win! s beats p" ? ? ? ? ? ? wins=wins+1 ? ? ? ? elif computer == 'r': ? ? ? ? ? ? print "You lose! r beats s" ? ? ? ? ? ? loses=loses+1 ? ? ? ? else: ? ? ? ? ? ? pass ? ? elif player=='p': ? ? ? ? ? ? if computer== 'p': ? ? ? ? ? ? ? ? print "Tie! Throw again." ? ? ? ? ? ? elif computer=='r': ? ? ? ? ? ? ? ? print "You win! p beats r" ? ? ? ? ? ? ? ? wins=wins+1 ? ? ? ? ? ? elif computer == 's': ? ? ? ? ? ? ? ? print "You lose! s beats p" ? ? ? ? ? ? ? ? loses=loses+1 ? ? ? ? ? ? else: ? ? ? ? ? ? ? ? pass ? ? else: ? ? ? ? print "Invalid entry" ? ? print"" ? ? print"Game Summary" ? ? print"Wins:", wins ? ? print"Loses:",loses ? ? play=raw_input("Play again? y (yes) or n (no):" print"Thanks for playing!" Thanks! Joey =========================================================== Change > y="something" TO : > y="y" Although, I would probably do something like y=("y","yes") play="y" while play in y: Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From thudfoo at gmail.com Thu Sep 22 22:26:39 2011 From: thudfoo at gmail.com (xDog Walker) Date: Thu, 22 Sep 2011 13:26:39 -0700 Subject: [Tutor] Help! In-Reply-To: <CAB=+OuRApEEGLsNLtfqfRQ0KTA-6qNfxSCxuiRnsVWXQ73Znvw@mail.gmail.com> References: <CAB=+OuQ87oJVD-x526Up-VhJvgzRj5+sNJ6JVF1+t5eCKzOUvg@mail.gmail.com> <CAB=+OuRApEEGLsNLtfqfRQ0KTA-6qNfxSCxuiRnsVWXQ73Znvw@mail.gmail.com> Message-ID: <201109221326.39671.thudfoo@gmail.com> Move the following two lines to immediately follow the while. player=raw_input("Please pick your throw: (r,s,p):") computer= random.choice(['r','s','p']) -- I have seen the future and I am not in it. From bgailer at gmail.com Fri Sep 23 01:35:09 2011 From: bgailer at gmail.com (bob gailer) Date: Thu, 22 Sep 2011 19:35:09 -0400 Subject: [Tutor] paper scissors In-Reply-To: <CAB=+OuRApEEGLsNLtfqfRQ0KTA-6qNfxSCxuiRnsVWXQ73Znvw@mail.gmail.com> References: <CAB=+OuQ87oJVD-x526Up-VhJvgzRj5+sNJ6JVF1+t5eCKzOUvg@mail.gmail.com> <CAB=+OuRApEEGLsNLtfqfRQ0KTA-6qNfxSCxuiRnsVWXQ73Znvw@mail.gmail.com> Message-ID: <4E7BC62D.3010607@gmail.com> On 9/22/2011 1:04 PM, Joseph Shakespeare wrote: > Hello, Hi - please use a meaningful subject line - I've changed it this time > > I am new Python (about 2 weeks) and need some help. I am making a rock > paper scissors game that a user can play with the computer by using a > while loop and if elif else statements. It needs to keep score of the > amount of losses and wins, and give the user the option to play again > after each round. I've tried so many different options and I don't > know what else to try. My problem is making the program loop back > around when the user selects y(yes) to play again and defining the > variables at the beginning. Here's my program: > I've taken the liberty to extensively edit (and simplify) your program. Cut 60 lines to 34. Study it - there are a lot of useful ideas in it. Feel free to ask questions. The following 3 llnes will NOT get you what you want. You appear to be confusing variable names with strings. > y="something" > play=y > while play==y: The while condition is not true - the program will not run. The proper initialization is: play = "y" However I've eliminated the need for even that. import random # Use a triple-quoted string rather than a bunch of print statements. print """Welcome to Rock,Paper, Scissors! This is a game of chance. The computer randomly picks one of three throws. Rock beats Scissors, but is beaten by Paper. Scissors beat Paper, but are beaten by Rock. Paper beats Rock, but is beaten by Scissors. You enter: r for Rock s for Scissors p for Paper q to Quit'""" wins = loses = 0 while True: # "endless" loop - exited by break statement player = raw_input("Please pick your throw: (r, s, p, or q ):") if player == "q": break # exits the loop elif player not in "rps": # check for valid entry print "Invalid entry" else: computer= random.choice("rsp") # no need for a list - a string is a sequence print "Computer throw:", computer if player == computer: # testing various conditiions cam be greatly simplified print "Tie! Throw again." elif player + computer in ["rs", "sp", "pr"]: print "You win! " + player + " beats " + computer wins += 1 # simpler than wins = wins + 1 else: print "You lose! " + computer + " beats " + player loses +=1 print """Game Summary Wins: %s Loses:" %s""" % (wins,loses) # using % formatting and triple quoted string print"Thanks for playing!" -- Bob Gailer 919-636-4239 Chapel Hill NC From thyecheeyung at gmail.com Fri Sep 23 07:15:10 2011 From: thyecheeyung at gmail.com (Cheeyung) Date: Fri, 23 Sep 2011 13:15:10 +0800 Subject: [Tutor] Need a bump in the right direction (network programming) Message-ID: <4E7C15DE.1050106@gmail.com> I'm creating a mobile application and I'm using python for a desktop server. However, I don't have access to a static IP on the desktop, but do have a website. Is it possible to connect from mobile -> http website -> desktop server and back? What kind of (python) libraries/functions am I looking for? As you can see, I'm completely clueless about where to begin. If someone could recommend a resource to learn network programming, that would be great too! Thanks! CY From d at davea.name Fri Sep 23 09:20:53 2011 From: d at davea.name (Dave Angel) Date: Fri, 23 Sep 2011 03:20:53 -0400 Subject: [Tutor] Need a bump in the right direction (network programming) In-Reply-To: <4E7C15DE.1050106@gmail.com> References: <4E7C15DE.1050106@gmail.com> Message-ID: <4E7C3355.8020806@davea.name> On 09/23/2011 01:15 AM, Cheeyung wrote: > I'm creating a mobile application and I'm using python for a desktop > server. However, I don't have access to a static IP on the desktop, > but do have a website. Is it possible to connect from mobile -> http > website -> desktop server and back? > > What kind of (python) libraries/functions am I looking for? > > As you can see, I'm completely clueless about where to begin. If > someone could recommend a resource to learn network programming, that > would be great too! > > Thanks! > > CY > _ Run ifconfig as an external process, and parse the output to find your IP address(es). Maybe that'll get you started. (if you're on Windows, it'll be called ipconfig instead, and is formatted somewhat differently) -- DaveA From quasipedia at gmail.com Fri Sep 23 10:43:23 2011 From: quasipedia at gmail.com (Mac Ryan) Date: Fri, 23 Sep 2011 10:43:23 +0200 Subject: [Tutor] Need a bump in the right direction (network programming) In-Reply-To: <4E7C3355.8020806@davea.name> References: <4E7C15DE.1050106@gmail.com> <4E7C3355.8020806@davea.name> Message-ID: <20110923104323.24c249b3@jabbar> On Fri, 23 Sep 2011 03:20:53 -0400 Dave Angel <d at davea.name> wrote: > On 09/23/2011 01:15 AM, Cheeyung wrote: > > I'm creating a mobile application and I'm using python for a > > desktop server. However, I don't have access to a static IP on the > > desktop, but do have a website. Is it possible to connect from > > mobile -> http website -> desktop server and back? If I got you right, I would skip the website entirely. Just connect directly to your desktop from the mobile, using a dynamic DNS service. Maybe the bump you need could be: http://dnslookup.me/dynamic-dns/ HTH, /mac From quasipedia at gmail.com Fri Sep 23 13:35:43 2011 From: quasipedia at gmail.com (Mac Ryan) Date: Fri, 23 Sep 2011 13:35:43 +0200 Subject: [Tutor] Need a bump in the right direction (network programming) In-Reply-To: <4E7C4B61.40209@gmail.com> References: <4E7C15DE.1050106@gmail.com> <4E7C3355.8020806@davea.name> <20110923104323.24c249b3@jabbar> <4E7C4B61.40209@gmail.com> Message-ID: <20110923133543.39df103f@jabbar> On Fri, 23 Sep 2011 17:03:29 +0800 Cheeyung <thyecheeyung at gmail.com> wrote: > >> On 09/23/2011 01:15 AM, Cheeyung wrote: > >>> I'm creating a mobile application and I'm using python for a > >>> desktop server. However, I don't have access to a static IP on the > >>> desktop, but do have a website. Is it possible to connect from > >>> mobile -> http website -> desktop server and back? > > If I got you right, I would skip the website entirely. Just connect > > directly to your desktop from the mobile, using a dynamic DNS > > service. Maybe the bump you need could be: > > http://dnslookup.me/dynamic-dns/ > > Hi, thanks for the reply. Dynamic DNS sounds like exactly what I > need, but just let me confirm if I understand it correctly. > > The mobile will connect to to the dynamic DNS service (ie. > example.dynamicdns.com), which will then redirect it to the desktop. > The desktop keeps the DDNS service updated using a script or > webclient etc. depending on the service. > > Did I get that right? I never used this service myself, but to the best of my knowledge yes, that's the way dynamic dns works. On another note: when replying to ML messages, remember to hit "reply all", otherwise your answer will be delivered to the author of the message only! :) /mac From bgailer at gmail.com Fri Sep 23 21:02:44 2011 From: bgailer at gmail.com (bob gailer) Date: Fri, 23 Sep 2011 15:02:44 -0400 Subject: [Tutor] paper scissors In-Reply-To: <CAB=+OuSjUCCjQ3FHN1aK2F3B-iVrPLg24xAmAPYS-0DSqjpSjA@mail.gmail.com> References: <CAB=+OuQ87oJVD-x526Up-VhJvgzRj5+sNJ6JVF1+t5eCKzOUvg@mail.gmail.com> <CAB=+OuRApEEGLsNLtfqfRQ0KTA-6qNfxSCxuiRnsVWXQ73Znvw@mail.gmail.com> <4E7BC62D.3010607@gmail.com> <CAB=+OuSjUCCjQ3FHN1aK2F3B-iVrPLg24xAmAPYS-0DSqjpSjA@mail.gmail.com> Message-ID: <4E7CD7D4.4050005@gmail.com> On 9/23/2011 2:04 PM, Joseph Shakespeare wrote: > Wow, thanks so much! This is amazing! > One question though. I understand everything in the program except > these 2 lines: > > Wins: %s > Loses:%s""" % (wins,loses) > > There are 2 things I don't understand. > 1. the %s > 2. the (wins,loses) > > Any explanation you have would be helpful. > Thanks for taking the time to help the newbie! > > Joey > > > > On Thu, Sep 22, 2011 at 6:35 PM, bob gailer <bgailer at gmail.com > <mailto:bgailer at gmail.com>> wrote: > > On 9/22/2011 1:04 PM, Joseph Shakespeare wrote: > > Hello, > > > Hi - please use a meaningful subject line - I've changed it this time > > > I am new Python (about 2 weeks) and need some help. I am > making a rock paper scissors game that a user can play with > the computer by using a while loop and if elif else > statements. It needs to keep score of the amount of losses and > wins, and give the user the option to play again after each > round. I've tried so many different options and I don't know > what else to try. My problem is making the program loop back > around when the user selects y(yes) to play again and defining > the variables at the beginning. Here's my program: > > I've taken the liberty to extensively edit (and simplify) your > program. Cut 60 lines to 34. Study it - there are a lot of useful > ideas in it. Feel free to ask questions. > > The following 3 llnes will NOT get you what you want. You appear > to be confusing variable names with strings. > > y="something" > play=y > while play==y: > > > The while condition is not true - the program will not run. > > The proper initialization is: > > play = "y" > > However I've eliminated the need for even that. > > import random > # Use a triple-quoted string rather than a bunch of print statements. > print """Welcome to Rock,Paper, Scissors! This is a game of chance. > The computer randomly picks one of three throws. > Rock beats Scissors, but is beaten by Paper. > Scissors beat Paper, but are beaten by Rock. > Paper beats Rock, but is beaten by Scissors. > You enter: > r for Rock > s for Scissors > p for Paper > q to Quit'""" > wins = loses = 0 > while True: # "endless" loop - exited by break statement > player = raw_input("Please pick your throw: (r, s, p, or q ):") > if player == "q": > break # exits the loop > elif player not in "rps": # check for valid entry > print "Invalid entry" > else: > computer= random.choice("rsp") # no need for a list - a > string is a sequence > print "Computer throw:", computer > if player == computer: # testing various conditiions cam be > greatly simplified > print "Tie! Throw again." > elif player + computer in ["rs", "sp", "pr"]: > print "You win! " + player + " beats " + computer > wins += 1 # simpler than wins = wins + 1 > else: > print "You lose! " + computer + " beats " + player > loses +=1 > print """Game Summary > Wins: %s > Loses:" %s""" % (wins,loses) # using % formatting and triple > quoted string > print"Thanks for playing!" > > > -- Bob Gailer 919-636-4239 <tel:919-636-4239> Chapel Hill NC > > -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110923/cea73a1c/attachment.html> From kellyadrian at hotmail.com Fri Sep 23 21:25:12 2011 From: kellyadrian at hotmail.com (ADRIAN KELLY) Date: Fri, 23 Sep 2011 19:25:12 +0000 Subject: [Tutor] guess-my-number programme Message-ID: <DUB103-W627F923D1E3302DF756901A90F0@phx.gbl> import random print("\tWelcome to 'Guess My Number'!") print("I'm thinking of a number between 1 and 100.") print("Try to guess it in as few attempts as possible.\n") # set the initial values the_number = random.randint(1, 100) guess = int(input("Take a guess: ")) tries = 1 # guessing loop while guess != the_number: if guess > the_number: print("Lower...") else: print("Higher...") guess = int(input("Take a guess: ")) tries = tries + 1 print("You guessed it! The number was", the_number) print("And it only took you", tries, "tries!\n") input("\n\nPress the enter key to exit.") ******************************************************************* can anyone explain the tries part of this programme to me i know its meant to count the number of guesses made by the user by adding 1 but i just cant figure out how it does this..........can someone explain?? i.e. tries = 1, tries +1 etc.... cant get my head around it... thanks all Adrian Kelly 1 Bramble Close Baylough Athlone County Westmeath 0879495663 -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110923/ab34a3e7/attachment.html> From emile at fenx.com Fri Sep 23 22:22:31 2011 From: emile at fenx.com (Emile van Sebille) Date: Fri, 23 Sep 2011 13:22:31 -0700 Subject: [Tutor] guess-my-number programme In-Reply-To: <DUB103-W627F923D1E3302DF756901A90F0@phx.gbl> References: <DUB103-W627F923D1E3302DF756901A90F0@phx.gbl> Message-ID: <j5ipmq$v13$1@dough.gmane.org> On 9/23/2011 12:25 PM ADRIAN KELLY said... <snip> > can anyone explain the *tries * part of this programme to me i know its > meant to count the number of guesses made by the user by adding 1 but i > just cant figure out how it does this..........can someone explain?? > i.e. tries = 1, tries +1 etc.... cant get my head around it... > tries = tries + 1 This simply increments tries by one each time through the loop. So the first time through it takes on the value 2, then 3, then 4, etc. Emile From waynejwerner at gmail.com Fri Sep 23 22:28:40 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Fri, 23 Sep 2011 15:28:40 -0500 Subject: [Tutor] guess-my-number programme In-Reply-To: <DUB103-W627F923D1E3302DF756901A90F0@phx.gbl> References: <DUB103-W627F923D1E3302DF756901A90F0@phx.gbl> Message-ID: <CAPM86NfC3ZVWO_cXJDUeEcveP7eCgVs_gxN795j7f6=uXkobSA@mail.gmail.com> On Fri, Sep 23, 2011 at 2:25 PM, ADRIAN KELLY <kellyadrian at hotmail.com>wrote: > <snip> > can anyone explain the *tries* part of this programme to me i know its meant > to count the number of guesses made by the user by adding 1 but i just cant > figure out how it does this..........can someone explain?? i.e. tries = 1, > tries +1 etc.... cant get my head around it... > The concept that's confusing you here is something called order of evaluation, or evaluation strategy: http://en.wikipedia.org/wiki/Evaluation_strategy The best way to understand these things is to try it out, and the interactive interpreter is extremely handy. I presume you understand the concept of assignment, correct? For example: >>> tries = 1 Now tries contains 1: >>> tries = 1 >>> tries 1 The variable 'tries' now contains the value 1 (In Python this is not technically true, but it's useful to describe it that way). >>> tries = 4 Now 'tries' contains 4. Of course, just like your standard algebra variables, you can use your variables in python: >>> tries * 4 16 >>> tries + tries 8 >>> tries / 1 4 when these expressions are /evaluated/ they produce the mathematical expression you probably expect. But you can do more than just evaluate expressions, you can store their results: >>> lots_of_tries = tries * 100 >>> lots_of_tries 400 So what about the expression that confuses you? >>> tries = tries + 1 >>> tries 5 Well, the first thing that happens when python sees the equals sign is that the right hand side of the expression is evaluated, so python takes: tries = tries + 1 and turns it into tries = 4 + 1 tries = 5 So each time your program sees 'tries = tries + 1' python evaluates the right side first, then assigns its value to the variable on the left. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110923/77ec4463/attachment-0001.html> From alan.gauld at btinternet.com Sat Sep 24 00:48:15 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 23 Sep 2011 23:48:15 +0100 Subject: [Tutor] How it is better than java In-Reply-To: <CAC88qxfnUOCorLUOpYZXZXycT2OZXBPUztx9iJoO7rLuC1Yjuw@mail.gmail.com> References: <CAC88qxfnUOCorLUOpYZXZXycT2OZXBPUztx9iJoO7rLuC1Yjuw@mail.gmail.com> Message-ID: <j5j2bf$mdo$1@dough.gmane.org> On 19/09/11 14:27, Ashish Gaonker wrote: First, to address the question in your subject line, we need to agree a definition of "better". In what respect? And by which benchmark? And who claimed that either one was "better" anyway? No serious programmer would be likely to make such a vague comparison. > My obvious thinking is : Java being compiled language , must be faster > then a interpreted language. There have been many other answers that address this. Suffice to say it is fallacious both factually and in principle. > I know couple of points : Development time is less + easy to learn + > python is expressive. These are all different dimensions of "betterness". Which aspect is important to you? There are no perfect languages. > Can you share some more especially as compared to Java / .net (two > primarily used languages in enterprise language & web based applications) .Net is not a lanuage it is a programming environment which supports multiple languages, but all of them working on the compile to bytecode then run in an interpreter model that Python mostly uses. Apart from trolling the list what do you hope to gain from this post? Do you have some objective, such as persuading a boss to allow you use Python instead of Java/.Net? Are you looking for justification to yourself to learn Python? (In that case forget everything else and just learn it for the different approaches and constructs it takes - like any other new language. Learning new languages will always benefit your programming by exposing new idioms.) HTH, -- Alan G Just back from an internet free vacation :-) From kellyadrian at hotmail.com Sat Sep 24 00:56:46 2011 From: kellyadrian at hotmail.com (ADRIAN KELLY) Date: Fri, 23 Sep 2011 22:56:46 +0000 Subject: [Tutor] password loop Message-ID: <DUB103-W46AFDAB0C1891553131C5EA90F0@phx.gbl> Can anyone help me with the programme below; i hope you can see what i am trying to do, if i enter the wrong password the loop goes on forever and if i enter the right one nothing is printed... i am a newbie............all comments welcome thanks adrian................ print 'hello' print 'i am your computer' # set the values password='route9999' Enter_Password=raw_input ('please enter your password: ') #password loop while Enter_Password != password: if Enter_Password !=password: print 'try again' else: print 'well done' -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110923/5b769662/attachment.html> From eire1130 at gmail.com Sat Sep 24 01:15:36 2011 From: eire1130 at gmail.com (eire1130 at gmail.com) Date: Fri, 23 Sep 2011 23:15:36 +0000 Subject: [Tutor] password loop In-Reply-To: <DUB103-W46AFDAB0C1891553131C5EA90F0@phx.gbl> References: <DUB103-W46AFDAB0C1891553131C5EA90F0@phx.gbl> Message-ID: <1184839337-1316819738-cardhu_decombobulator_blackberry.rim.net-1505688878-@b1.c28.bise6.blackberry> The while condition is never true when you enter the correct password. So the while loop is evaluated False and is never triggered. What you should do, as a general rule of troubleshooting, is to use print statements. So print the two outcomes and print the boolean evaluation I'm assuming when it is false that it prints 'try again' infinitely. Sent from my Verizon Wireless BlackBerry -----Original Message----- From: ADRIAN KELLY <kellyadrian at hotmail.com> Sender: tutor-bounces+eire1130=gmail.com at python.org Date: Fri, 23 Sep 2011 22:56:46 To: <tutor at python.org> Subject: [Tutor] password loop _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From steve at alchemy.com Sat Sep 24 01:17:31 2011 From: steve at alchemy.com (Steve Willoughby) Date: Fri, 23 Sep 2011 16:17:31 -0700 Subject: [Tutor] password loop In-Reply-To: <DUB103-W46AFDAB0C1891553131C5EA90F0@phx.gbl> References: <DUB103-W46AFDAB0C1891553131C5EA90F0@phx.gbl> Message-ID: <4E7D138B.8040906@alchemy.com> On 23-Sep-11 15:56, ADRIAN KELLY wrote: > Can anyone help me with the programme below; i hope you can see what i > am trying to do, if i enter the wrong password the loop goes on forever > and if i enter the right one nothing is printed... > i am a newbie............all comments welcome Remember that raw_input() is what actually asks you a question and stores your answer somewhere. You only ever ask the question one time in your code, then keep re-checking the same value over and over, without anything to ever change its value. In a case like this, it's helpful (especially if you're new to programming) to step through the instructions you've written for the computer, one at a time, and repeat to yourself what each step is accomplishing. -- Steve Willoughby / steve at alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C From steve at pearwood.info Sat Sep 24 04:17:30 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 24 Sep 2011 12:17:30 +1000 Subject: [Tutor] password loop In-Reply-To: <DUB103-W46AFDAB0C1891553131C5EA90F0@phx.gbl> References: <DUB103-W46AFDAB0C1891553131C5EA90F0@phx.gbl> Message-ID: <4E7D3DBA.3060509@pearwood.info> ADRIAN KELLY wrote: > Can anyone help me with the programme below; i hope you can see what i am trying to do, if i enter the wrong password the loop goes on forever and if i enter the right one nothing is printed... > i am a newbie............all comments welcome > > thanks adrian................ > > print 'hello' > print 'i am your computer' > > # set the values > password='route9999' > Enter_Password=raw_input ('please enter your password: ') This sets the password once, outside the loop. > #password loop > while Enter_Password != password: > if Enter_Password !=password: > print 'try again' > else: > print 'well done' This loops forever, but never asks for a password. You need to ask for a password *inside* the loop. actual_password = 'route9999' given_password = '' while given_password != actual_password: given_password = raw_input('please enter your password: ') if given_password == actual_password: print 'well done' else: print 'try again' -- Steven From steve at pearwood.info Sat Sep 24 04:24:44 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 24 Sep 2011 12:24:44 +1000 Subject: [Tutor] How it is better than java In-Reply-To: <j5j2bf$mdo$1@dough.gmane.org> References: <CAC88qxfnUOCorLUOpYZXZXycT2OZXBPUztx9iJoO7rLuC1Yjuw@mail.gmail.com> <j5j2bf$mdo$1@dough.gmane.org> Message-ID: <4E7D3F6C.7030000@pearwood.info> Alan Gauld wrote: > Apart from trolling the list what do you hope to gain from this post? Be fair -- there's no evidence that Ashish Gaonker was insincere about his question or trying to stir up trouble. It is a very common misapprehension that "language Foo is faster than language Bar", and in practice, Java programs often are faster than the equivalent Python program. That's a quality of implementation issue rather than a language issue: Python hasn't had the millions of dollars of development that Java has had. But I bet I could write a Java compiler that was slower than Python, easy! <wink> -- Steven From suryak at live.com Sat Sep 24 05:50:31 2011 From: suryak at live.com (surya k) Date: Sat, 24 Sep 2011 09:20:31 +0530 Subject: [Tutor] integrating python and C Message-ID: <CAArdDCoFUQ8nfKuS=0-vtC119GCA3TfRdzvzbvOLeMt0Y1YDig@mail.gmail.com> Hi! Actually, I'm writing sudoku solver. So, I'd write my logic in C but when it comes to GUI, I feel that python is much easier than doing in C. What I'm looking at is, take input from python program with graphic interface and passing it to my C program file then solve the puzzle and again passing the whole array to python code to display.. How should I do it. Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110924/00712bc7/attachment-0001.html> From cfuller084 at thinkingplanet.net Sat Sep 24 06:18:48 2011 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Fri, 23 Sep 2011 23:18:48 -0500 Subject: [Tutor] integrating python and C In-Reply-To: <CAArdDCoFUQ8nfKuS=0-vtC119GCA3TfRdzvzbvOLeMt0Y1YDig@mail.gmail.com> References: <CAArdDCoFUQ8nfKuS=0-vtC119GCA3TfRdzvzbvOLeMt0Y1YDig@mail.gmail.com> Message-ID: <201109232318.49828.cfuller084@thinkingplanet.net> Sudoku is actually a pretty easy problem computationally, I'd do the whole thing in Python, unless you aren't as comfortable doing fancy algorithms (usually easier, anyway, unless you aren't used to the language, or really need static typing) in Python.. but then this would be a good opportunity to overcome that :) Or you're doing large boards, generating puzzles in bulk, or something like that that multiplies the computational effort. The GNOME Sudoku is written in Python, by the way. There's tons of ways to interface C and Python. You can access the Python API directly: http://docs.python.org/extending/index.html; this is not for the faint of heart, but it provides maximum control and you learn a lot about Python internals on the way! Write your C code as a library and use SWIG to wrap it up into a Python module: http://www.swig.org/; this can get interesting if you have complicated call signatures, I sometimes avoid it and go right to the API, since I'm comfortable there :) If your code is C++, you can do something similar with Boost::Python: http://www.boost.org/doc/libs/1_47_0/libs/python/doc/; I've never used it, but it's there. Note that SWIG works fine with C++ libraries. There's always the Python-C hybrid, Cython: http://cython.org/; I haven't waded into its waters yet, either. But I'd recommend doing it all in Python, for the exercise, if nothing else, unless you have a good reason not to. GNOME Sudoku: http://live.gnome.org/GnomeSudoku Cheers On Friday 23 September 2011, surya k wrote: > Hi! > > Actually, I'm writing sudoku solver. So, I'd write my logic in C but when > it comes to GUI, I feel that python is much easier than doing in C. > What I'm looking at is, take input from python program with graphic > interface and passing it to my C program file then solve the puzzle and > again passing the whole array to python code to display.. > > How should I do it. > > Thanks. From amonroe at columbus.rr.com Sat Sep 24 07:56:33 2011 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sat, 24 Sep 2011 01:56:33 -0400 Subject: [Tutor] paper scissors In-Reply-To: <4E7CD7D4.4050005@gmail.com> References: <CAB=+OuQ87oJVD-x526Up-VhJvgzRj5+sNJ6JVF1+t5eCKzOUvg@mail.gmail.com> <CAB=+OuRApEEGLsNLtfqfRQ0KTA-6qNfxSCxuiRnsVWXQ73Znvw@mail.gmail.com> <4E7BC62D.3010607@gmail.com> <CAB=+OuSjUCCjQ3FHN1aK2F3B-iVrPLg24xAmAPYS-0DSqjpSjA@mail.gmail.com> <4E7CD7D4.4050005@gmail.com> Message-ID: <881809760898.20110924015633@columbus.rr.com> >> There are 2 things I don't understand. >> 1. the %s >> 2. the (wins,loses) Did you ever play Mad Libs when you were a kid? http://en.wikipedia.org/wiki/Madlibs Same concept. The %s in Python is just like the blank spaces in a Mad Lib game. The items in parentheses after a percent sign are the variables that "fill in the blanks". Alan From kinuthia.muchane at gmail.com Sat Sep 24 09:58:45 2011 From: kinuthia.muchane at gmail.com (=?UTF-8?B?S8SpbsWpdGhpYSBNxaljaGFuZQ==?=) Date: Sat, 24 Sep 2011 10:58:45 +0300 Subject: [Tutor] guess-my-number programme In-Reply-To: <CAPM86NfC3ZVWO_cXJDUeEcveP7eCgVs_gxN795j7f6=uXkobSA@mail.gmail.com> References: <DUB103-W627F923D1E3302DF756901A90F0@phx.gbl> <CAPM86NfC3ZVWO_cXJDUeEcveP7eCgVs_gxN795j7f6=uXkobSA@mail.gmail.com> Message-ID: <4E7D8DB5.3070109@gmail.com> On 09/23/2011 11:28 PM, Wayne Werner wrote: > On Fri, Sep 23, 2011 at 2:25 PM, ADRIAN KELLY <kellyadrian at hotmail.com > <mailto:kellyadrian at hotmail.com>> wrote: > > <snip> > > can anyone explain the *_tries_* part of this programme to me i > know its meant to count the number of guesses made by the user by > adding 1 but i just cant figure out how it does this..........can > someone explain?? i.e. tries = 1, tries +1 etc.... cant get my > head around it... > > > The concept that's confusing you here is something called order of > evaluation, or evaluation strategy: > http://en.wikipedia.org/wiki/Evaluation_strategy > > The best way to understand these things is to try it out, and the > interactive interpreter is extremely handy. > > I presume you understand the concept of assignment, correct? For example: > > >>> tries = 1 > > Now tries contains 1: > > >>> tries = 1 > >>> tries > 1 > > The variable 'tries' now contains the value 1 (In Python this is not > technically true, but it's useful to describe it that way). Why? > > >>> tries = 4 > > Now 'tries' contains 4. Of course, just like your standard algebra > variables, you can use your variables in python: > > >>> tries * 4 > 16 > >>> tries + tries > 8 > >>> tries / 1 > 4 > > when these expressions are /evaluated/ they produce the mathematical > expression you probably expect. But you can do more than just evaluate > expressions, you can store their results: > > >>> lots_of_tries = tries * 100 > >>> lots_of_tries > 400 > > So what about the expression that confuses you? > > >>> tries = tries + 1 > >>> tries > 5 > > Well, the first thing that happens when python sees the equals sign is > that the right hand side of the expression is evaluated, so python takes: > > tries = tries + 1 > > and turns it into > > tries = 4 + 1 > tries = 5 > > So each time your program sees 'tries = tries + 1' python evaluates > the right side first, then assigns its value to the variable on the left. > > HTH, > Wayne > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- K?n?thia S 1? 8' 24? E 36? 57' 36? 1522m -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110924/c9440332/attachment.html> From bodsda at googlemail.com Sat Sep 24 14:55:07 2011 From: bodsda at googlemail.com (bodsda at googlemail.com) Date: Sat, 24 Sep 2011 12:55:07 +0000 Subject: [Tutor] paper scissors In-Reply-To: <4E7CD7D4.4050005@gmail.com> References: <CAB=+OuQ87oJVD-x526Up-VhJvgzRj5+sNJ6JVF1+t5eCKzOUvg@mail.gmail.com><CAB=+OuRApEEGLsNLtfqfRQ0KTA-6qNfxSCxuiRnsVWXQ73Znvw@mail.gmail.com><4E7BC62D.3010607@gmail.com><CAB=+OuSjUCCjQ3FHN1aK2F3B-iVrPLg24xAmAPYS-0DSqjpSjA@mail.gmail.com><4E7CD7D4.4050005@gmail.com> Message-ID: <1263225280-1316868908-cardhu_decombobulator_blackberry.rim.net-1401081418-@b28.c12.bise7.blackberry> The %s signifies that a string will be provided to go there. The % after the string signifies that the following variable/strings/tuple will contain the items to be placed where the %s's are (in order) The tuple (wins, losses) are the two items that should replace the %s's Be aware that there are other place holders such as %i and %d that expect a certain data type. With %s, if it is not a string that is given to it, it will attempt to be converted to a string first. Hope this helps, Bodsda Sent from my BlackBerry? wireless device -----Original Message----- From: bob gailer <bgailer at gmail.com> Sender: tutor-bounces+bodsda=googlemail.com at python.org Date: Fri, 23 Sep 2011 15:02:44 To: *tutor python<tutor at python.org> Subject: Re: [Tutor] paper scissors _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From cmacleod170 at gmail.com Sat Sep 24 16:43:19 2011 From: cmacleod170 at gmail.com (Cameron Macleod) Date: Sat, 24 Sep 2011 15:43:19 +0100 Subject: [Tutor] Infinite Loop Message-ID: <CAExoPr2gG8q5WFEkZB8zScuOJHH+iwhRyTOjcQCmSwFzJKi32g@mail.gmail.com> Hi, I've been trying to code a simple guess my number game as a starter programming project but I've generated an infinite loop accidentally. Since I'm new to programming in general, I can't really figure out what's causing it. Thanks ======================= import random print("\tWelcome to 'Guess my Number'!") print("\nI'm thinking of a number between 1 and 100.") print("Try to guess it in as few attempts as possible.\n") #set the initial values the_number = random.randint(1, 100) guess = int(input("Take a guess: ")) tries = 1 # guessing loop while guess != the_number: if guess > the_number: print("Lower...") else: print("Higher...") guess = int(input("Take a guess: ")) tries += 1 print("You guessed it! The number was", the_number) print("And it only took you", tries, "tries!\n") if tries <= 5: print("I didn't know roadrunners could type!") elif tries >= 99: print("P'raps 'Only' wasn't the right word...") elif tries == 100: print("0_0 You are the unluckiest person in the world. Or the stupidest...") input("\n\nPress the enter key to exit.") -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110924/74524887/attachment.html> From nehal.dattani at gmail.com Sat Sep 24 17:00:14 2011 From: nehal.dattani at gmail.com (nehal dattani) Date: Sat, 24 Sep 2011 20:30:14 +0530 Subject: [Tutor] Infinite Loop In-Reply-To: <CAExoPr2gG8q5WFEkZB8zScuOJHH+iwhRyTOjcQCmSwFzJKi32g@mail.gmail.com> References: <CAExoPr2gG8q5WFEkZB8zScuOJHH+iwhRyTOjcQCmSwFzJKi32g@mail.gmail.com> Message-ID: <CAHn-yPxuN+q1jW-3hcfgNKgFy5e3UqG8KB8xYoQJk=2LDRgfmA@mail.gmail.com> Hi, Please modify your else block . else: print("Higher...") guess = int(input("Take a guess: ")) tries += 1 This should work for you. Regards, Nehal Dattani On Sat, Sep 24, 2011 at 8:13 PM, Cameron Macleod <cmacleod170 at gmail.com>wrote: > Hi, > > I've been trying to code a simple guess my number game as a starter > programming project but I've generated an infinite loop accidentally. Since > I'm new to programming in general, I can't really figure out what's causing > it. Thanks > > ======================= > > import random > > print("\tWelcome to 'Guess my Number'!") > print("\nI'm thinking of a number between 1 and 100.") > print("Try to guess it in as few attempts as possible.\n") > > #set the initial values > the_number = random.randint(1, 100) > guess = int(input("Take a guess: ")) > tries = 1 > > # guessing loop > while guess != the_number: > if guess > the_number: > print("Lower...") > else: > print("Higher...") > > guess = int(input("Take a guess: ")) > tries += 1 > > print("You guessed it! The number was", the_number) > print("And it only took you", tries, "tries!\n") > > if tries <= 5: > print("I didn't know roadrunners could type!") > elif tries >= 99: > print("P'raps 'Only' wasn't the right word...") > elif tries == 100: > print("0_0 You are the unluckiest person in the world. Or the > stupidest...") > > 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 > > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110924/2279a65d/attachment.html> From nehal.dattani at gmail.com Sat Sep 24 17:06:35 2011 From: nehal.dattani at gmail.com (nehal dattani) Date: Sat, 24 Sep 2011 20:36:35 +0530 Subject: [Tutor] Infinite Loop In-Reply-To: <CAExoPr2gG8q5WFEkZB8zScuOJHH+iwhRyTOjcQCmSwFzJKi32g@mail.gmail.com> References: <CAExoPr2gG8q5WFEkZB8zScuOJHH+iwhRyTOjcQCmSwFzJKi32g@mail.gmail.com> Message-ID: <CAHn-yPz8Qd5hBFnubEgeD3=g-YKyqO6VZZjX9XM1Wu8am5y=DQ@mail.gmail.com> Hi cameron, Sorry, I didn't tested it properly. Actual block should go like this while guess != the_number: if guess > the_number: print("Lower...") else: print("Higher...") guess = int(input("Take a guess: ")) tries += 1 On Sat, Sep 24, 2011 at 8:13 PM, Cameron Macleod <cmacleod170 at gmail.com>wrote: > Hi, > > I've been trying to code a simple guess my number game as a starter > programming project but I've generated an infinite loop accidentally. Since > I'm new to programming in general, I can't really figure out what's causing > it. Thanks > > ======================= > > import random > > print("\tWelcome to 'Guess my Number'!") > print("\nI'm thinking of a number between 1 and 100.") > print("Try to guess it in as few attempts as possible.\n") > > #set the initial values > the_number = random.randint(1, 100) > guess = int(input("Take a guess: ")) > tries = 1 > > # guessing loop > while guess != the_number: > if guess > the_number: > print("Lower...") > else: > print("Higher...") > > guess = int(input("Take a guess: ")) > tries += 1 > > print("You guessed it! The number was", the_number) > print("And it only took you", tries, "tries!\n") > > if tries <= 5: > print("I didn't know roadrunners could type!") > elif tries >= 99: > print("P'raps 'Only' wasn't the right word...") > elif tries == 100: > print("0_0 You are the unluckiest person in the world. Or the > stupidest...") > > 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 > > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110924/f70786b6/attachment.html> From thudfoo at gmail.com Sat Sep 24 17:28:14 2011 From: thudfoo at gmail.com (xDog Walker) Date: Sat, 24 Sep 2011 08:28:14 -0700 Subject: [Tutor] Infinite Loop In-Reply-To: <CAExoPr2gG8q5WFEkZB8zScuOJHH+iwhRyTOjcQCmSwFzJKi32g@mail.gmail.com> References: <CAExoPr2gG8q5WFEkZB8zScuOJHH+iwhRyTOjcQCmSwFzJKi32g@mail.gmail.com> Message-ID: <201109240828.14646.thudfoo@gmail.com> On Saturday 2011 September 24 07:43, Cameron Macleod wrote: > Hi, > > I've been trying to code a simple guess my number game as a starter > programming project but I've generated an infinite loop accidentally. Since > I'm new to programming in general, I can't really figure out what's causing > it. Thanks > > ======================= > > import random > > print("\tWelcome to 'Guess my Number'!") > print("\nI'm thinking of a number between 1 and 100.") > print("Try to guess it in as few attempts as possible.\n") > > #set the initial values > the_number = random.randint(1, 100) > guess = int(input("Take a guess: ")) > tries = 1 > > # guessing loop > while guess != the_number: > if guess > the_number: > print("Lower...") > else: > print("Higher...") > > guess = int(input("Take a guess: ")) > tries += 1 > > print("You guessed it! The number was", the_number) > print("And it only took you", tries, "tries!\n") > > if tries <= 5: > print("I didn't know roadrunners could type!") > elif tries >= 99: > print("P'raps 'Only' wasn't the right word...") > elif tries == 100: > print("0_0 You are the unluckiest person in the world. Or the > stupidest...") > > input("\n\nPress the enter key to exit.") I suspect that your test procedure was invalid. When I converted your code to run with python 2.5 and lowered the randint to (1, 5), it ran alright. -- I have seen the future and I am not in it. From alan.gauld at btinternet.com Sat Sep 24 18:48:38 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 24 Sep 2011 17:48:38 +0100 Subject: [Tutor] Infinite Loop In-Reply-To: <CAExoPr2gG8q5WFEkZB8zScuOJHH+iwhRyTOjcQCmSwFzJKi32g@mail.gmail.com> References: <CAExoPr2gG8q5WFEkZB8zScuOJHH+iwhRyTOjcQCmSwFzJKi32g@mail.gmail.com> Message-ID: <j5l1l6$m5q$1@dough.gmane.org> On 24/09/11 15:43, Cameron Macleod wrote: > Hi, > > I've been trying to code a simple guess my number game as a starter > programming project but I've generated an infinite loop accidentally. > Since I'm new to programming in general, I can't really figure out > what's causing it. Nehal told you how to fix it but didn't explain why. You have the input() call indented to the same level as the else block so it only gets executed as part of that block. If the guessed number is greater than the target the loop repeats infinitely. By moving the input() line out you get a new number each time. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From swiftone at swiftone.org Sat Sep 24 19:20:29 2011 From: swiftone at swiftone.org (Brett Ritter) Date: Sat, 24 Sep 2011 13:20:29 -0400 Subject: [Tutor] Logging to different directories Message-ID: <CAMb349x93YnHvmgXE6Ex=_tTU5GLtMpbPiLwgPHP_JmqOcK7Gw@mail.gmail.com> I commonly prefer to have my log files in /YYYY/MM/DD/ directories (it allows for lots of fun command-line actions). I've not yet sussed out a nice way to do this with the logging module. Before I ask the main list, is there a fundamental feature I've missed? The TimedRotatingFileHandler will let me write to filenames based on date, but it won't alter the path (in fact, the entire logging module seems to be built on the assumption of no subdirectories). Have I missed something? -- Brett Ritter / SwiftOne swiftone at swiftone.org From questions.anon at gmail.com Mon Sep 26 01:21:27 2011 From: questions.anon at gmail.com (questions anon) Date: Mon, 26 Sep 2011 09:21:27 +1000 Subject: [Tutor] Funtions, modules & global variables Message-ID: <CAN_=ogse6i=VFYKmN_a-UtbpT9A=BRra26seK11=nE9-GQOk0w@mail.gmail.com> Hi All, I am trying to move from writing one long script each time I need to do a new thing but I do not quite understand how functions work, even after reading many manuals. My first attempt is to create a python file where I have defined a number of functions that get data in various ways. I have also made another python file where I want to plot the data in different ways. but I am having trouble getting that data to run in my python plotting file. I have made the variable I require 'global' but that doesn't seem to be working. I keep receiving: * UnboundLocalError: local variable 'TSFC' referenced before assignment* Below is a some of the script for both folder, just note that their will be many functions in each folder Any help will be greatly appreciated!!! #selectdata.py def selectalldata(): for (path, dirs, files) in os.walk(MainFolder): for dir in dirs: print dir path=path+'/' for ncfile in files: if ncfile[-3:]=='.nc': print "dealing with ncfiles:", path+ncfile ncfile=os.path.join(path,ncfile) ncfile=Dataset(ncfile, 'r+', 'NETCDF4') global TSFC TSFC=ncfile.variables['T_SFC'][:,:,:] LAT=ncfile.variables['latitude'][:] LON=ncfile.variables['longitude'][:] TIME=ncfile.variables['time'][:] fillvalue=ncfile.variables['T_SFC']._FillValue ncfile.close() #plotdata.py from selectdata import selectalldata selectalldata() def plotncfilewithtime(): for TSFC, TIME in zip((TSFC[1::3]),(TIME[1::3])): #convert time from numbers to date and prepare it to have no symbols for saving to filename cdftime=utime('seconds since 1970-01-01 00:00:00') ncfiletime=cdftime.num2date(TIME) print ncfiletime timestr=str(ncfiletime) d = datetime.strptime(timestr, '%Y-%m-%d %H:%M:%S') date_string = d.strftime('%Y%m%d_%H%M') map = Basemap(projection='merc',llcrnrlat=-40,urcrnrlat=-33, llcrnrlon=139.0,urcrnrlon=151.0,lat_ts=0,resolution='i') x,y=map(*N.meshgrid(LON,LAT)) map.drawcoastlines(linewidth=0.5) map.readshapefile(shapefile1, 'DSE_REGIONS') map.drawstates() plt.title('Surface temperature at %s UTC'%ncfiletime) ticks=[-5,0,5,10,15,20,25,30,35,40,45,50] CS = map.contourf(x,y,TSFC, ticks, cmap=plt.cm.jet) l,b,w,h =0.1,0.1,0.8,0.8 cax = plt.axes([l+w+0.025, b, 0.025, h], ) cbar=plt.colorbar(CS, cax=cax, drawedges=True) plt.savefig((os.path.join(outputfolder, 'TSFC'+date_string+'UTC.png'))) plt.close() # must use plt.close() so that colorbar works! print "end of processing" plotncfilewithtime() -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110926/147f0480/attachment.html> From d at davea.name Mon Sep 26 01:58:07 2011 From: d at davea.name (Dave Angel) Date: Sun, 25 Sep 2011 19:58:07 -0400 Subject: [Tutor] Funtions, modules & global variables In-Reply-To: <CAN_=ogse6i=VFYKmN_a-UtbpT9A=BRra26seK11=nE9-GQOk0w@mail.gmail.com> References: <CAN_=ogse6i=VFYKmN_a-UtbpT9A=BRra26seK11=nE9-GQOk0w@mail.gmail.com> Message-ID: <4E7FC00F.9010303@davea.name> On 09/25/2011 07:21 PM, questions anon wrote: > Hi All, > I am trying to move from writing one long script each time I need to do a > new thing but I do not quite understand how functions work, even after > reading many manuals. > My first attempt is to create a python file where I have defined a number of > functions that get data in various ways. > I have also made another python file where I want to plot the data in > different ways. but I am having trouble getting that data to run in my > python plotting file. > I have made the variable I require 'global' but that doesn't seem to be > working. I keep receiving: > * > UnboundLocalError: local variable 'TSFC' referenced before assignment* > > Below is a some of the script for both folder, just note that their will be > many functions in each folder > Any help will be greatly appreciated!!! > > #selectdata.py > def selectalldata(): > for (path, dirs, files) in os.walk(MainFolder): > for dir in dirs: > print dir > path=path+'/' > for ncfile in files: > if ncfile[-3:]=='.nc': > print "dealing with ncfiles:", path+ncfile > ncfile=os.path.join(path,ncfile) > ncfile=Dataset(ncfile, 'r+', 'NETCDF4') > global TSFC > TSFC=ncfile.variables['T_SFC'][:,:,:] > LAT=ncfile.variables['latitude'][:] > LON=ncfile.variables['longitude'][:] > TIME=ncfile.variables['time'][:] > fillvalue=ncfile.variables['T_SFC']._FillValue > ncfile.close() > > > #plotdata.py > > from selectdata import selectalldata > selectalldata() > > def plotncfilewithtime(): > for TSFC, TIME in zip((TSFC[1::3]),(TIME[1::3])): > #convert time from numbers to date and prepare it to have no symbols for > saving to filename > cdftime=utime('seconds since 1970-01-01 00:00:00') > ncfiletime=cdftime.num2date(TIME) > print ncfiletime > timestr=str(ncfiletime) > d = datetime.strptime(timestr, '%Y-%m-%d %H:%M:%S') > date_string = d.strftime('%Y%m%d_%H%M') > map = Basemap(projection='merc',llcrnrlat=-40,urcrnrlat=-33, > > llcrnrlon=139.0,urcrnrlon=151.0,lat_ts=0,resolution='i') > > x,y=map(*N.meshgrid(LON,LAT)) > map.drawcoastlines(linewidth=0.5) > map.readshapefile(shapefile1, 'DSE_REGIONS') > map.drawstates() > > plt.title('Surface temperature at %s UTC'%ncfiletime) > ticks=[-5,0,5,10,15,20,25,30,35,40,45,50] > CS = map.contourf(x,y,TSFC, ticks, cmap=plt.cm.jet) > l,b,w,h =0.1,0.1,0.8,0.8 > cax = plt.axes([l+w+0.025, b, 0.025, h], ) > cbar=plt.colorbar(CS, cax=cax, drawedges=True) > > plt.savefig((os.path.join(outputfolder, > 'TSFC'+date_string+'UTC.png'))) > plt.close() # must use plt.close() so that colorbar works! > > print "end of processing" > plotncfilewithtime() > 1) If you're just learning how to split a long top-level script into functions, don't confuse the issues by also trying multiple source files, and especially multiple folders of source files. Learn one concept before starting on the other. 2) when you mention an error message, give the whole thing, including stack trace. or one thing, that'd mean we could see which line actually got the error. 3) if a function doesn't take any arguments and doesn't return any values, you're probably wasting your time. Separate functions that only share by global variables aren't much better than top-level code. 4) When you declare a global in a function, please do it at the beginning of the function, right after the docstring. 5) Use all caps for constants, not for ordinary varables. It's just a convention, but it'll make the code easier for others to read. 6) That particular error means that a variable in a function, WITHOUT a global statement, has been used as an rvalue, without first having been given a value. The most common cause for that is that the assignment occurs inside a conditional, but you get the error when that particular branch doesn't happen. Since your present code is in multiple files, I'll also point out: global means global to the one module, not global to the whole program. -- DaveA From alan.gauld at btinternet.com Mon Sep 26 02:35:43 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 26 Sep 2011 01:35:43 +0100 Subject: [Tutor] Funtions, modules & global variables In-Reply-To: <CAN_=ogse6i=VFYKmN_a-UtbpT9A=BRra26seK11=nE9-GQOk0w@mail.gmail.com> References: <CAN_=ogse6i=VFYKmN_a-UtbpT9A=BRra26seK11=nE9-GQOk0w@mail.gmail.com> Message-ID: <j5ohd0$sa3$1@dough.gmane.org> On 26/09/11 00:21, questions anon wrote: > Hi All, > I am trying to move from writing one long script each time I need to do > a new thing but I do not quite understand how functions work, even after > reading many manuals. Can you be more specific about what you dpn;t understand. For example can you understand how this function works? def square(x): return x*x If not what is the area of difficulty? > My first attempt is to create a python file where I have defined a > number of functions that get data in various ways. > I have also made another python file where I want to plot the data in > different ways. but I am having trouble getting that data to run in my > python plotting file. It may be easier to keep all the functions in a single file initially. It just eliminates an extra layer of complexity until we get things working. Once you know your functions work we can think about moving them into separate files. > I have made the variable I require 'global' but that doesn't seem to be > working. I keep receiving: > / > UnboundLocalError: local variable 'TSFC' referenced before assignment/ global in Python means global within the current file. It does not mean across all files. > > Below is a some of the script for both folder, just note that their will > be many functions in each folder I'm not sure I understand that bit. So I'll just ignore it for now! :-) > #selectdata.py > def selectalldata(): > for (path, dirs, files) in os.walk(MainFolder): > for dir in dirs: > print dir > path=path+'/' > for ncfile in files: > if ncfile[-3:]=='.nc': > print "dealing with ncfiles:", path+ncfile > ncfile=os.path.join(path,ncfile) > ncfile=Dataset(ncfile, 'r+', 'NETCDF4') > global TSFC Normally globals are defined at the top of the function. Its not necessary but its where most readers will look for it. In this case there is no existing global variable TSFC so it gets created in your module space on the assignment. > TSFC=ncfile.variables['T_SFC'][:,:,:] I'm not familiar with the [:,:,:] style? What does it do? Are you sure you want the commas? But since that happens inside an if block, if the block doesn't get executed the global variable will never get created. Any attempt to access the variable before the if block is executed will result in your error. > LAT=ncfile.variables['latitude'][:] > LON=ncfile.variables['longitude'][:] > TIME=ncfile.variables['time'][:] > fillvalue=ncfile.variables['T_SFC']._FillValue > ncfile.close() And since there are no other functions in this file nobody else can see the TSFC variable you created. And since the function does not return any data it will be hard for other modules to use this function. > > > #plotdata.py > > from selectdata import selectalldata > selectalldata() This will (msometimes) create a TSFC variable in the selectdata module, but you will not be able to access it here because you have not imported selectdata. If you had you could have done TSFC = selectdata.TSFC But since you didn't I suspect that > def plotncfilewithtime(): > for TSFC, TIME in zip((TSFC[1::3]),(TIME[1::3])): This will fail when it tries to slice TSFC which it can't see. Even if it did work it would be bad practice to do this sin e from the next line onwards the original TSFC would be masked by the new TSFC variable you are creating. Better to use unique names for the two values. > #convert time from numbers to date and prepare it to have no > symbols for saving to filename .... I ignored the techie stuff :-) > print "end of processing" > plotncfilewithtime() Again, this is not the best way to use functions, better to get the function to return the output to be displayed by the other program. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From bbbgggwww at gmail.com Mon Sep 26 04:25:06 2011 From: bbbgggwww at gmail.com (brandon w) Date: Sun, 25 Sep 2011 22:25:06 -0400 Subject: [Tutor] My code works but it is a little bit broken. Message-ID: <CAKXQjyUyQLRSEXm=cs+3+iMa_Tx9TZ3pyX4TwobQsqGAz9KHwQ@mail.gmail.com> This code calculates money. The problem is that in the first field after the mouse enters a second time updates itself with the value from the last field. I don't want it to do that. I think that the problem is in the "callback" method. #!/usr/bin/python from Tkinter import * root = Tk() root.title("Money Calculator") root.geometry("400x300") root.grid() def callback(event): field0 = varText1.get() initAmount.delete(0, END) initAmount.insert(0, field0) return def calculateAmount(): field1 = varText.get() weekly_sum.delete(0, END) weekly_sum.insert(0, int(field1 * 7)) field2 = varText.get() monthly_sum.delete(0, END) monthly_sum.insert(0, int(field2 * 31)) field3 = varText.get() yearly_sum.delete(0, END) yearly_sum.insert(0, int(field3 * 356)) field4 = varText.get() five_year_sum.delete(0, END) five_year_sum.insert(0, int((field4 * 1825) + 1)) field5 = varText.get() ten_year_sum.delete(0, END) ten_year_sum.insert(0, int((field5 * 3650) + 1)) return Label(root, text="Inital amount: $").grid(sticky=W, row=0) varText = IntVar() varText.set(0) initAmount = Entry(root, textvariable=varText, width=10, bg = "pale green") initAmount.bind("<Enter>", callback) initAmount.grid(sticky=W, row=0, column=1) Label(root, text="dollars").grid(sticky=W, column=2, row=0) varText1 = StringVar(None) Entry(root, textvariable=varText1, bg = "pale green").grid(sticky=W, row=1, columnspan=3) Label(root, text=".").grid(sticky=W, column=3, row=1) Label(root, text="Calculated amount: ").grid(sticky=W, row=3, columnspan=3) Button(root, text="Calculate", width=10, command=calculateAmount).grid(sticky=W, row=2, columnspan=3) Label(root, text="a week").grid(sticky=W, row=4, column=0) varText1 = StringVar(None) weekly_sum = Entry(root, textvariable=varText1, takefocus=0, width=15, bg = "pale green") weekly_sum.grid(sticky=W, row=4, column=2) Label(root, text="a month").grid(sticky=W, row=5, columnspan=3) varText1 = StringVar(None) monthly_sum = Entry(root, textvariable=varText1, takefocus=0, width=15, bg = "pale green") monthly_sum.grid(sticky=W, row=5, column=2) Label(root, text="a year").grid(sticky=W, row=6, columnspan=3) varText1 = StringVar(None) yearly_sum = Entry(root, textvariable=varText1, takefocus=0, width=15, bg = "pale green") yearly_sum.grid(sticky=W, row=6, column=2) Label(root, text="five years").grid(sticky=W, row=7, columnspan=3) varText1 = StringVar(None) five_year_sum = Entry(root, textvariable=varText1, takefocus=0, width=15, bg = "pale green") five_year_sum.grid(sticky=W, row=7, column=2) Label(root, text="ten years").grid(sticky=W, row=8, columnspan=3) varText1 = StringVar(None) ten_year_sum = Entry(root, textvariable=varText1, takefocus=0, width=15, bg = "pale green") ten_year_sum.grid(sticky=W, row=8, column=2) root.mainloop() Python 2.6.6 Linux -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110925/aa2bd558/attachment-0001.html> From alan.gauld at btinternet.com Mon Sep 26 10:03:43 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 26 Sep 2011 09:03:43 +0100 Subject: [Tutor] My code works but it is a little bit broken. In-Reply-To: <CAKXQjyUyQLRSEXm=cs+3+iMa_Tx9TZ3pyX4TwobQsqGAz9KHwQ@mail.gmail.com> References: <CAKXQjyUyQLRSEXm=cs+3+iMa_Tx9TZ3pyX4TwobQsqGAz9KHwQ@mail.gmail.com> Message-ID: <j5pbkv$97i$1@dough.gmane.org> On 26/09/11 03:25, brandon w wrote: > This code calculates money. The problem is that in the first field after > the mouse enters a second time updates itself with the value from the > last field. I don't want it to do that. > I think that the problem is in the "callback" method. > I haven't gone through this in depth but one thing that looked odd to me was: > def calculateAmount(): > field1 = varText.get() > ... > field2 = varText.get() > ... > field3 = varText.get() > ... > field4 = varText.get() > ... > field5 = varText.get() Are all fields supposed to be getting the same value? And if so why not just do it once at the start of the function? But as I say I didn't read it all in depth so maybe you have some magic going on that changes the value between reads... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From dosto.walla at gmail.com Mon Sep 26 12:53:50 2011 From: dosto.walla at gmail.com (Sajjad) Date: Mon, 26 Sep 2011 12:53:50 +0200 Subject: [Tutor] execute a function Message-ID: <CALxLa5i_1i-AwkCt=S0tpqK9sBsfnD7dgjyJFRXBKsjmHu-SBA@mail.gmail.com> Hello forum, It has been two days that i have started with python and i am stuck with the following simple issue: i have created a python file and inside the file i have defined a function as follows: //////////////////////////////////////////////////////////// def greeting(): print "Welcome to python" /////////////////////////////////////////////////////////// I am following the Book named - "Rapid GUI programming with Python and Qt" In the book they mentioned that in the command line if i type greeting() i should get the output "Welcome to python" But i get nothing. Any hint on this? Regards Sajjad -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110926/788de7c3/attachment.html> From steve at pearwood.info Mon Sep 26 13:15:07 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 26 Sep 2011 21:15:07 +1000 Subject: [Tutor] execute a function In-Reply-To: <CALxLa5i_1i-AwkCt=S0tpqK9sBsfnD7dgjyJFRXBKsjmHu-SBA@mail.gmail.com> References: <CALxLa5i_1i-AwkCt=S0tpqK9sBsfnD7dgjyJFRXBKsjmHu-SBA@mail.gmail.com> Message-ID: <4E805EBB.4050208@pearwood.info> Sajjad wrote: > Hello forum, > > > It has been two days that i have started with python and i am stuck with the > following simple issue: > > i have created a python file and inside the file i have defined a function > as follows: > > //////////////////////////////////////////////////////////// > def greeting(): > print "Welcome to python" > > /////////////////////////////////////////////////////////// > > I am following the Book named - "Rapid GUI programming with Python and Qt" > > In the book they mentioned that in the command line if i type > > greeting() i should get the output "Welcome to python" > > But i get nothing. "Nothing"? Are you sure? You shouldn't get nothing. You should get either "Welcome to python", or an error message. But you shouldn't get nothing at all. First off, you need to launch the Python interactive interpreter from the command line. I don't know what operating system you are using, but this is how I do it from Linux: Start menu > System > Terminal (terminal window opens) At the $ prompt, type: "python" and then press the Enter key. The terminal shows: [steve at sylar ~]$ python Python 2.5 (r25:51908, Nov 6 2007, 16:54:01) [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> Now, I don't know what you have called your Python file, so I will make up a name: "myfile.py". Make sure it is saved in your home directory. At the >>> prompt, type "import myfile" (WITHOUT the .py) and then hit Enter. The terminal shows: >>> import myfile >>> At the >>> prompt, type "myfile.greeting() and hit Enter: >>> myfile.greeting() Welcome to python >>> Now type "from myfile import greeting", Enter, then "greeting()", Enter: >>> from myfile import greeting >>> greeting() Welcome to python >>> Remember to change the word "myfile" to whatever the actual name of your file is. The file MUST have a .py extension, but inside Python you never use the .py. If you get any errors, please COPY AND PASTE them and send them to the mailing list. Don't type them by memory, paraphrase them, or otherwise edit them. Good luck! -- Steven From d at davea.name Mon Sep 26 13:22:27 2011 From: d at davea.name (Dave Angel) Date: Mon, 26 Sep 2011 07:22:27 -0400 Subject: [Tutor] execute a function In-Reply-To: <CALxLa5i_1i-AwkCt=S0tpqK9sBsfnD7dgjyJFRXBKsjmHu-SBA@mail.gmail.com> References: <CALxLa5i_1i-AwkCt=S0tpqK9sBsfnD7dgjyJFRXBKsjmHu-SBA@mail.gmail.com> Message-ID: <4E806073.608@davea.name> On 09/26/2011 06:53 AM, Sajjad wrote: > Hello forum, > > > It has been two days that i have started with python and i am stuck with the > following simple issue: > > i have created a python file and inside the file i have defined a function > as follows: > > //////////////////////////////////////////////////////////// > def greeting(): > print "Welcome to python" > > /////////////////////////////////////////////////////////// > > I am following the Book named - "Rapid GUI programming with Python and Qt" > > In the book they mentioned that in the command line if i type > > greeting() i should get the output "Welcome to python" > > But i get nothing. > > > Any hint on this? > > > Regards > Sajjad > A little more precision would be helpful. You never told us what you called that source file. And there are several possible "command line" you might be referring to. The most likely are the shell, and the interpreter prompt. if you had shown us your session (via cut 'n paste), we might have been able to guess. If you get nothing, then you must be somewhere else, since each of those will give you some response, depending on which shell you're running. So for example, if you're running Python 2.7 on Linux 10.04, with Bash as your shell, you might get davea at think:~$ greeting() > That > prompt means you haven't finished the command line, and bash is waiting for the rest. Use Ctrl-C to get out of that one. Greeting is not a program from bash's point of view. or if I'm running in the interpreter, I might get: 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. >>> greeting() Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'greeting' is not defined >>> And this would be because two errors have occurred. In the above session I didn't import the source file, and I didn't qualify the name greeting so the interpreter could look in that module. I would normally just add the greeting() call to the bottom of the source file firstprogram.py, and then run the whole thing with davea at think:~$ python firstprogram.py But your tutorial may have other ideas, so you'd best tell us what you've tried, and exactly what happened. -- DaveA From chanakya at optirisk-systems.com Mon Sep 26 13:55:06 2011 From: chanakya at optirisk-systems.com (Chanakya Mitra) Date: Mon, 26 Sep 2011 12:55:06 +0100 Subject: [Tutor] Review my code Message-ID: <D3BB39827235EC43BE146896E4AA631F015EDCD3@EXCH-BE30.exchange.local> I wrote a short script that tries to check if an email address exists or not. It takes the domain of the inputted email and looks up the registered mail exchange. It then connects via smtp and attempts the "RCPT TO:<entered email>" command and based on the response decides if the email exists or not. I was trying to be more OOP in my approach but not sure I've been entirely successful. Thanks for your time. Chan Code: import DNS, socket, string, re, sys servers = [] myserver = 'mailgate.xxxxxxxx.com' mymail = 'maywedtuza at xxxxxxxx.com' CRLF="\r\n" def mailxch(hname): mxhosts = DNS.mxlookup(hname) return mxhosts def prompt(prompt): return raw_input(prompt).strip() class smtsock(object): response = None def getmsg(self): self.response = self.msock.makefile('rb') while 1: try: line = self.response.readline() return line[:3], line[4:] except socket.error: self.msock.close() return "socket Error" def put(self,cmd,args=""): if args == "": str = '%s%s' % (cmd, CRLF) else: str = '%s %s%s' % (cmd, args, CRLF) try: self.msock.send(str) except socket.error: self.msock.close() return "socket Error" def pr(self,cmd,args=""): self.put(cmd, args) return self.getmsg() def conn(self,server): try: self.msock = socket.create_connection((server,25)) (hand, msg) = self.getmsg() return hand, msg except: err = sys.exc_info()[1] return err def helo(self, server): (hand, msg) = self.pr("HELO",server) return hand, msg def vrfy(self, hname): cstr = "<%s>"% hname (hand, msg) = self.pr("VRFY", cstr) return hand, msg def mailfrm(self, emf): cstr = "<%s>"% emf (hand, msg) = self.pr("MAIL FROM:", cstr) return hand, msg def rcptto(self,hname): cstr = "<%s>"% hname (hand, msg) = self.pr("rcpt to:", cstr) return hand, msg def cls(self): self.msock.close() rcpt_handlers = { "250":" \n#------------------------------------------# \n\tE-mail Exists\n#------------------------------------------# \n", "251":" User not local; will forward to <forward-path>", "550":" \n#------------------------------------------# \n\tNo Such Address\n#------------------------------------------# \n", "551":" User not local; please try <forward-path>", "552":" Requested mail action aborted: exceeded storage allocation", "553":" Requested action not taken: mailbox name not allowed", "450":" Requested mail action not taken: mailbox unavailable", "451":" Requested action aborted: local error in processing", "452":" Requested action not taken: insufficient system storage", "500":" Syntax error, command unrecognised", "501":" Syntax error in parameters or arguments", "503":" Bad sequence of commands", "521":" <domain> does not accept mail [rfc1846]", "socket Error":" Socket Error: Connection closed.", "421":" <domain> Service not available, closing transmission channel" } em = re.compile(r"(?:^|\s)[-a-z0-9_.]+@(?:[-a-z0-9]+\.)+[a-z]{2,6}(?:\s|$)",r e.IGNORECASE) while True: hname = prompt("E-Mail Address(or XX to quit): ") if hname == "XX": break if em.match(hname) == None: print "Email incorrect format" else: s = smtsock() servers = mailxch(hname.split("@")[1]) print servers i = 0 for i in range(len(servers)): print "Trying mailserver: %s"% servers[i][1] (reply, msg)= s.conn(servers[i][1]) if reply != '220': break (reply, msg) = s.helo(myserver) if reply != '250': break (reply, msg) = s.mailfrm(mymail) if reply != '250': break (reply, msg) = s.rcptto(hname) print rcpt_handlers.get(reply) if reply == '250': break s.cls() -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110926/b4ea60f1/attachment-0001.html> From suryak at live.com Mon Sep 26 14:46:00 2011 From: suryak at live.com (surya k) Date: Mon, 26 Sep 2011 18:16:00 +0530 Subject: [Tutor] taking input for a list in a list Message-ID: <CAArdDCq2K9GBXwpZuTm1eQ3YB7TxwaHn0KegMotnxHc6M1+YsA@mail.gmail.com> Hi, Actually my programming language is C.. learning python. I'm trying to write sudoku program for which I need to take input. This is what I did merely *list = [] for i in range (0,4) : for j in range (0,4) : list[i][j].append (" int (raw_input("Enter") ) ) * This is completely wrong.. but I couldn't handle this kind of.. how do I.. Actually I need a list in a list to handle sudoku. for a simple list to get input.. this would obviously work.. *list.append ( int(raw_input("Enter") )* Can you tell me how do I do this correctly ? -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110926/d8a65700/attachment.html> From joel.goldstick at gmail.com Mon Sep 26 15:08:05 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 26 Sep 2011 09:08:05 -0400 Subject: [Tutor] taking input for a list in a list In-Reply-To: <CAArdDCq2K9GBXwpZuTm1eQ3YB7TxwaHn0KegMotnxHc6M1+YsA@mail.gmail.com> References: <CAArdDCq2K9GBXwpZuTm1eQ3YB7TxwaHn0KegMotnxHc6M1+YsA@mail.gmail.com> Message-ID: <CAPM-O+xKD6KrQKEwL8x-xyzd_uXXs-PCj_=8+R8EU=C1tiQ5eQ@mail.gmail.com> On Mon, Sep 26, 2011 at 8:46 AM, surya k <suryak at live.com> wrote: > Hi, > > Actually my programming language is C.. learning python. > > I'm trying to write sudoku program for which I need to take input. > This is what I did merely > > *list = [] > for i in range (0,4) : > for j in range (0,4) : > list[i][j].append (" int (raw_input("Enter") ) ) > > * > This is completely wrong.. but I couldn't handle this kind of.. how do I.. > Actually I need a list in a list to handle sudoku. > > for a simple list to get input.. this would obviously work.. > *list.append ( int(raw_input("Enter") )* > > > Can you tell me how do I do this correctly ? > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > because list is a built in data type you should name your list something else. What does your code do? does it give traceback errors? After you change list to, say my_list what do you get? -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110926/fbf63536/attachment.html> From __peter__ at web.de Mon Sep 26 15:42:22 2011 From: __peter__ at web.de (Peter Otten) Date: Mon, 26 Sep 2011 15:42:22 +0200 Subject: [Tutor] taking input for a list in a list References: <CAArdDCq2K9GBXwpZuTm1eQ3YB7TxwaHn0KegMotnxHc6M1+YsA@mail.gmail.com> Message-ID: <j5pvff$nhb$1@dough.gmane.org> surya k wrote: > Actually my programming language is C.. learning python. > > I'm trying to write sudoku program for which I need to take input. > This is what I did merely > > *list = [] > for i in range (0,4) : > for j in range (0,4) : > list[i][j].append (" int (raw_input("Enter") ) ) > > * > This is completely wrong.. but I couldn't handle this kind of.. how do I.. > Actually I need a list in a list to handle sudoku. > > for a simple list to get input.. this would obviously work.. > *list.append ( int(raw_input("Enter") )* > > > Can you tell me how do I do this correctly ? Break the problem down to one you already know how to solve: if you add a new inner list for the columns to the outer list of rows adding an entry to the row means just appending an integer to the inner list: def input_int(): return int(raw_input("Enter an integer ")) square = [] N = 4 for i in range(N): row = [] square.append(row) for k in range(N): row.append(input_int()) From steve at pearwood.info Mon Sep 26 17:42:22 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 27 Sep 2011 01:42:22 +1000 Subject: [Tutor] Review my code In-Reply-To: <D3BB39827235EC43BE146896E4AA631F015EDCD3@EXCH-BE30.exchange.local> References: <D3BB39827235EC43BE146896E4AA631F015EDCD3@EXCH-BE30.exchange.local> Message-ID: <4E809D5E.2090909@pearwood.info> Chanakya Mitra wrote: > > > I wrote a short script that tries to check if an email address exists or > not. Some brief comments: When you send code by HTML email, you mess up the formatting of the code. Please don't do that in the future. > def mailxch(hname): > mxhosts = DNS.mxlookup(hname) > return mxhosts That can be re-written as: def mailxch(hname): return DNS.mxlookup(hname) but why bother calling the function? Instead of: x = mailxch("some host name") why not just call the actual function that does the work? x = DNS.mxlookup("some host name") If all you want is to use a different name, because you don't like "mxlookup", then: mailxch = DNS.mxlookup will bind the mxlookup function to the name "mailxch" without the cost of an extra function call. > def prompt(prompt): > return raw_input(prompt).strip() Another function which may be simple enough to just call inline. But that's a matter of taste. > class smtsock(object): > response = None This class has no initialiser (no __init__ method). Is that deliberate? Also, it is normal for classes to be named in CamelCase. > def getmsg(self): > self.response = self.msock.makefile('rb') > while 1: The more Pythonic idiom is to say "while True" rather than "while 1", although again that's a matter of taste. > try: > line = self.response.readline() > return line[:3], line[4:] > except socket.error: > self.msock.close() > return "socket Error" Generally speaking, this is poor design. Now you have a method which sometimes returns a tuple of lines, and sometimes a string. So you can't do this: alines, blines = smtsock().getmsg() because it will break if there is a socket error. So you have to do this: result = smtsock().getmsg() if result == "socket error": # oops, I spelled it wrong... # how do I recover from this? pass # ??? else: alines, blines = result Ugly and fragile! Don't write code like this. Instead, errors should raise an exception. The caller can always catch the exception if they know how to deal with it, or they can ignore it and let it bubble up to the top, then they will get a nice traceback. So something like this is probably better: try: line = self.response.readline() return line[:3], line[4:] finally: # Always close the socket, even if an error occurred. self.msock.close() If an error occurs, you will get an exception, but the socket will still be closed. > def put(self,cmd,args=""): > if args == "": > str = '%s%s' % (cmd, CRLF) > else: > str = '%s %s%s' % (cmd, args, CRLF) > try: > self.msock.send(str) > except socket.error: > self.msock.close() > return "socket Error" Same here. Never return a magic error code when you can use an exception instead. > def pr(self,cmd,args=""): > self.put(cmd, args) > return self.getmsg() > > def conn(self,server): > try: > self.msock = socket.create_connection((server,25)) > (hand, msg) = self.getmsg() > return hand, msg > except: Never catch a bare except! (Well, truth be told there are situations where catching a bare except is useful, but they're rare.) Bare excepts catch too much -- they mask bugs in your code, they prevent the user from interrupting the script with Ctrl-C. You should only ever catch the smallest set of exceptions that you know you can deal with. > err = sys.exc_info()[1] > return err Again, don't return magic error codes. > def helo(self, server): > (hand, msg) = self.pr("HELO",server) > return hand, msg > > def vrfy(self, hname): > cstr = "<%s>"% hname > (hand, msg) = self.pr("VRFY", cstr) > return hand, msg > > def mailfrm(self, emf): > cstr = "<%s>"% emf > (hand, msg) = self.pr("MAIL FROM:", cstr) > return hand, msg > > def rcptto(self,hname): > cstr = "<%s>"% hname > (hand, msg) = self.pr("rcpt to:", cstr) > return hand, msg > > def cls(self): > self.msock.close() Apart from the painfully terse method names ("cls"? Would typing "close" break your keyboard?), nothing looks too bad there. -- Steven From chanakya at optirisk-systems.com Mon Sep 26 23:19:18 2011 From: chanakya at optirisk-systems.com (Chanakya Mitra) Date: Mon, 26 Sep 2011 22:19:18 +0100 Subject: [Tutor] Review my code References: <D3BB39827235EC43BE146896E4AA631F015EDCD3@EXCH-BE30.exchange.local> <4E809D5E.2090909@pearwood.info> Message-ID: <D3BB39827235EC43BE146896E4AA631F17A0F4@EXCH-BE30.exchange.local> Hi Steve, >Some brief comments: > >When you send code by HTML email, you mess up the formatting of the >code. Please don't do that in the future. Noted and sorry about that. Someone also pointed out I should have said 'please' in my original email, so apologies if I came across as rude and demanding. Thanks for the feedback and critique, I'll be reworking the script with all your points in mind. Chan -----Original Message----- From: tutor-bounces+chanakya=optirisk-systems.com at python.org on behalf of Steven D'Aprano Sent: Mon 26/09/2011 16:42 To: Tutor at python.org Subject: Re: [Tutor] Review my code Chanakya Mitra wrote: > > > I wrote a short script that tries to check if an email address exists or > not. > def mailxch(hname): > mxhosts = DNS.mxlookup(hname) > return mxhosts That can be re-written as: def mailxch(hname): return DNS.mxlookup(hname) but why bother calling the function? Instead of: x = mailxch("some host name") why not just call the actual function that does the work? x = DNS.mxlookup("some host name") If all you want is to use a different name, because you don't like "mxlookup", then: mailxch = DNS.mxlookup will bind the mxlookup function to the name "mailxch" without the cost of an extra function call. > def prompt(prompt): > return raw_input(prompt).strip() Another function which may be simple enough to just call inline. But that's a matter of taste. > class smtsock(object): > response = None This class has no initialiser (no __init__ method). Is that deliberate? Also, it is normal for classes to be named in CamelCase. > def getmsg(self): > self.response = self.msock.makefile('rb') > while 1: The more Pythonic idiom is to say "while True" rather than "while 1", although again that's a matter of taste. > try: > line = self.response.readline() > return line[:3], line[4:] > except socket.error: > self.msock.close() > return "socket Error" Generally speaking, this is poor design. Now you have a method which sometimes returns a tuple of lines, and sometimes a string. So you can't do this: alines, blines = smtsock().getmsg() because it will break if there is a socket error. So you have to do this: result = smtsock().getmsg() if result == "socket error": # oops, I spelled it wrong... # how do I recover from this? pass # ??? else: alines, blines = result Ugly and fragile! Don't write code like this. Instead, errors should raise an exception. The caller can always catch the exception if they know how to deal with it, or they can ignore it and let it bubble up to the top, then they will get a nice traceback. So something like this is probably better: try: line = self.response.readline() return line[:3], line[4:] finally: # Always close the socket, even if an error occurred. self.msock.close() If an error occurs, you will get an exception, but the socket will still be closed. > def put(self,cmd,args=""): > if args == "": > str = '%s%s' % (cmd, CRLF) > else: > str = '%s %s%s' % (cmd, args, CRLF) > try: > self.msock.send(str) > except socket.error: > self.msock.close() > return "socket Error" Same here. Never return a magic error code when you can use an exception instead. > def pr(self,cmd,args=""): > self.put(cmd, args) > return self.getmsg() > > def conn(self,server): > try: > self.msock = socket.create_connection((server,25)) > (hand, msg) = self.getmsg() > return hand, msg > except: Never catch a bare except! (Well, truth be told there are situations where catching a bare except is useful, but they're rare.) Bare excepts catch too much -- they mask bugs in your code, they prevent the user from interrupting the script with Ctrl-C. You should only ever catch the smallest set of exceptions that you know you can deal with. > err = sys.exc_info()[1] > return err Again, don't return magic error codes. > def helo(self, server): > (hand, msg) = self.pr("HELO",server) > return hand, msg > > def vrfy(self, hname): > cstr = "<%s>"% hname > (hand, msg) = self.pr("VRFY", cstr) > return hand, msg > > def mailfrm(self, emf): > cstr = "<%s>"% emf > (hand, msg) = self.pr("MAIL FROM:", cstr) > return hand, msg > > def rcptto(self,hname): > cstr = "<%s>"% hname > (hand, msg) = self.pr("rcpt to:", cstr) > return hand, msg > > def cls(self): > self.msock.close() Apart from the painfully terse method names ("cls"? Would typing "close" break your keyboard?), nothing looks too bad there. -- 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: <http://mail.python.org/pipermail/tutor/attachments/20110926/8723c070/attachment-0001.html> From questions.anon at gmail.com Tue Sep 27 02:26:33 2011 From: questions.anon at gmail.com (questions anon) Date: Tue, 27 Sep 2011 10:26:33 +1000 Subject: [Tutor] Funtions, modules & global variables In-Reply-To: <j5ohd0$sa3$1@dough.gmane.org> References: <CAN_=ogse6i=VFYKmN_a-UtbpT9A=BRra26seK11=nE9-GQOk0w@mail.gmail.com> <j5ohd0$sa3$1@dough.gmane.org> Message-ID: <CAN_=ogsPQsfqUDxCRF5qn-p=hYNaTraFBbEn1mEnSZ7=dCDmZg@mail.gmail.com> Thanks for your feedback. I might be asking the wrong questions. I have written a number of scripts that do various things for each step: 1. get data (e.g. Dec-jan-feb, only januarys, all data) 2. summary stats(e.g. max, min, frequency) 3. plot data (e.g. plot with time, plots subplots, plot with particular projection) I would like to then be able to choose which script for each step and somehow feed the data/variables written in earlier functions through to then be able to run something like: def main(): getdataDJF() calculatemean() plotmean() main() Is this possible? Is this the correct way to do things? My main problem is not being able to feed the output from one function into the next. Thanks Sarah On Mon, Sep 26, 2011 at 10:35 AM, Alan Gauld <alan.gauld at btinternet.com>wrote: > On 26/09/11 00:21, questions anon wrote: > >> Hi All, >> I am trying to move from writing one long script each time I need to do >> a new thing but I do not quite understand how functions work, even after >> reading many manuals. >> > > Can you be more specific about what you dpn;t understand. > > For example can you understand how this function works? > > def square(x): > return x*x > > If not what is the area of difficulty? > > > My first attempt is to create a python file where I have defined a >> number of functions that get data in various ways. >> I have also made another python file where I want to plot the data in >> different ways. but I am having trouble getting that data to run in my >> python plotting file. >> > > It may be easier to keep all the functions in a single file initially. It > just eliminates an extra layer of complexity until we get things working. > Once you know your functions work we can think about moving them into > separate files. > > > I have made the variable I require 'global' but that doesn't seem to be >> working. I keep receiving: >> / >> UnboundLocalError: local variable 'TSFC' referenced before assignment/ >> > > global in Python means global within the current file. It does not mean > across all files. > > > >> Below is a some of the script for both folder, just note that their will >> be many functions in each folder >> > > I'm not sure I understand that bit. So I'll just ignore it for now! :-) > > > > #selectdata.py >> def selectalldata(): >> for (path, dirs, files) in os.walk(MainFolder): >> for dir in dirs: >> print dir >> path=path+'/' >> for ncfile in files: >> if ncfile[-3:]=='.nc': >> print "dealing with ncfiles:", path+ncfile >> ncfile=os.path.join(path,**ncfile) >> ncfile=Dataset(ncfile, 'r+', 'NETCDF4') >> global TSFC >> > > Normally globals are defined at the top of the function. Its not necessary > but its where most readers will look for it. In this case there is no > existing global variable TSFC so it gets created in your module space on the > assignment. > > > > TSFC=ncfile.variables['T_SFC']**[:,:,:] > > I'm not familiar with the [:,:,:] style? What does it do? > Are you sure you want the commas? > > > But since that happens inside an if block, if the block doesn't get > executed the global variable will never get created. Any attempt to access > the variable before the if block is executed will result in your error. > > > LAT=ncfile.variables['**latitude'][:] >> LON=ncfile.variables['**longitude'][:] >> TIME=ncfile.variables['time'][**:] >> fillvalue=ncfile.variables['T_**SFC']._FillValue >> ncfile.close() >> > > And since there are no other functions in this file nobody else can see the > TSFC variable you created. And since the function does not return any data > it will be hard for other modules to use this function. > > > > >> >> #plotdata.py >> >> from selectdata import selectalldata >> selectalldata() >> > > This will (msometimes) create a TSFC variable in the selectdata module, but > you will not be able to access it here because you have not imported > selectdata. If you had you could have done > > TSFC = selectdata.TSFC > > But since you didn't I suspect that > > > def plotncfilewithtime(): >> for TSFC, TIME in zip((TSFC[1::3]),(TIME[1::3]))**: >> > > This will fail when it tries to slice TSFC which it can't see. > Even if it did work it would be bad practice to do this sin e from the next > line onwards the original TSFC would be masked by the new TSFC variable you > are creating. Better to use unique names for the two values. > > > #convert time from numbers to date and prepare it to have no >> symbols for saving to filename >> > .... > I ignored the techie stuff :-) > > > print "end of processing" >> plotncfilewithtime() >> > > Again, this is not the best way to use functions, better to get the > function to return the output to be displayed by the other program. > > HTH, > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor> > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110927/a89d7d49/attachment.html> From d at davea.name Tue Sep 27 02:52:28 2011 From: d at davea.name (Dave Angel) Date: Mon, 26 Sep 2011 20:52:28 -0400 Subject: [Tutor] Funtions, modules & global variables In-Reply-To: <CAN_=ogsPQsfqUDxCRF5qn-p=hYNaTraFBbEn1mEnSZ7=dCDmZg@mail.gmail.com> References: <CAN_=ogse6i=VFYKmN_a-UtbpT9A=BRra26seK11=nE9-GQOk0w@mail.gmail.com> <j5ohd0$sa3$1@dough.gmane.org> <CAN_=ogsPQsfqUDxCRF5qn-p=hYNaTraFBbEn1mEnSZ7=dCDmZg@mail.gmail.com> Message-ID: <4E811E4C.2030109@davea.name> (Don't top-post. Put your new remarks after whatever you're quoting) On 09/26/2011 08:26 PM, questions anon wrote: > Thanks for your feedback. I might be asking the wrong questions. > I have written a number of scripts that do various things for each step: > 1. get data (e.g. Dec-jan-feb, only januarys, all data) > 2. summary stats(e.g. max, min, frequency) > 3. plot data (e.g. plot with time, plots subplots, plot with particular > projection) > > I would like to then be able to choose which script for each step and > somehow feed the data/variables written in earlier functions through to then > be able to run something like: > > def main(): > getdataDJF() > calculatemean() > plotmean() > main() > > Is this possible? Is this the correct way to do things? > My main problem is not being able to feed the output from one function into > the next. > Thanks > Sarah > > If multiple functions need to share data, it should be done by passing parameters, and returning results. If you can understand how to do that within a single source file, you'll be ready to extend the concept to multiple source files. But if you just want to skip to a solution, without worrying about whether it makes sense, read on. You have multiple files, how do they relate to each other? What is the kind of data you're trying to share? I'll make a crazy guess, since you still give no clue. Perhaps each of your multiple files, called external1.py, external2.py defines three functions, called getdataDJF(), calculatemean(), and plotmean(). They're defined as follows: getdataDJF - takes arg1, arg2 and arg3 as parameters, and returns results as (res1, res2) calculatemean - takes arg1 and arg2 as parameters, and returns mydata as result plotmean - takes mydata and device as parameters, and doesn't return anything So your script could do a conditional import to get various implementations of the functions. import sys if (something): from external1 import getdataDJF, calculateman, plotmean else: from external2 import getdataDJF, calculateman, plotmean def main(argv): (res1, res2) = getdataDJF(argv[1], argv[2], argv[3]) buffer = calculatemean(res1, res2) plotmean(buffer, argv[4]) main(sys.argv, "printer") Another approach if this guess is wrong: use classes. Keep all the data as attributes of a class instance, and the methods can share data by stuffing it in those attributes. -- DaveA From bbbgggwww at gmail.com Tue Sep 27 03:32:48 2011 From: bbbgggwww at gmail.com (brandon w) Date: Mon, 26 Sep 2011 21:32:48 -0400 Subject: [Tutor] My code works but it is a little bit broken. In-Reply-To: <j5pbkv$97i$1@dough.gmane.org> References: <CAKXQjyUyQLRSEXm=cs+3+iMa_Tx9TZ3pyX4TwobQsqGAz9KHwQ@mail.gmail.com> <j5pbkv$97i$1@dough.gmane.org> Message-ID: <CAKXQjyWOFNJiuM_cTM9itr-QH45zLcr5t-JBiVPLBtnRoMGLHA@mail.gmail.com> The fields take the initial value and multiply it to get the amount. The problem in in the callback function. It uses the <Enter> event to clear a field, but when the mouse enters a second time it adds a numeric value. This is a semantic error. It is not doing what I want it to do. On Mon, Sep 26, 2011 at 4:03 AM, Alan Gauld <alan.gauld at btinternet.com>wrote: > On 26/09/11 03:25, brandon w wrote: > >> This code calculates money. The problem is that in the first field after >> the mouse enters a second time updates itself with the value from the >> last field. I don't want it to do that. >> I think that the problem is in the "callback" method. >> >> > I haven't gone through this in depth but one thing that > looked odd to me was: > > > def calculateAmount(): >> field1 = varText.get() >> ... >> field2 = varText.get() >> ... >> field3 = varText.get() >> ... >> field4 = varText.get() >> ... >> field5 = varText.get() >> > > Are all fields supposed to be getting the same value? > And if so why not just do it once at the start of the function? > > But as I say I didn't read it all in depth so maybe you > have some magic going on that changes the value between reads... > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor> > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110926/fc607289/attachment-0001.html> From alan.gauld at btinternet.com Tue Sep 27 12:43:09 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 27 Sep 2011 11:43:09 +0100 Subject: [Tutor] My code works but it is a little bit broken. In-Reply-To: <CAKXQjyWOFNJiuM_cTM9itr-QH45zLcr5t-JBiVPLBtnRoMGLHA@mail.gmail.com> References: <CAKXQjyUyQLRSEXm=cs+3+iMa_Tx9TZ3pyX4TwobQsqGAz9KHwQ@mail.gmail.com> <j5pbkv$97i$1@dough.gmane.org> <CAKXQjyWOFNJiuM_cTM9itr-QH45zLcr5t-JBiVPLBtnRoMGLHA@mail.gmail.com> Message-ID: <j5s9bt$602$1@dough.gmane.org> On 27/09/11 02:32, brandon w wrote: > The fields take the initial value and multiply it to get the amount. > The problem in in the callback function. It uses the <Enter> event to > clear a field, but when the mouse enters a second time it adds a numeric > value. This is a semantic error. It is not doing what I want it to do. Here is the callback function: def callback(event): field0 = varText1.get() initAmount.delete(0, END) initAmount.insert(0, field0) return It quite clearly does an insert. If you don't want the insert remove it? I still don't think I understand what your problem is? You read the field and insert it, presumably you did that for a reason, so why are you surprised when it works as you designed it to work? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From waynejwerner at gmail.com Tue Sep 27 13:21:41 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Tue, 27 Sep 2011 06:21:41 -0500 Subject: [Tutor] password loop In-Reply-To: <DUB103-W46AFDAB0C1891553131C5EA90F0@phx.gbl> References: <DUB103-W46AFDAB0C1891553131C5EA90F0@phx.gbl> Message-ID: <CAPM86NeJzUYETKuj_Tcrbu++hNO3L66VbXE+nTYRZ5Y1h_EH2w@mail.gmail.com> On Fri, Sep 23, 2011 at 5:56 PM, ADRIAN KELLY <kellyadrian at hotmail.com>wrote: > Can anyone help me with the programme below; i hope you can see what i am > trying to do, if i enter the wrong password the loop goes on forever and if > i enter the right one nothing is printed... > i am a newbie............all comments welcome > I didn't notice anyone else mention it, but this is where the interactive interpreter really shines, because it allows you to see immediately what the result is: Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> print "hello" hello >>> print "I am your computer" I am your computer >>> password = 'route9999' >>> enter_password = raw_input('Please enter your password: ') Please enter your password: bob Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> print "hello" hello >>> print "I am your computer" I am your computer >>> password = 'route9999' >>> enter_password = raw_input('Please enter your password: ') Please enter your password: bob >>> >From your code and your variable names, it looks like you're confused as to what the statement 'enter_password = raw_input('Enter your password')' does. Because you use the assignment operator (the = sign), the expression on the right (raw_input('Enter your password')) is evaluated, and then the result of that operation is assigned to the enter_password variable. If you use the interactive interpreter you will see that happen immediately, and there's no confusion about exactly what is happening. Whenever I am coding (and most Pythonistas, I suspect) I have two windows open - one containing the code that I'm working on, and another containing an interactive interpreter (I use IPython which is much more powerful than your standard interpreter). This allows me to try out snippets (short pieces) of code, to see what will happen there. It's much quicker to play around in the interpreter and then copy my code into my actual program, than write my code and then test to see if it does what I thought it would do. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110927/a0d585ac/attachment.html> From waynejwerner at gmail.com Tue Sep 27 15:58:19 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Tue, 27 Sep 2011 08:58:19 -0500 Subject: [Tutor] How Python handles data (was guess-my-number programme) Message-ID: <CAPM86NfJgwiGd7T9a+-NWNK871_UVhwz2H_Lq716mK-fbUcKVQ@mail.gmail.com> On Sat, Sep 24, 2011 at 2:58 AM, K?n?thia M?chane < kinuthia.muchane at gmail.com> wrote: > ** > On 09/23/2011 11:28 PM, Wayne Werner wrote: > > <snip> > >>> tries = 1 > >>> tries > 1 > > The variable 'tries' now contains the value 1 (In Python this is not > technically true, but it's useful to describe it that way). > > Why? > Python is a true object-oriented language in that everything in Python is an object. As an aside, one of the great things about Python is that you can program using almost any paradigm and ignore the object-oreintedness. In a language such as C, variables refer to memory locations that you store values in. When you do something like this in C: int x = 0; int y = 0; What you have actually done behind the scenes is allocated two bytes of memory(IIRC that's in the C spec, but I'm not 100% sure that it's guaranteed to be two bytes). Perhaps they are near each other, say at addresses 0xab0fcd and 0xab0fce. And in each of these locations the value of 0 is stored. When you create a variable, memory is allocated, and you refer to that location by the variable name, and that variable name always references that address, at least until it goes out of scope. So if you did something like this: x = 4; y = x; Then x and y contain the same value, but they don't point to the same address. In Python, things are a little bit more ambiguous because everything is an object. So if you do this: x = 4 y = x Then it's /possible/ (not guaranteed) that y and x point to the same memory location. You can test this out by using the 'is' operator, which tells you if the variables reference the same object: >>> x = 4 >>> y = x >>> x is y True But this is not guaranteed behavior - this particular time, python happened to cache the value 4 and set x and y to both reference that location. This is done for optimization, both space and speed, and possibly other reasons I'm not aware of. So instead of saying "I stored the value 4 in x and copied that value into y", the correct statement would be "I gave the value 4 the name of x, and then I also gave it the name of y". The biggest reason that we use the first abstraction, storing a value in a "container" (variable), is that this is the abstraction that you find when talking about almost any other programming language. So whether out of habit, or simply because it will be less confusing to folks who encounter other languages, most Pythonistas will refer to x = 4 as storing 4 in x. Python uses caching for a variety of built-in types, so you can see the 'is' phenomenon on other types as well: >>> x = 'hi' >>> y = x >>> y is x True >>> x = 3.14 >>> y = x >>> x is y True >>> x = 'This is a super long sentence' >>> y = x >>> x is y True >>> y = 'This is a super long sentence' >>> x is y False >>> x == y True >>> x = 'hi' >>> y = 'hi' >>> x is y True >>> y += '!' >>> x is y False >>> x == y False >>> x 'hi' >>> y 'hi!' One thing that is important to note is that in each of these examples, the data types are immutable. In C++ if you have a string and you add to the end of that string, that string is still stored in the same location. In Python there's this magical string space that contains all the possible strings in existence[1] and when you "modify" a string using addition, what you're actually doing is telling the interpreter that you want to point to the string that is the result of addition, like 'hi' + '!'. Sometimes Python stores these as the same object, other times they're stored as different objects. And since you can't change immutable objects in-place (e.g. 'hello'[0] = 'j' raises a TypeError, as does ('hello',)[0] = 'goodbye'), it's just fine to use the standard "store 4 in x" abstraction. But there are also mutable types such as lists and dictionaries that will get you in trouble if you don't understand the difference. Here is an example that has bitten every Python programmer who's been programming long enough: >>> names = ["Werner", "Lancelot", "Bedevere", "Idle", "Chapman"] >>> def add_something(mylist): ... knights = mylist ... for x in range(len(knights)-1): ... knights[x] = "Sir " + knights[x] ... return knights ... >>> knights = add_something(names) >>> knights ['Sir Werner', 'Sir Lancelot', 'Sir Bedevere', 'Sir Idle', 'Chapman'] >>> names ['Sir Werner', 'Sir Lancelot', 'Sir Bedevere', 'Sir Idle', 'Chapman'] And the question is "wait, why did 'names' change??" Because we thought that when we wrote 'knights = mylist' that we were storing a copy of mylist in knights, just like when we ran 'y = x' we stored a copy of 4 in y. But instead what we did was add the name "knights" to the list that was already named by "mylist" and "names". So we can modify the list by using any of those names. Mostly it's nothing to worry about. You will have no problems writing programs in Python if you don't understand the name concept when it comes to immutable types, because the behavior ends out the same from the logic side of things (as long as you compare with == and not 'is', anyway). When it comes to mutable types you need to understand references or you'll have problems. When it comes to numbers and strings (and tuples, AFAIK), I don't know that there is any other need to understand those concepts other than to satisfy your curiosity. If I've made any mistakes, I'm sure others will quickly correct me. HTH, Wayne [1] Not really. It just contains the strings that you have references to, or that have not been garbage collected yet. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110927/711bf6f9/attachment-0001.html> From lina.lastname at gmail.com Tue Sep 27 15:45:00 2011 From: lina.lastname at gmail.com (lina) Date: Tue, 27 Sep 2011 21:45:00 +0800 Subject: [Tutor] map one file and print it out following the sequence Message-ID: <CAG9cJmm7nR-qYR7r8B=6Ea5mRTpm2s+DyOHx-7Kkq8J9LZbvfQ@mail.gmail.com> Hi, I have file 1: cur.itp 1 CH3 1 CUR C1 1 0.066 15.0350 2 OA 1 CUR O1 1 -0.183 15.9994 3 C 1 CUR C2 1 0.126 12.0110 4 CR1 1 CUR C3 1 -0.020 12.0110 5 HC 1 CUR H31 1 0.011 1.0080 6 C 1 CUR C7 2 0.137 12.0110 7 OA 1 CUR O2 2 -0.175 15.9994 8 H 1 CUR H22 2 0.038 1.0080 9 CR1 1 CUR C6 3 -0.025 12.0110 10 HC 1 CUR H61 3 0.009 1.0080 11 CR1 1 CUR C5 3 -0.025 12.0110 12 HC 1 CUR H51 3 0.009 1.0080 13 C 1 CUR C4 3 -0.041 12.0110 14 C 1 CUR C8 3 -0.012 13.0190 15 C 1 CUR C9 3 -0.013 13.0190 16 C 1 CUR C10 3 0.304 12.0110 17 OA 1 CUR O6 3 -0.234 15.9994 18 H 1 CUR H62 3 0.028 1.0080 19 C 1 CUR C11 4 0.000 13.0190 20 C 1 CUR C12 5 0.304 12.0110 21 OA 1 CUR O3 5 -0.234 15.9994 22 H 1 CUR H32 5 0.028 1.0080 23 C 1 CUR C13 5 -0.012 13.0190 24 C 1 CUR C14 5 -0.012 13.0190 25 C 1 CUR C15 5 -0.041 12.0110 26 CR1 1 CUR C20 5 -0.026 12.0110 27 HC 1 CUR H20 5 0.009 1.0080 28 CR1 1 CUR C16 5 -0.025 12.0110 29 HC 1 CUR H16 5 0.009 1.0080 30 CR1 1 CUR C17 6 -0.018 12.0110 31 HC 1 CUR H17 6 0.012 1.0080 32 C 1 CUR C18 6 0.140 12.0110 33 OA 1 CUR O5 6 -0.172 15.9994 34 H 1 CUR H52 6 0.038 1.0080 35 C 1 CUR C19 7 0.123 12.0110 36 OA 1 CUR O4 7 -0.187 15.9994 37 CH3 1 CUR C21 7 0.064 15.0350 and file 2: procesed.pdb ATOM 1 H52 CUR 1 33.502 30.958 -9.831 -0.71 -0.23 H ATOM 2 H32 CUR 1 34.440 28.421 -3.916 0.00 0.09 H ATOM 3 H22 CUR 1 31.110 22.839 1.886 -0.18 0.12 H ATOM 4 H51 CUR 1 29.829 27.375 1.674 -0.21 -0.00 H ATOM 5 H31 CUR 1 33.510 26.681 -0.511 -0.27 -0.02 H ATOM 6 H6 CUR 1 29.459 24.909 1.878 -0.23 -0.01 H ATOM 7 H17 CUR 1 35.217 29.440 -7.832 -0.21 0.01 H ATOM 8 H20 CUR 1 30.338 28.778 -6.812 -0.06 -0.01 H ATOM 9 H16 CUR 1 34.487 28.652 -5.564 -0.18 -0.00 H ATOM 10 C21 CUR 1 30.599 28.677 -10.410 -0.06 -0.05 C ATOM 11 O4 CUR 1 30.948 29.625 -9.382 -0.04 0.04 O ATOM 12 C19 CUR 1 31.790 29.357 -8.323 -0.10 -0.00 C ATOM 13 C20 CUR 1 31.394 28.922 -7.039 -0.06 -0.01 C ATOM 14 C15 CUR 1 32.371 28.675 -6.051 -0.08 0.00 C ATOM 15 C16 CUR 1 33.744 28.855 -6.335 -0.18 -0.00 C ATOM 16 C17 CUR 1 34.160 29.295 -7.609 -0.21 0.01 C ATOM 17 C18 CUR 1 33.174 29.543 -8.587 -0.20 0.02 C ATOM 18 C14 CUR 1 31.931 28.137 -4.836 -0.06 0.00 C ATOM 19 C13 CUR 1 31.827 29.048 -3.599 -0.03 -0.01 C ATOM 20 C12 CUR 1 33.154 29.408 -2.909 -0.04 -0.03 C ATOM 21 O3 CUR 1 34.199 28.542 -2.995 0.00 0.09 O ATOM 22 C11 CUR 1 33.102 30.386 -1.736 -0.14 -0.02 C ATOM 23 C10 CUR 1 31.707 30.606 -1.152 -0.30 -0.04 C ATOM 24 O6 CUR 1 31.139 31.683 -1.277 -0.38 0.05 O ATOM 25 C9 CUR 1 31.046 29.377 -0.519 -0.35 -0.04 C ATOM 26 C8 CUR 1 31.923 28.547 0.425 -0.29 0.01 C ATOM 27 C4 CUR 1 31.681 27.171 0.558 -0.27 0.01 C ATOM 28 C3 CUR 1 32.636 26.289 0.009 -0.27 -0.02 C ATOM 29 C2 CUR 1 32.451 24.894 0.139 -0.24 -0.02 C ATOM 30 C7 CUR 1 31.296 24.423 0.823 -0.22 -0.02 C ATOM 31 C6 CUR 1 30.341 25.296 1.368 -0.23 -0.01 C ATOM 32 C5 CUR 1 30.547 26.678 1.242 -0.21 -0.00 C ATOM 33 O1 CUR 1 33.288 23.913 -0.343 -0.69 0.04 O ATOM 34 C1 CUR 1 34.646 24.135 -0.767 -0.21 -0.06 C ATOM 35 O2 CUR 1 31.119 23.072 0.955 -0.18 0.12 O ATOM 36 O5 CUR 1 33.561 30.000 -9.813 -0.71 -0.23 O Now I wish the file 2 filed 3 output as the order of the file 1 field 2, namely will be, ATOM 10 C21 CUR 1 30.599 28.677 -10.410 -0.06 -0.05 C ATOM 11 O4 CUR 1 30.948 29.625 -9.382 -0.04 0.04 O namely rearrange it. I wrote a failed python script, hope someone can give me some advice, #!/bin/python mapping={} for line in open("cur.itp").readlines(): parts=line.strip().split() if len(parts)==8: mapping[parts[4]]=parts[0] origs=open("processedpdb").read().split() print " ".join([mapping[orig] for orig in origs]) the last sentence I even don't know what I am doing. sorry. -- Best Regards, lina -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110927/b8c8294d/attachment.html> From steve at pearwood.info Tue Sep 27 17:56:48 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 28 Sep 2011 01:56:48 +1000 Subject: [Tutor] How Python handles data (was guess-my-number programme) In-Reply-To: <CAPM86NfJgwiGd7T9a+-NWNK871_UVhwz2H_Lq716mK-fbUcKVQ@mail.gmail.com> References: <CAPM86NfJgwiGd7T9a+-NWNK871_UVhwz2H_Lq716mK-fbUcKVQ@mail.gmail.com> Message-ID: <4E81F240.1090907@pearwood.info> Wayne Werner wrote: > When you do something like this in C: > > int x = 0; > int y = 0; > > What you have actually done behind the scenes is allocated two bytes of > memory(IIRC that's in the C spec, but I'm not 100% sure that it's guaranteed > to be two bytes). Perhaps they are near each other, say at addresses > 0xab0fcd and 0xab0fce. And in each of these locations the value of 0 is > stored. The amount of memory will depend on the type of the variable. In C, you have to declare what type the variable will be. The compiler then knows how much space to allocate for it. > When you create a variable, memory is allocated, and you refer to that > location by the variable name, and that variable name always references that > address, at least until it goes out of scope. So if you did something like > this: > > x = 4; > y = x; > > Then x and y contain the same value, but they don't point to the same > address. Correct, at least for languages like C or Pascal that have the "memory location" model for variables. > In Python, things are a little bit more ambiguous because everything is an > object. So if you do this: No. There is nothing ambiguous about it, it is merely different from C. The rules are completely straightforward and defined exactly. Also, the fact that Python is object oriented is irrelevant to this question. You could have objects stored and referenced at memory locations, like in C, if the language designer wanted it that way. > x = 4 > y = x > > Then it's /possible/ (not guaranteed) that y and x point to the same memory > location. You can test this out by using the 'is' operator, which tells you > if the variables reference the same object: The second half of your sentence is correct, you can test it with the 'is' operator. But the first half is wrong: given the two assignments shown, x=4 and y=x, it *is* guaranteed that x and y will both reference the same object. That is a language promise made by Python: assignment never makes a copy. So if you have x = 4 and then you do y = x the language *promises* that x and y now are names for the same object. That is, "x is y" will return True, or id(x) == id(y). However, what is not promised is the behaviour of this: x = 4 y = 4 In this case, you are doing two separate assignments where the right hand side is given by a literal which merely happens to be the same. The compiler is free to either create two separate objects, both with value 4, or just one. In CPython's case, it reuses some small numbers, but not larger ones: >>> x = 4 >>> y = 4 >>> x is y True >>> x = 40000 >>> y = 40000 >>> x is y False CPython caches the first 100 integers, I believe, although that will depend on exactly which version of CPython you are using. The reason for caching small integers is that it is faster to look them up in the cache than to create a new object each time; but the reason for only caching a handful of them is that the cache uses memory, and you wouldn't want billions of integers being saved for a rainy day. >>>> x = 4 >>>> y = x >>>> x is y > True > > But this is not guaranteed behavior - this particular time, python happened > to cache the value 4 and set x and y to both reference that location. As I've said, this is guaranteed behaviour, but furthermore, you shouldn't think about objects ("variables") in Python having locations. Of course, in reality they do, since it would be impossible -- or at least amazingly difficult -- to design a programming language without the concept of memory location. But as far as *Python* is concerned, rather than the underlying engine that makes Python go, variables don't have locations in an meaningful sense. Think of objects in Python as floating in space, rather than lined up in nice rows with memory addresses. From Python code, you can't tell what address an object is at, and if you can, you can't do anything with the knowledge. Some implementations, such as CPython, expose the address of an object as the id(). But you can't do anything with it, it's just a number. And other implementations, such as Jython and IronPython, don't do that. Every object gets a unique number, starting from 1 and counting up. If an object is deleted, the id doesn't get reused in Jython and IronPython (unlike CPython). Unlike the C "memory address" model, Python's model is of "name binding". Every object can have zero, one, or more names: print [] # Here, the list has no name. x = [] # Here, the list has a single name, "x" x = y = [] # Here, the list has two names, "x" and "y". In practice, Python uses a dictionary to map names to objects. That dictionary is exposed to the user using the function globals(). The main differences between "memory location" variables and "name binding" variables are: (1) Memory locations are known by the compiler at compile-time, but only at run-time for name binding languages. In C-like languages, if I say: x = 42 print x the compiler knows to store 42 into location 123456 (say), and then have the print command look at location 123456. But with name-binding, the compiler doesn't know what location 42 will actually end up at until run-time. It might be anything. (2) Memory location variables must be fixed sizes, while name-binding can allow variables to change size. (3) Memory location variables must copy on assignment: x = 4; y = x makes a copy of x to store in y, since x and y are different variables and therefore different locations. Name-binding though, gives the language designer a choice to copy or not. [...] > One thing that is important to note is that in each of these examples, the > data types are immutable. In C++ if you have a string and you add to the end > of that string, that string is still stored in the same location. In Python > there's this magical string space that contains all the possible strings in > existence[1] and when you "modify" a string using addition, what you're > actually doing is telling the interpreter that you want to point to the > string that is the result of addition, like 'hi' + '!'. Sometimes Python > stores these as the same object, other times they're stored as different > objects. A better way of thinking about this is to say that when you concatenate two strings: a = "hello" b = "world" text = a + b Python will build a new string on the spot and then bind the name text to this new string. The same thing happens even if you concatenate a string to an existing string, like this: text = "hello" text = text + "world" Python looks at the length of the existing two strings: 5 and 5, allocates enough space for 10 letters, then copies letter-by-letter into the new string. However, this can be slow for big strings, so CPython (but not Jython and IronPython) have an optimization that can *sometimes* apply. If there is only one reference to "hello", and you are concatenating to the end, then CPython can sneakily re-use the space already there by expanding the first string, then copying into the end of it. But this is an implementation-dependent trick, and not something you can rely on. -- Steven From illusiontechniques at gmail.com Tue Sep 27 20:32:00 2011 From: illusiontechniques at gmail.com (c smith) Date: Tue, 27 Sep 2011 14:32:00 -0400 Subject: [Tutor] help with a recursive function Message-ID: <CAL2Y8-T8sODACzSzoQqAro0WWyp-9k+atgs1HGS8Fe+R_7kemQ@mail.gmail.com> hi list, i understand the general idea of recursion and if I am following well written code I can understand how it works, but when I try to write it for myself I get a bit confused with the flow. I was trying to turn an ackerman function into python code for practice and I tried writing it like this: #!/usr/bin/env python import sys, os def ack(m,n): if m == 0: return n+1 elif m > 0 and n == 0: ack(m-1,1) elif m > 0 and n > 0: ack(m-1,ack(m,n-1)) if __name__=='__main__': sys.argv[1] = int(sys.argv[1]) sys.argv[2] = int(sys.argv[2]) print ack(sys.argv[1], sys.argv[2]) The major problem, I think, is that I cant figure out where to turn the args into ints. When run in this form I get the 'typeError' error on 'n+1' I guess because the args are still strings. Also, does the second 'elif' make sense? I am not sure if the function can take itself as an argument. thanks for any suggestions, this list has been a big help. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110927/d7c4be45/attachment-0001.html> From alan.gauld at btinternet.com Tue Sep 27 21:08:23 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 27 Sep 2011 20:08:23 +0100 Subject: [Tutor] map one file and print it out following the sequence In-Reply-To: <CAG9cJmm7nR-qYR7r8B=6Ea5mRTpm2s+DyOHx-7Kkq8J9LZbvfQ@mail.gmail.com> References: <CAG9cJmm7nR-qYR7r8B=6Ea5mRTpm2s+DyOHx-7Kkq8J9LZbvfQ@mail.gmail.com> Message-ID: <j5t6v8$5if$1@dough.gmane.org> On 27/09/11 14:45, lina wrote: > Hi, > > I have file 1: cur.itp > > 1 CH3 1 CUR C1 1 0.066 15.0350 > 2 OA 1 CUR O1 1 -0.183 15.9994 > 3 C 1 CUR C2 1 0.126 12.0110 > > and file 2: procesed.pdb > > ATOM 1 H52 CUR 1 33.502 30.958 -9.831 -0.71 > -0.23 H > ATOM 2 H32 CUR 1 34.440 28.421 -3.916 0.00 > 0.09 H > ATOM 3 H22 CUR 1 31.110 22.839 1.886 -0.18 > 0.12 H > While it's good to show us sample data please keep it to the minimum needed to illustrate the point. > Now I wish the file 2 filed 3 output as the order of the file 1 field 2, > namely will be, > ATOM 10 C21 CUR 1 30.599 28.677 -10.410 -0.06 > -0.05 C > ATOM 11 O4 CUR 1 30.948 29.625 -9.382 -0.04 > 0.04 O Sorry, I have no idea what you mean by that. Can you explain again in more detail please? > hope someone can give me some advice, We probably can once we understand what you are trying to do. Or maybe its just me being slow... > origs=open("processedpdb").read().split() > print " ".join([mapping[orig] for orig in origs]) > > the last sentence I even don't know what I am doing. sorry. That makes two of us! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From quasipedia at gmail.com Tue Sep 27 22:22:10 2011 From: quasipedia at gmail.com (Mac Ryan) Date: Tue, 27 Sep 2011 22:22:10 +0200 Subject: [Tutor] help with a recursive function In-Reply-To: <CAL2Y8-T8sODACzSzoQqAro0WWyp-9k+atgs1HGS8Fe+R_7kemQ@mail.gmail.com> References: <CAL2Y8-T8sODACzSzoQqAro0WWyp-9k+atgs1HGS8Fe+R_7kemQ@mail.gmail.com> Message-ID: <20110927222210.65a5b3e4@jabbar> On Tue, 27 Sep 2011 14:32:00 -0400 c smith <illusiontechniques at gmail.com> wrote: > hi list, > i understand the general idea of recursion and if I am following well > written code I can understand how it works, but when I try to write > it for myself I get a bit confused with the flow. > I was trying to turn an ackerman function into python code for > practice and I tried writing it like this: > #!/usr/bin/env python > > import sys, os > def ack(m,n): > > if m == 0: > return n+1 > elif m > 0 and n == 0: > ack(m-1,1) > elif m > 0 and n > 0: > ack(m-1,ack(m,n-1)) > > if __name__=='__main__': > sys.argv[1] = int(sys.argv[1]) > sys.argv[2] = int(sys.argv[2]) > > print ack(sys.argv[1], sys.argv[2]) > > The major problem, I think, is that I cant figure out where to turn > the args into ints. You did it right, just when you loaded them. What is not correct is to try to assign them to a property inside a standard library module. You should assign them to local variables (``m`` and ``n`` for example). > Also, does the second 'elif' make sense? I have am not familiar with the ackerman functions, but since you mentioned recursion, I suppose you wanted to recurse in those elif`s and return the result of a new call to the funtion. If that is the case, you could happily skip the "else" part of "elif" because if the ``if`` code will run, the interpreter will never reach the ``elif`` line. > I am not sure if the function can take itself as an argument. > thanks for any suggestions, this list has been a big help. Here's the code readapted (but verify it still does what is intended to!): #!/usr/bin/env python import sys, os def ack(m,n): if m == 0: return n+1 if m > 0: if n == 0: return ack(m-1,1) if n > 0: return ack(m-1,ack(m,n-1)) raise BaseException('Something is wrong here!') if __name__=='__main__': m = int(sys.argv[1]) n = int(sys.argv[2]) print ack(m, n) HTH! /mac From ramit.prasad at jpmorgan.com Tue Sep 27 23:18:16 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 27 Sep 2011 17:18:16 -0400 Subject: [Tutor] map one file and print it out following the sequence In-Reply-To: <CAG9cJmm7nR-qYR7r8B=6Ea5mRTpm2s+DyOHx-7Kkq8J9LZbvfQ@mail.gmail.com> References: <CAG9cJmm7nR-qYR7r8B=6Ea5mRTpm2s+DyOHx-7Kkq8J9LZbvfQ@mail.gmail.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20D811A3@EMARC112VS01.exchad.jpmchase.net> >I have file 1: cur.itp > >???? 1?????? CH3???? 1? CUR????? C1???? 1??? 0.066? 15.0350?? >???? 2??????? OA???? 1? CUR????? O1???? 1?? -0.183? 15.9994?? >???? 3???????? C???? 1? CUR????? C2???? 1??? 0.126? 12.0110?? >and file 2: procesed.pdb >ATOM????? 1? H52 CUR???? 1????? 33.502? 30.958? -9.831 -0.71 -0.23?????????? H? >ATOM????? 2? H32 CUR???? 1????? 34.440? 28.421? -3.916? 0.00? 0.09?????????? H? >Now I wish the file 2 filed 3 output as the order of the file 1 field 2, >namely will be, >ATOM???? 10? C21 CUR???? 1????? 30.599? 28.677 -10.410 -0.06 -0.05?????????? C? >ATOM???? 11? O4? CUR???? 1????? 30.948? 29.625? -9.382 -0.04? 0.04?????????? O? >mapping={} >for line in open("cur.itp").readlines(): I would also suggest changing the line above to the following lines below. with open("cur.itp") as f: for line in f.readlines(): # do task here. I would do this as it will close the file automatically (starting with Python 2.6?). Not a big deal in this sample program, but I think this is considered a good practice (I am sure people will correct me if I am wrong). >??? parts=line.strip().split() >??? if len(parts)==8: >?????????? mapping[parts[4]]=parts[0] This will create a dictionary of where the key is C2 or O1 or C1 and the value is the line number (or what I assume to be the line number). >origs=open("processedpdb").read().split() >print " ".join([mapping[orig] for orig in origs]) > > the last sentence I even don't know what I am doing. sorry. I can help with that. " " is a string and the join function takes an iterable (like an array or set) and then creates one string with all the elements of the iterable in it but separated by a space. You can use any string for the separator even multi-character ones. >>> print " ".join( [ 'blah' , 'hum', 'bug' , 'see' ] ) blah hum bug see >>> print ",".join( [ 'blah' , 'hum', 'bug' , 'see' ] ) blah,hum,bug,see >>> print ", ".join( [ 'blah' , 'hum', 'bug' , 'see' ] ) blah, hum, bug, see >>> print "a_-_a".join( [ 'blah' , 'hum', 'bug' , 'see' ] ) blaha_-_ahuma_-_abuga_-_asee In your situation this will probably print nothing (actually it should raise a KeyError). >origs=open("processedpdb").read().split() >print " ".join([mapping[orig] for orig in origs]) The reason I do not think this will print anything is because you are searching for the incorrect information in the mapping dictionary. First it will read the entire file and then split the file by lines. So origs will be a list of lines. [mapping[orig] for orig in origs] If done correctly this will generate a list with the results of mapping[orig]. The problem is that you are looking for a key that is "ATOM 1 H52 CUR 1 33.502 30.958 -9.831 -0.71 -0.23 H" but all the keys are in the format "C1" or "C2" or "O1" as mentioned before. Accessing the dictionary in this manner will raise a key error when trying to access a value for which there is no key. >>> d = {} >>> d['blayh'] KeyError: 'blayh' > namely rearrange it. I am not sure what you are trying to do. It would help a lot if you could explain a bit more detail about what you are trying to accomplish. From what I see your output looks to be the same as your file2. Without knowing exactly what you are trying to achieve I cannot really help to fix this, except for pointing out some of the mistakes. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From bbbgggwww at gmail.com Tue Sep 27 23:54:50 2011 From: bbbgggwww at gmail.com (brandon w) Date: Tue, 27 Sep 2011 17:54:50 -0400 Subject: [Tutor] My code works but it is a little bit broken. In-Reply-To: <j5s9bt$602$1@dough.gmane.org> References: <CAKXQjyUyQLRSEXm=cs+3+iMa_Tx9TZ3pyX4TwobQsqGAz9KHwQ@mail.gmail.com> <j5pbkv$97i$1@dough.gmane.org> <CAKXQjyWOFNJiuM_cTM9itr-QH45zLcr5t-JBiVPLBtnRoMGLHA@mail.gmail.com> <j5s9bt$602$1@dough.gmane.org> Message-ID: <CAKXQjyV-=YtEvyvBMSpDCn628vKo_tfA0h3pYBQyA5tUtMCJWg@mail.gmail.com> That was my problem. I had the "insert" function. I don't know why I did not see that before or why I even put that in there. Thank you for your help once again. On Tue, Sep 27, 2011 at 6:43 AM, Alan Gauld <alan.gauld at btinternet.com>wrote: > On 27/09/11 02:32, brandon w wrote: > >> The fields take the initial value and multiply it to get the amount. >> The problem in in the callback function. It uses the <Enter> event to >> clear a field, but when the mouse enters a second time it adds a numeric >> value. This is a semantic error. It is not doing what I want it to do. >> > > Here is the callback function: > > > def callback(event): > field0 = varText1.get() > initAmount.delete(0, END) > initAmount.insert(0, field0) > return > > It quite clearly does an insert. If you don't want the insert remove it? > I still don't think I understand what your problem is? You read the field > and insert it, presumably you did that for a reason, so why are you > surprised when it works as you designed it to work? > > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor> > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110927/707503a1/attachment.html> From steve at pearwood.info Wed Sep 28 01:35:06 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 28 Sep 2011 09:35:06 +1000 Subject: [Tutor] help with a recursive function In-Reply-To: <CAL2Y8-T8sODACzSzoQqAro0WWyp-9k+atgs1HGS8Fe+R_7kemQ@mail.gmail.com> References: <CAL2Y8-T8sODACzSzoQqAro0WWyp-9k+atgs1HGS8Fe+R_7kemQ@mail.gmail.com> Message-ID: <4E825DAA.7030000@pearwood.info> c smith wrote: > hi list, > i understand the general idea of recursion and if I am following well > written code I can understand how it works, but when I try to write it for > myself I get a bit confused with the flow. Your flow is fine. You just forget to return anything in two of the three branches. It's one thing to *call* the recursive function, but you have to do something with the result, normally return it. Otherwise Python just throws the result away and then returns None, exactly the same as this non-recursive function: def add_one(x): """Return x + 1""" y = x + 1 You need a return statement. Further comments below: > I was trying to turn an ackerman function into python code for practice and > I tried writing it like this: > #!/usr/bin/env python > > import sys, os > def ack(m,n): > > if m == 0: > return n+1 > elif m > 0 and n == 0: > ack(m-1,1) > elif m > 0 and n > 0: > ack(m-1,ack(m,n-1)) > > if __name__=='__main__': > sys.argv[1] = int(sys.argv[1]) > sys.argv[2] = int(sys.argv[2]) > > print ack(sys.argv[1], sys.argv[2]) > > The major problem, I think, is that I cant figure out where to turn the args > into ints. (1) That has nothing to do with recursion. (2) Your guess as to the problem is wrong. You are successfully turning the args into ints. (3) In my opinion, it is bad form to write back to sys.argv like that. You should say something like this: m = int(sys.argv[1]) n = int(sys.argv[2]) print ack(m, n) although what you haven't done is strictly *wrong*, it is a bit strange. > When run in this form I get the 'typeError' error on 'n+1' I guess because > the args are still strings. Rather than guess, you should read the error message and pay attention to what it actually says. When I run your code, I get: TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' But if I try to add 1 to a string, I get a very different error message: >>> '2' + 1 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: cannot concatenate 'str' and 'int' objects So the problem is *not* that n is still a string, the problem is that n is NoneType, that is, n = None. Why is n None? Because this branch of the function: ack(m-1,ack(m,n-1)) calls ack with m=m-1 and n=ack(m, n-1) but ack(...) returns None in two out of the three branches. Hence n gets set to None. If you want to understand recursion, you are probably better off starting with simpler examples: start by writing your own recursive factorial function, then Fibonacci, and once you understand them, then try Ackerman. -- Steven From steve at pearwood.info Wed Sep 28 01:58:49 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 28 Sep 2011 09:58:49 +1000 Subject: [Tutor] help with a recursive function In-Reply-To: <20110927222210.65a5b3e4@jabbar> References: <CAL2Y8-T8sODACzSzoQqAro0WWyp-9k+atgs1HGS8Fe+R_7kemQ@mail.gmail.com> <20110927222210.65a5b3e4@jabbar> Message-ID: <4E826339.1050403@pearwood.info> Mac Ryan wrote: > raise BaseException('Something is wrong here!') Never raise BaseException directly! BaseException is the very top of the exception hierarchy, you should raise the *most* specific exception you can, not the least specific. BaseException isn't even just for errors, it's also for flow control exceptions like StopIteration . At worst, you should raise StandardError, but even that is a pretty dodgy thing to do. In general you want something more specific, like ValueError or TypeError. In this particular case, the appropriate error would be to raise RuntimeError: if you're ever in the position of having to just give up and say "I have no idea what is wrong, but something is wrong", then RuntimeError is the one to use. More about exceptions here: http://docs.python.org/library/exceptions.html -- Steven From alan.gauld at btinternet.com Wed Sep 28 03:09:24 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 28 Sep 2011 02:09:24 +0100 Subject: [Tutor] help with a recursive function In-Reply-To: <CAL2Y8-T8sODACzSzoQqAro0WWyp-9k+atgs1HGS8Fe+R_7kemQ@mail.gmail.com> References: <CAL2Y8-T8sODACzSzoQqAro0WWyp-9k+atgs1HGS8Fe+R_7kemQ@mail.gmail.com> Message-ID: <j5ts45$amb$1@dough.gmane.org> On 27/09/11 19:32, c smith wrote: > i understand the general idea of recursion and if I am following well > written code I can understand how it works, but when I try to write it > for myself I get a bit confused with the flow. Others have dealt with the specifics. If you really want to learn how to use and write recursive code there is (IMHO!) no better place to go than the online book How To Design Programs. It's written using Scheme but the code is clear enough that you should translate to Python easily. You probably only need to read the first 4 chapters or so. The author builds up a set of heuristics for defining recursive solutions - i.e. writing functions! http://www.htdp.org Enjoy, Alan G. From questions.anon at gmail.com Wed Sep 28 05:18:13 2011 From: questions.anon at gmail.com (questions anon) Date: Wed, 28 Sep 2011 13:18:13 +1000 Subject: [Tutor] raw_input() slice list Message-ID: <CAN_=ogttfQn82zobRpApShBKstTNUL=vLkD8=B5F9SvGdrOVpA@mail.gmail.com> I would like to use user_input() to decide how to slice a list. This works fine until I try to leave it blank to try and select the whole list [:] I have posted the section of interest below and the error I get when I try to press enter. Further below that is the entire code. Any feedback will be greatly appreciated. * section of code of interest:* startperiod=int(raw_input("Start slice (e.g. 1 ): ")) endperiod=int(raw_input("End slice (e.g. 2): ")) skipperiod=int(raw_input("skip slice (e.g. 1): ")) if startperiod=="" and endperiod=="" and skipperiod=="": startperiod="" endperiod="" skipperiod="" for (path, dirs, files) in os.walk(MainFolder): for dir in dirs: print dir path=path+'/' for ncfile in files: if ncfile[-3:]=='.nc': print "dealing with ncfiles:", path+ncfile ncfile=os.path.join(path,ncfile) ncfile=Dataset(ncfile, 'r+', 'NETCDF4') variable=ncfile.variables[ncvariablename][:] TIME=ncfile.variables['time'][:] fillvalue=ncfile.variables[ncvariablename]._FillValue ncfile.close() for variable, TIME in zip((variable[startperiod:endperiod:skipperiod]),(TIME[startperiod:endperiod:skipperiod])): *the error:* Traceback (most recent call last): File "<pyshell#27>", line 1, in <module> plotrawdata('TSFC') File "D:\My Dropbox\Python_code\functions.py", line 39, in plotrawdata startperiod=int(raw_input("Start slice (e.g. 1 ): ")) ValueError: invalid literal for int() with base 10: '' *THE WHOLE PROGRAM:* from netCDF4 import Dataset import numpy as N import matplotlib.pyplot as plt from numpy import ma as MA from mpl_toolkits.basemap import Basemap from netcdftime import utime from datetime import datetime import os import matplotlib.colors as mc import matplotlib.colorbar as c OutputFolder=r"D:/DSE_work/temp_samples2/" MainFolder=r"D:/DSE_work/temp_samples2/" def plotrawdata(variable): if variable=='TSFC': ncvariablename='T_SFC' MainFolder=r"D:/DSE_work/temp_samples2/" ticks=[-5,0,5,10,15,20,25,30,35,40,45,50] Title='Surface Temperature' elif variable=='RHSFC': ncvariablename='RH_SFC' MainFolder=r"E:/DSE_BushfireClimatologyProject/griddeddatasamples/temp_samples6/" ticks=[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 101] Title='Surface RH' fileforlatlon=Dataset("D:/DSE_work/temp_samples2/2020/01/IDZ00026_VIC_ADFD_T_SFC.nc", 'r+', 'NETCDF4') LAT=fileforlatlon.variables['latitude'][:] LON=fileforlatlon.variables['longitude'][:] startperiod=int(raw_input("Start slice (e.g. 1 ): ")) endperiod=int(raw_input("End slice (e.g. 2): ")) skipperiod=int(raw_input("skip slice (e.g. 1): ")) if startperiod=="" and endperiod=="" and skipperiod=="": startperiod=str("") endperiod=str("") skipperiod=str("") for (path, dirs, files) in os.walk(MainFolder): for dir in dirs: print dir path=path+'/' for ncfile in files: if ncfile[-3:]=='.nc': print "dealing with ncfiles:", path+ncfile ncfile=os.path.join(path,ncfile) ncfile=Dataset(ncfile, 'r+', 'NETCDF4') variable=ncfile.variables[ncvariablename][:] TIME=ncfile.variables['time'][:] fillvalue=ncfile.variables[ncvariablename]._FillValue ncfile.close() for variable, TIME in zip((variable[startperiod:endperiod:skipperiod]),(TIME[startperiod:endperiod:skipperiod])): #for variable, TIME in zip((variable[sliceperiod]),(TIME[sliceperiod])): cdftime=utime('seconds since 1970-01-01 00:00:00') ncfiletime=cdftime.num2date(TIME) print ncfiletime timestr=str(ncfiletime) d = datetime.strptime(timestr, '%Y-%m-%d %H:%M:%S') date_string = d.strftime('%Y%m%d_%H%M') #Set up basemap using mercator projection http://matplotlib.sourceforge.net/basemap/doc/html/users/merc.html map = Basemap(projection='merc',llcrnrlat=-40,urcrnrlat=-33, llcrnrlon=139.0,urcrnrlon=151.0,lat_ts=0,resolution='i') x,y=map(*N.meshgrid(LON,LAT)) map.drawcoastlines(linewidth=0.5) #map.readshapefile(shapefile1, 'DSE_REGIONS') map.drawstates() plt.title(Title+' %s UTC'%ncfiletime) CS = map.contourf(x,y,variable, ticks, cmap=plt.cm.jet) l,b,w,h =0.1,0.1,0.8,0.8 cax = plt.axes([l+w+0.025, b, 0.025, h], ) cbar=plt.colorbar(CS, cax=cax, drawedges=True) #save map as *.png and plot netcdf file plt.savefig((os.path.join(OutputFolder, ncvariablename+date_string+'UTC.png'))) plt.show() plt.close() # must use plt.close() so that colorbar works! -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110928/6a8b88a2/attachment.html> From lina.lastname at gmail.com Wed Sep 28 05:34:46 2011 From: lina.lastname at gmail.com (lina) Date: Wed, 28 Sep 2011 11:34:46 +0800 Subject: [Tutor] map one file and print it out following the sequence In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20D811A3@EMARC112VS01.exchad.jpmchase.net> References: <CAG9cJmm7nR-qYR7r8B=6Ea5mRTpm2s+DyOHx-7Kkq8J9LZbvfQ@mail.gmail.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20D811A3@EMARC112VS01.exchad.jpmchase.net> Message-ID: <CAG9cJmkJX_b3NN2XvuBNfagUzaF+AS-Z3ULkR3nYyAi8Ob-frw@mail.gmail.com> Hi, Thanks for both of your reply. File 1 is: 3 C 1 CUR C19 1 0.200 12.0110 4 CR1 1 CUR C20 1 -0.060 12.0110 5 HC 1 CUR H20 1 0.060 1.0080 File 2 is: ATOM 2 H20 CUR 1 30.338 28.778 -6.812 1.00 0.00 ATOM 4 C20 CUR 1 31.394 28.922 -7.039 1.00 0.00 ATOM 5 C19 CUR 1 31.790 29.357 -8.323 1.00 0.00 I wish to get: ATOM 5 C19 CUR 1 31.790 29.357 -8.323 1.00 0.00 ATOM 4 C20 CUR 1 31.394 28.922 -7.039 1.00 0.00 ATOM 2 H20 CUR 1 30.338 28.778 -6.812 1.00 0.00 The dictionary is C19 C20 H20 sequence read from file 1 field 5. rearrange the file 2 field 3 following the sequence of C19, C20, H20. Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110928/db21dc14/attachment-0001.html> From bgailer at gmail.com Wed Sep 28 08:13:20 2011 From: bgailer at gmail.com (bob gailer) Date: Wed, 28 Sep 2011 02:13:20 -0400 Subject: [Tutor] raw_input() slice list In-Reply-To: <CAN_=ogttfQn82zobRpApShBKstTNUL=vLkD8=B5F9SvGdrOVpA@mail.gmail.com> References: <CAN_=ogttfQn82zobRpApShBKstTNUL=vLkD8=B5F9SvGdrOVpA@mail.gmail.com> Message-ID: <4E82BB00.1040509@gmail.com> On 9/27/2011 11:18 PM, questions anon wrote: > I would like to use user_input() to decide how to slice a list. > This works fine until I try to leave it blank to try and select the > whole list [:] > I have posted the section of interest below and the error I get when I > try to press enter. Further below that is the entire code. > Any feedback will be greatly appreciated. > * > section of code of interest:* > startperiod=int(raw_input("Start slice (e.g. 1 ): ")) > endperiod=int(raw_input("End slice (e.g. 2): ")) > skipperiod=int(raw_input("skip slice (e.g. 1): ")) > > if startperiod=="" and endperiod=="" and skipperiod=="": > startperiod="" > endperiod="" > skipperiod="" > int() expects a character representation of an integer. An empty string will raise the exception you reported. startperiod will NEVER == "", as it will be an integer. The entire if statement does nothing! Discard it. Defer applying int(). Then you can check startperiod etc for equality to "". if startperiod == "": startperiod = None else: startperiod = int(startperiod) if endperiod == "": endperiod = None else: endperiod = int(endperiod) if skipperiod == "": skipperiod = None else: skipperiod= int(skipperiod) AND BE PREPARED to catch & handle exceptions in case user enters a non-integer value. > > for (path, dirs, files) in os.walk(MainFolder): > for dir in dirs: > print dir > path=path+'/' > > for ncfile in files: > if ncfile[-3:]=='.nc': > print "dealing with ncfiles:", > path+ncfile > ncfile=os.path.join(path,ncfile) > ncfile=Dataset(ncfile, 'r+', > 'NETCDF4') > > variable=ncfile.variables[ncvariablename][:] > TIME=ncfile.variables['time'][:] > > fillvalue=ncfile.variables[ncvariablename]._FillValue > ncfile.close() > > for variable, TIME in > zip((variable[startperiod:endperiod:skipperiod]),(TIME[startperiod:endperiod:skipperiod])): > > > *the error:* > > Traceback (most recent call last): > File "<pyshell#27>", line 1, in <module> > plotrawdata('TSFC') > File "D:\My Dropbox\Python_code\functions.py", line 39, in plotrawdata > startperiod=int(raw_input("Start slice (e.g. 1 ): ")) > ValueError: invalid literal for int() with base 10: '' > > > *THE WHOLE PROGRAM:* > from netCDF4 import Dataset > import numpy as N > import matplotlib.pyplot as plt > from numpy import ma as MA > from mpl_toolkits.basemap import Basemap > from netcdftime import utime > from datetime import datetime > import os > import matplotlib.colors as mc > import matplotlib.colorbar as c > > OutputFolder=r"D:/DSE_work/temp_samples2/" > MainFolder=r"D:/DSE_work/temp_samples2/" > > > def plotrawdata(variable): > if variable=='TSFC': > ncvariablename='T_SFC' > MainFolder=r"D:/DSE_work/temp_samples2/" > ticks=[-5,0,5,10,15,20,25,30,35,40,45,50] > Title='Surface Temperature' > > elif variable=='RHSFC': > ncvariablename='RH_SFC' > > MainFolder=r"E:/DSE_BushfireClimatologyProject/griddeddatasamples/temp_samples6/" > ticks=[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 101] > Title='Surface RH' > > > fileforlatlon=Dataset("D:/DSE_work/temp_samples2/2020/01/IDZ00026_VIC_ADFD_T_SFC.nc", > 'r+', 'NETCDF4') > LAT=fileforlatlon.variables['latitude'][:] > LON=fileforlatlon.variables['longitude'][:] > > startperiod=int(raw_input("Start slice (e.g. 1 ): ")) > endperiod=int(raw_input("End slice (e.g. 2): ")) > skipperiod=int(raw_input("skip slice (e.g. 1): ")) > > if startperiod=="" and endperiod=="" and skipperiod=="": > startperiod=str("") > endperiod=str("") > skipperiod=str("") > > > for (path, dirs, files) in os.walk(MainFolder): > for dir in dirs: > print dir > path=path+'/' > > for ncfile in files: > if ncfile[-3:]=='.nc': > print "dealing with ncfiles:", > path+ncfile > ncfile=os.path.join(path,ncfile) > ncfile=Dataset(ncfile, 'r+', > 'NETCDF4') > > variable=ncfile.variables[ncvariablename][:] > TIME=ncfile.variables['time'][:] > > fillvalue=ncfile.variables[ncvariablename]._FillValue > ncfile.close() > > for variable, TIME in > zip((variable[startperiod:endperiod:skipperiod]),(TIME[startperiod:endperiod:skipperiod])): > #for variable, TIME in > zip((variable[sliceperiod]),(TIME[sliceperiod])): > > cdftime=utime('seconds > since 1970-01-01 00:00:00') > > ncfiletime=cdftime.num2date(TIME) > print ncfiletime > timestr=str(ncfiletime) > d = > datetime.strptime(timestr, '%Y-%m-%d %H:%M:%S') > date_string = > d.strftime('%Y%m%d_%H%M') > #Set up basemap using > mercator projection > http://matplotlib.sourceforge.net/basemap/doc/html/users/merc.html > map = > Basemap(projection='merc',llcrnrlat=-40,urcrnrlat=-33, > > llcrnrlon=139.0,urcrnrlon=151.0,lat_ts=0,resolution='i') > x,y=map(*N.meshgrid(LON,LAT)) > > map.drawcoastlines(linewidth=0.5) > > #map.readshapefile(shapefile1, 'DSE_REGIONS') > map.drawstates() > > plt.title(Title+' %s > UTC'%ncfiletime) > > CS = > map.contourf(x,y,variable, ticks, cmap=plt.cm.jet) > l,b,w,h =0.1,0.1,0.8,0.8 > cax = plt.axes([l+w+0.025, > b, 0.025, h], ) > cbar=plt.colorbar(CS, > cax=cax, drawedges=True) > > #save map as *.png and > plot netcdf file > > plt.savefig((os.path.join(OutputFolder, > ncvariablename+date_string+'UTC.png'))) > plt.show() > plt.close() # must use > plt.close() so that colorbar works! > > > > > > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110928/87de9954/attachment-0001.html> From quasipedia at gmail.com Wed Sep 28 08:33:37 2011 From: quasipedia at gmail.com (Mac Ryan) Date: Wed, 28 Sep 2011 08:33:37 +0200 Subject: [Tutor] Why subclassing exceptions? In-Reply-To: <4E826339.1050403@pearwood.info> References: <CAL2Y8-T8sODACzSzoQqAro0WWyp-9k+atgs1HGS8Fe+R_7kemQ@mail.gmail.com> <20110927222210.65a5b3e4@jabbar> <4E826339.1050403@pearwood.info> Message-ID: <20110928083337.462d24b8@jabbar> On Wed, 28 Sep 2011 09:58:49 +1000 Steven D'Aprano <steve at pearwood.info> wrote: > Mac Ryan wrote: > > > raise BaseException('Something is wrong here!') > > Never raise BaseException directly! BaseException is the very top of > the exception hierarchy, you should raise the *most* specific > exception you can, not the least specific. BaseException isn't even > just for errors, it's also for flow control exceptions like > StopIteration . Fair enough! :) I just put that line to signal that there were cases that weren't catch by the series of ``if``, but nevertheless you are right. **I would like to know more on the rationale behind this guidelines, though.** I explain: I already knew before that I should subclass exceptions, nevertheless I very seldom do, as I feel like they are just taking space on my screen doing nothing useful. All I need to do is often just print out a useful message, so I find that >>> raise StandardError('This value should be True.') does the job in a much more elegant way than: >>> class ShouldBeTrueError(StandardError): ... ... ''' ... Custom Error triggered in case a value should be True. ... ''' ... ... pass ... >>> raise ShouldBeTrueError('Doh! An error!') Ok, I already hear some of you screaming out loud "Anathema!!" ;) ...yet could somebody please clarify why should I bother subclassing? [I'm positive there is a good reason, but in all honesty I can't imagine which one...]. Thanks, /mac From questions.anon at gmail.com Wed Sep 28 09:58:19 2011 From: questions.anon at gmail.com (questions anon) Date: Wed, 28 Sep 2011 17:58:19 +1000 Subject: [Tutor] raw_input() slice list In-Reply-To: <4E82BB00.1040509@gmail.com> References: <CAN_=ogttfQn82zobRpApShBKstTNUL=vLkD8=B5F9SvGdrOVpA@mail.gmail.com> <4E82BB00.1040509@gmail.com> Message-ID: <CAN_=oguP=womZ2dKrJcJmxKMBO+AxBjCSbSWmixs6iVZ-cxpSA@mail.gmail.com> Excellent, thank you and yes I need to work on how to catch and handle exceptions Thanks again! On Wed, Sep 28, 2011 at 4:13 PM, bob gailer <bgailer at gmail.com> wrote: > On 9/27/2011 11:18 PM, questions anon wrote: > > I would like to use user_input() to decide how to slice a list. > This works fine until I try to leave it blank to try and select the whole > list [:] > I have posted the section of interest below and the error I get when I try > to press enter. Further below that is the entire code. > Any feedback will be greatly appreciated. > * > section of code of interest:* > startperiod=int(raw_input("Start slice (e.g. 1 ): ")) > endperiod=int(raw_input("End slice (e.g. 2): ")) > skipperiod=int(raw_input("skip slice (e.g. 1): ")) > > if startperiod=="" and endperiod=="" and skipperiod=="": > startperiod="" > endperiod="" > skipperiod="" > > > int() expects a character representation of an integer. An empty string > will raise the exception you reported. > > startperiod will NEVER == "", as it will be an integer. > > The entire if statement does nothing! Discard it. > > Defer applying int(). > > Then you can check startperiod etc for equality to "". > > if startperiod == "": > startperiod = None > else: > startperiod = int(startperiod) > if endperiod == "": > > endperiod = None > else: > endperiod = int(endperiod) > if skipperiod == "": > skipperiod = None > else: > skipperiod= int(skipperiod) > > AND BE PREPARED to catch & handle exceptions in case user enters a > non-integer value. > > > for (path, dirs, files) in os.walk(MainFolder): > for dir in dirs: > print dir > path=path+'/' > > for ncfile in files: > if ncfile[-3:]=='.nc': > print "dealing with ncfiles:", > path+ncfile > ncfile=os.path.join(path,ncfile) > ncfile=Dataset(ncfile, 'r+', 'NETCDF4') > > variable=ncfile.variables[ncvariablename][:] > TIME=ncfile.variables['time'][:] > > fillvalue=ncfile.variables[ncvariablename]._FillValue > ncfile.close() > > for variable, TIME in > zip((variable[startperiod:endperiod:skipperiod]),(TIME[startperiod:endperiod:skipperiod])): > > > *the error:* > > Traceback (most recent call last): > File "<pyshell#27>", line 1, in <module> > plotrawdata('TSFC') > File "D:\My Dropbox\Python_code\functions.py", line 39, in plotrawdata > startperiod=int(raw_input("Start slice (e.g. 1 ): ")) > ValueError: invalid literal for int() with base 10: '' > > > *THE WHOLE PROGRAM:* > from netCDF4 import Dataset > import numpy as N > import matplotlib.pyplot as plt > from numpy import ma as MA > from mpl_toolkits.basemap import Basemap > from netcdftime import utime > from datetime import datetime > import os > import matplotlib.colors as mc > import matplotlib.colorbar as c > > OutputFolder=r"D:/DSE_work/temp_samples2/" > MainFolder=r"D:/DSE_work/temp_samples2/" > > > def plotrawdata(variable): > if variable=='TSFC': > ncvariablename='T_SFC' > MainFolder=r"D:/DSE_work/temp_samples2/" > ticks=[-5,0,5,10,15,20,25,30,35,40,45,50] > Title='Surface Temperature' > > elif variable=='RHSFC': > ncvariablename='RH_SFC' > > MainFolder=r"E:/DSE_BushfireClimatologyProject/griddeddatasamples/temp_samples6/" > ticks=[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 101] > Title='Surface RH' > > > fileforlatlon=Dataset("D:/DSE_work/temp_samples2/2020/01/IDZ00026_VIC_ADFD_T_SFC.nc", > 'r+', 'NETCDF4') > LAT=fileforlatlon.variables['latitude'][:] > LON=fileforlatlon.variables['longitude'][:] > > startperiod=int(raw_input("Start slice (e.g. 1 ): ")) > endperiod=int(raw_input("End slice (e.g. 2): ")) > skipperiod=int(raw_input("skip slice (e.g. 1): ")) > > if startperiod=="" and endperiod=="" and skipperiod=="": > startperiod=str("") > endperiod=str("") > skipperiod=str("") > > > for (path, dirs, files) in os.walk(MainFolder): > for dir in dirs: > print dir > path=path+'/' > > for ncfile in files: > if ncfile[-3:]=='.nc': > print "dealing with ncfiles:", > path+ncfile > ncfile=os.path.join(path,ncfile) > ncfile=Dataset(ncfile, 'r+', 'NETCDF4') > > variable=ncfile.variables[ncvariablename][:] > TIME=ncfile.variables['time'][:] > > fillvalue=ncfile.variables[ncvariablename]._FillValue > ncfile.close() > > for variable, TIME in > zip((variable[startperiod:endperiod:skipperiod]),(TIME[startperiod:endperiod:skipperiod])): > #for variable, TIME in > zip((variable[sliceperiod]),(TIME[sliceperiod])): > > cdftime=utime('seconds since > 1970-01-01 00:00:00') > > ncfiletime=cdftime.num2date(TIME) > print ncfiletime > timestr=str(ncfiletime) > d = datetime.strptime(timestr, > '%Y-%m-%d %H:%M:%S') > date_string = > d.strftime('%Y%m%d_%H%M') > #Set up basemap using mercator > projection > http://matplotlib.sourceforge.net/basemap/doc/html/users/merc.html > map = > Basemap(projection='merc',llcrnrlat=-40,urcrnrlat=-33, > > llcrnrlon=139.0,urcrnrlon=151.0,lat_ts=0,resolution='i') > x,y=map(*N.meshgrid(LON,LAT)) > > map.drawcoastlines(linewidth=0.5) > #map.readshapefile(shapefile1, > 'DSE_REGIONS') > map.drawstates() > > plt.title(Title+' %s > UTC'%ncfiletime) > > CS = map.contourf(x,y,variable, > ticks, cmap=plt.cm.jet) > l,b,w,h =0.1,0.1,0.8,0.8 > cax = plt.axes([l+w+0.025, b, > 0.025, h], ) > cbar=plt.colorbar(CS, cax=cax, > drawedges=True) > > #save map as *.png and plot > netcdf file > > plt.savefig((os.path.join(OutputFolder, > ncvariablename+date_string+'UTC.png'))) > plt.show() > plt.close() # must use > plt.close() so that colorbar works! > > > > > > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options:http://mail.python.org/mailman/listinfo/tutor > > > > -- > Bob Gailer919-636-4239 > Chapel Hill NC > > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110928/f226bd21/attachment-0001.html> From alan.gauld at btinternet.com Wed Sep 28 10:03:11 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 28 Sep 2011 09:03:11 +0100 Subject: [Tutor] Why subclassing exceptions? In-Reply-To: <20110928083337.462d24b8@jabbar> References: <CAL2Y8-T8sODACzSzoQqAro0WWyp-9k+atgs1HGS8Fe+R_7kemQ@mail.gmail.com> <20110927222210.65a5b3e4@jabbar> <4E826339.1050403@pearwood.info> <20110928083337.462d24b8@jabbar> Message-ID: <j5ukbv$odr$1@dough.gmane.org> On 28/09/11 07:33, Mac Ryan wrote: >>> raise BaseException('Something is wrong here!') >> >> Never raise BaseException directly! > **I would like to know more on the rationale behind this > guidelines, though.** > >>>> raise StandardError('This value should be True.') > > does the job in a much more elegant way than: > >>>> class ShouldBeTrueError(StandardError): > ... >>>> raise ShouldBeTrueError('Doh! An error!') Can you explain why you think that is "more elegant"? To me it looks ugly. If there are multiple errors I need to open up the exception and test against the message string (with all the dangers of mis-spelling etc) Compare: try: someFuncWithMultipleExceptions() except StandardError, e: if e.message == "This value should be True": makeItTrue() elif e.message == "This value should be black": makeItBlack() except ValueError: var = raw_input("oops, that's an invalid value, try again") With try: someFuncWithMultipleExceptions() except ShouldBeTrueError: makeItTrue() except ShouldBeBlackError: makeItBlack() except ValueError() var = raw_input("oops, that's an invalid value, try again") The second form is more precise, more robust, and consistent with the built in exception handling. Remember that when handling exceptions we should be trying to recover the situation not just bombing with an error message. Exceptions should not be thought of as purely about messages, they are opportunities to recover the situation without the user even being aware that something went wrong. Only when recovery is impossible should we bomb out with a message. Otherwise you might as well do it this way: if errorDetected: print "It's all gone terribly wrong" raise SystemExit -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Sep 28 10:15:40 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 28 Sep 2011 09:15:40 +0100 Subject: [Tutor] map one file and print it out following the sequence In-Reply-To: <CAG9cJmkJX_b3NN2XvuBNfagUzaF+AS-Z3ULkR3nYyAi8Ob-frw@mail.gmail.com> References: <CAG9cJmm7nR-qYR7r8B=6Ea5mRTpm2s+DyOHx-7Kkq8J9LZbvfQ@mail.gmail.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20D811A3@EMARC112VS01.exchad.jpmchase.net> <CAG9cJmkJX_b3NN2XvuBNfagUzaF+AS-Z3ULkR3nYyAi8Ob-frw@mail.gmail.com> Message-ID: <j5ul3c$t3q$1@dough.gmane.org> On 28/09/11 04:34, lina wrote: > File 1 is: > > 3 C 1 CUR C19 1 0.200 12.0110 > 4 CR1 1 CUR C20 1 -0.060 12.0110 > 5 HC 1 CUR H20 1 0.060 1.0080 > > File 2 is: > ATOM 2 H20 CUR 1 30.338 28.778 -6.812 1.00 0.00 > ATOM 4 C20 CUR 1 31.394 28.922 -7.039 1.00 0.00 > ATOM 5 C19 CUR 1 31.790 29.357 -8.323 1.00 0.00 > > I wish to get: > > ATOM 5 C19 CUR 1 31.790 29.357 -8.323 1.00 0.00 > ATOM 4 C20 CUR 1 31.394 28.922 -7.039 1.00 0.00 > ATOM 2 H20 CUR 1 30.338 28.778 -6.812 1.00 0.00 > > The dictionary is C19 C20 H20 sequence read from file 1 field 5. > rearrange the file 2 field 3 following the sequence of C19, C20, H20. OK, so just to confirm: you want to sort file 2 based on the order of field 5 in file 1. So read file2 into a dictionary keyed by field 3 Then read file 1 and output the dictionary entry associated with field 5 So in pseudo code: d = dict() for line in file1: d[ line.split()[2] ] = line for line in file1: print d[ line.split()[4] ] Is that what you want? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From quasipedia at gmail.com Wed Sep 28 11:23:28 2011 From: quasipedia at gmail.com (Mac Ryan) Date: Wed, 28 Sep 2011 11:23:28 +0200 Subject: [Tutor] Why subclassing exceptions? In-Reply-To: <j5ukbv$odr$1@dough.gmane.org> References: <CAL2Y8-T8sODACzSzoQqAro0WWyp-9k+atgs1HGS8Fe+R_7kemQ@mail.gmail.com> <20110927222210.65a5b3e4@jabbar> <4E826339.1050403@pearwood.info> <20110928083337.462d24b8@jabbar> <j5ukbv$odr$1@dough.gmane.org> Message-ID: <20110928112328.2520aa92@jabbar> On Wed, 28 Sep 2011 09:03:11 +0100 Alan Gauld <alan.gauld at btinternet.com> wrote: > Remember that when handling exceptions we should be trying > to recover the situation not just bombing with an error message. > Exceptions should not be thought of as purely about > messages, they are opportunities to recover the situation without the > user even being aware that something went wrong. Only when recovery > is impossible should we bomb out with a message. Thank you Alan for the quick response. I totally see your logic, and surely I can't (nor I wish to) argue with it in the context you illustrated. I have to say - however - that even after a few years of python development I seldom use exceptions that way: in fact I can only remember having subclassed error classes once, when I wrote a library that was intended to be used by third-parties (for the exact same reasons that you exemplified). In all other cases (code that doesn't expose an API to third parties) I consider that either my program works (and thus it can handle all possible situations) or it does not, in which case - given that nothing should silently fail - I'm happy for it to scream out loud with a raise BaseException('<useful-debug-message-here>'). In fact, I use exceptions only when I can't write an ``assert`` statement concise enough. In the original code to which you initially reacted I used an exception simply because it was more concise to put it under the else clause rather then writing an ``assert`` statement with all the if/else possibility it would have needed. Is there any reason for which you (or anybody on the list, of course) think I should avoid doing this? /mac From alan.gauld at btinternet.com Wed Sep 28 12:24:00 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 28 Sep 2011 11:24:00 +0100 Subject: [Tutor] Why subclassing exceptions? In-Reply-To: <20110928112328.2520aa92@jabbar> References: <CAL2Y8-T8sODACzSzoQqAro0WWyp-9k+atgs1HGS8Fe+R_7kemQ@mail.gmail.com> <20110927222210.65a5b3e4@jabbar> <4E826339.1050403@pearwood.info> <20110928083337.462d24b8@jabbar> <j5ukbv$odr$1@dough.gmane.org> <20110928112328.2520aa92@jabbar> Message-ID: <j5usk0$gip$1@dough.gmane.org> On 28/09/11 10:23, Mac Ryan wrote: > I have to say - however - that even after a few years of python > development I seldom use exceptions that way: in fact I can only > remember having subclassed error classes once, when I wrote a library > that was intended to be used by third-parties (for the exact same > reasons that you exemplified). That doesn't make it good :-) You can write a lot of code without using functions or classes or exceptions. But it doesn't mean it couldn't be improved by adding those features. > In all other cases (code that doesn't expose an API to third parties) > I consider that either my program works (and thus it can handle all > possible situations) or it does not, in which case - given that nothing > should silently fail - I'm happy for it to scream out loud with a raise > BaseException('<useful-debug-message-here>'). If all you can do is scream out then raising an exception is mostly a waste of space. Exceptions are there to be caught and handled. Error messages are where we should scream out, not the exceptions themselves. > In fact, I use exceptions only when I can't write an ``assert`` But asserts should be used in debugging only. They are dangerous things to rely on in production code. Unless you are using assert in a wider context than literal assert() calls? > > reacted I used an exception simply because it was more concise to put > it under the else clause rather then writing an ``assert`` statement > with all the if/else possibility it would have needed. Using asserts is a form of the if/else type error handling that plagued programmers during the 70's,80's and even into the 90's (thanks Microsoft!) and which try/except style exceptions were, in part, designed to eliminate. The problem with "assert" and if/else style checking is it greatly complexifies the code structure and makes it much harder to see the "happy path" flow. Exceptions allow us to code in the same way we write use cases during analysis: Precondition check happy path sequence exception cases postcondition check That makes for more readable and therefore more maintainable code. It also means we can add new exception handlers as needed without interfering with the core algorithm structure. (It also means the core algorithm can be optimised for speed without all the explicit if/else checks going on, but that should be considered a free bonus not a reason to adopt exceptions!) And finally, as you suggest, when code gets reused (and often that happens to code we didn't expect to reuse!) exceptions make for an easier and more consistent interface for the reuser (who may be yourself!) > Is there any reason for which you (or anybody on the list, of course) > think I should avoid doing this? It's perfectly possible to write code the way you are doing but it involves multiple error mechanisms (because the standard library uses exceptions) and is less familiar to other programmers. If its only for your own use then its a moot point, it really becomes significant when working on collaborative projects or for reuse. OTOH writing with exceptions takes very few extra keystrokes so why not just use as intended? ;-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Wed Sep 28 16:08:15 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 29 Sep 2011 00:08:15 +1000 Subject: [Tutor] Why subclassing exceptions? In-Reply-To: <20110928112328.2520aa92@jabbar> References: <CAL2Y8-T8sODACzSzoQqAro0WWyp-9k+atgs1HGS8Fe+R_7kemQ@mail.gmail.com> <20110927222210.65a5b3e4@jabbar> <4E826339.1050403@pearwood.info> <20110928083337.462d24b8@jabbar> <j5ukbv$odr$1@dough.gmane.org> <20110928112328.2520aa92@jabbar> Message-ID: <4E832A4F.9080203@pearwood.info> Mac Ryan wrote: > I have to say - however - that even after a few years of python > development I seldom use exceptions that way: in fact I can only > remember having subclassed error classes once, when I wrote a library > that was intended to be used by third-parties (for the exact same > reasons that you exemplified). You don't have to subclass exceptions. You can raise exception classes that already exist. Most of the time, that's exactly what you should do. > In all other cases (code that doesn't expose an API to third parties) > I consider that either my program works (and thus it can handle all > possible situations) or it does not, in which case - given that nothing If your program can handle ALL possible situations, that would be a first for any program written in any language in the entire history of computing. Well done! <wink> > should silently fail - I'm happy for it to scream out loud with a raise > BaseException('<useful-debug-message-here>'). Well here's the thing. It's your program, you can make it do anything you like. If you want it to raise TooMuchCoffee exceptions, go right ahead. But there are standard meanings for exceptions in Python, and you are ignoring them. The error message gives you a human readable message. The exception type tells you the category of error. You are ignoring or abusing that information channel by mis-using BaseException. Regardless of whether the exception gets caught or not, the exception type gives the user valuable information. Think of it this way: exceptions are like a great big control panel with warning lights. There's a warning light for "fuel warnings", another one for "temperature warnings", a third for "did you remember to lock the front door when you left home", and so forth. Each light can blink in a pattern, which a human being can look up in the manual to see exactly what sort of fuel warning: "no fuel in engine 3", say. But even without reading the detailed message (which sometimes can be fairly cryptic), the mere fact that it's a fuel warning gives you a lot of useful information: it's a *fuel* warning, not a flat tire. You are always using the same "miscellaneous unknown warning" light, for *everything*: "miscellaneous unknown warning: out of fuel" "miscellaneous unknown warning: doors left unlocked" "miscellaneous unknown warning: temperature too high" "miscellaneous unknown warning: out of milk" > In fact, I use exceptions only when I can't write an ``assert`` > statement concise enough. In the original code to which you initially > reacted I used an exception simply because it was more concise to put > it under the else clause rather then writing an ``assert`` statement > with all the if/else possibility it would have needed. If you are using asserts for data validation, then your code is broken. The caller can disable every single assert, and hence remove your data validation, by simply passing a command line switch when calling your program. -- Steven From ramit.prasad at jpmorgan.com Wed Sep 28 16:15:07 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Wed, 28 Sep 2011 10:15:07 -0400 Subject: [Tutor] Why subclassing exceptions? In-Reply-To: <4E832A4F.9080203@pearwood.info> References: <CAL2Y8-T8sODACzSzoQqAro0WWyp-9k+atgs1HGS8Fe+R_7kemQ@mail.gmail.com> <20110927222210.65a5b3e4@jabbar> <4E826339.1050403@pearwood.info> <20110928083337.462d24b8@jabbar> <j5ukbv$odr$1@dough.gmane.org> <20110928112328.2520aa92@jabbar> <4E832A4F.9080203@pearwood.info> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20D817FE@EMARC112VS01.exchad.jpmchase.net> >If you are using asserts for data validation, then your code is broken. >The caller can disable every single assert, and hence remove your data >validation, by simply passing a command line switch when calling your >program. To be fair, there are plenty of situations where someone has enough control of their execution environment to prevent that from happening. I agree on principle and for readability/maintainability; if I saw that I would be highly confused as to why asserts were everywhere. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 21h6 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From quasipedia at gmail.com Thu Sep 29 08:35:24 2011 From: quasipedia at gmail.com (Mac Ryan) Date: Thu, 29 Sep 2011 08:35:24 +0200 Subject: [Tutor] Why subclassing exceptions? In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20D817FE@EMARC112VS01.exchad.jpmchase.net> References: <CAL2Y8-T8sODACzSzoQqAro0WWyp-9k+atgs1HGS8Fe+R_7kemQ@mail.gmail.com> <20110927222210.65a5b3e4@jabbar> <4E826339.1050403@pearwood.info> <20110928083337.462d24b8@jabbar> <j5ukbv$odr$1@dough.gmane.org> <20110928112328.2520aa92@jabbar> <4E832A4F.9080203@pearwood.info> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20D817FE@EMARC112VS01.exchad.jpmchase.net> Message-ID: <20110929083524.1f80b368@jabbar> On Wed, 28 Sep 2011 10:15:07 -0400 "Prasad, Ramit" <ramit.prasad at jpmorgan.com> wrote: > >If you are using asserts for data validation, then your code is > >broken. The caller can disable every single assert, and hence remove > >your data validation, by simply passing a command line switch when > >calling your program. > > To be fair, there are plenty of situations where someone has enough > control of their execution environment to prevent that from > happening. I agree on principle and for readability/maintainability; > if I saw that I would be highly confused as to why asserts were > everywhere. Thank you Alan, Steve, Ramit for all your answers, very appreciated and useful. I would like to point out that I am not using ``assert`` for data validation. I am using it to understand if my code works. The reason why I prefer asserts over exceptions is just what you pointed out. Keeping building on Steve's simile: when I use asserts in my code, I'm still at the car factory. I'm not trying to communicate anything to a potential driver: I'm just trying to prevent myself to say "the car is ready" if there is a major flow in its design. In other words: rather than creating a specific "EngineerForgotToDesignEngine" warning light, I want the engineer to realise at a much earlier stage that she does need to put an engine on the car before the car is ready for prime time. Maybe the initial example that generated this thread was misleading, as a function is a typical example of a code that never knows what parameters will be passed in. All that said, I totally see your point and I swear that from now on I will give a deeper thought to what to write after the word "raise"! :) Thank you very much once more, /mac From c2praveen30jun at gmail.com Thu Sep 29 10:27:46 2011 From: c2praveen30jun at gmail.com (Praveen Singh) Date: Thu, 29 Sep 2011 13:57:46 +0530 Subject: [Tutor] where to look for python codes Message-ID: <CAJcoiztHOBAwu8fiB7ZCQ+HFw9H93uTpRcxE_ZGweSV_9j=Buw@mail.gmail.com> i am a beginner in python.i am not asking about any books here.As i have heard one essential steps of learning is to look for some good python codes.So, can you guys please and please suggest me some sites or some small projects where i can find these codes?? please remember i am at a BEGINNER's level!! thank you!! -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110929/b71395e7/attachment-0001.html> From alan.gauld at btinternet.com Thu Sep 29 10:47:35 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 29 Sep 2011 09:47:35 +0100 Subject: [Tutor] where to look for python codes In-Reply-To: <CAJcoiztHOBAwu8fiB7ZCQ+HFw9H93uTpRcxE_ZGweSV_9j=Buw@mail.gmail.com> References: <CAJcoiztHOBAwu8fiB7ZCQ+HFw9H93uTpRcxE_ZGweSV_9j=Buw@mail.gmail.com> Message-ID: <j61bb8$kig$1@dough.gmane.org> On 29/09/11 09:27, Praveen Singh wrote: > i am a beginner in python.i am not asking about any books here.As i have > heard one essential steps of learning is to look for some good python > codes.So, can you guys please and please suggest me some sites or some > small projects where i can find these codes?? please remember i am at a > BEGINNER's level!! We used to have a site called UselessPython for that but last time I visited it was down. I don't know if its been resurrected but it was a useful resource for that kind of thing. Other sources are the simple tool scripts that come with Python. Look in the Library folders and you will find various sample/tool folders that you can investigate. hth, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From kellyadrian at hotmail.com Thu Sep 29 11:05:58 2011 From: kellyadrian at hotmail.com (ADRIAN KELLY) Date: Thu, 29 Sep 2011 09:05:58 +0000 Subject: [Tutor] last part of my programme Message-ID: <DUB103-W61A38BB87506AA346FAA3A9F60@phx.gbl> can anyone tell me why the last part of my programme wont work. i want the user to have to press enter to exit but it doesn't happen through the python interface. the programme works fine otherwise but just shuts down when finished thanks all adrian -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110929/3e301bf8/attachment.html> -------------- next part -------------- A non-text attachment was scrubbed... Name: password - Copy - Copy.py Type: text/x-script.phyton Size: 914 bytes Desc: not available URL: <http://mail.python.org/pipermail/tutor/attachments/20110929/3e301bf8/attachment.bin> From cwitts at compuscan.co.za Thu Sep 29 11:17:58 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Thu, 29 Sep 2011 11:17:58 +0200 Subject: [Tutor] last part of my programme In-Reply-To: <DUB103-W61A38BB87506AA346FAA3A9F60@phx.gbl> References: <DUB103-W61A38BB87506AA346FAA3A9F60@phx.gbl> Message-ID: <4E8437C6.8050508@compuscan.co.za> On 2011/09/29 11:05 AM, ADRIAN KELLY wrote: > can anyone tell me why the last part of my programme wont work. i > want the user to have to press enter to exit but it doesn't happen > through the python interface. > > the programme works fine otherwise but just shuts down when finished > > thanks all > > adrian > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor You should run this from the command line to see the errors and tracebacks. You have a `firstname` and `lastname` variable, no `name` variable. Traceback (most recent call last): File "py_tutor.py", line 34, in <module> STATS() File "py_tutor.py", line 26, in STATS details=name+"\n"+town+"\n"+county NameError: global name 'name' is not defined Once you fix that with something like `name = firstname + ' ' + lastname` you'll get a further error Press the enter key to exit. Traceback (most recent call last): File "py_tutor.py", line 39, in <module> _ = input("\n\nPress the enter key to exit. ") File "<string>", line 0 Which is because input() converts the input to an integer so you would need to type for eg 0 then enter for it to exit without failing. Changing that to raw_input() like the rest of your inputs will fix that. -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110929/758219a1/attachment.html> From __peter__ at web.de Thu Sep 29 11:33:04 2011 From: __peter__ at web.de (Peter Otten) Date: Thu, 29 Sep 2011 11:33:04 +0200 Subject: [Tutor] last part of my programme References: <DUB103-W61A38BB87506AA346FAA3A9F60@phx.gbl> Message-ID: <j61dvl$6ms$1@dough.gmane.org> ADRIAN KELLY wrote: > can anyone tell me why the last part of my programme wont work. i want > the user to have to press enter to exit but it doesn't happen through the > python interface. > > the programme works fine otherwise but just shuts down when finished (I'm assuming you are on Windows) Open a DOS window and cd to the directory where you have stored your script. Invoke it with python <name-of-the-script> When you now enter the data your script is asking for you will at some point run into the error and get a so-called "traceback" and an error message. Here's how it looks on Linux (I've stored your script as tmp_adrian.py): $ python tmp_adrian.py hello i am your computer please enter your password: gorilla Password Accepted hello please enter your firstname: peter please enter your lastname: otten what town are your from? won't what county are you from? tell Traceback (most recent call last): File "tmp_adrian.py", line 34, in <module> STATS() File "tmp_adrian.py", line 26, in STATS details=name+"\n"+town+"\n"+county NameError: global name 'name' is not defined $ Can you make sense of that message and find the bug that is causing it? Come back if not. From robert.johansson at math.umu.se Thu Sep 29 11:42:23 2011 From: robert.johansson at math.umu.se (Robert Johansson) Date: Thu, 29 Sep 2011 11:42:23 +0200 Subject: [Tutor] Mac IDE Message-ID: <61310E38B60C8F4AB59757E88A3C967723F3021237@UMDAC-CCR2.ad.umu.se> Hi, I know that there is a lot to read about different IDEs on the net but I have tried a couple and I'm still not pleased. My demands are not that high, when I'm under Windows I'm happy with IDLE (an interactive shell and debug) but the problem is with Mac (Python >= 2.7 and OS 10.7). IDLE had serious problems and TextWrangler had no interactive shell. There's a lot of other stuff to try and I would be grateful if someone could spare me some time on this. Cheers, Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110929/7f53f183/attachment.html> From sli1que at yahoo.com Thu Sep 29 12:42:28 2011 From: sli1que at yahoo.com (=?utf-8?B?c2xpMXF1ZUB5YWhvby5jb20=?=) Date: Thu, 29 Sep 2011 03:42:28 -0700 Subject: [Tutor] =?utf-8?q?Mac_IDE?= Message-ID: <951221.77145.bm@smtp211.mail.bf1.yahoo.com> I use eclipse. Overkill for you maybe but you can so anything. Sent from my Verizon Wireless 4GLTE smartphone ----- Reply message ----- From: "Robert Johansson" <robert.johansson at math.umu.se> To: "tutor at python.org" <tutor at python.org> Subject: [Tutor] Mac IDE Date: Thu, Sep 29, 2011 2:42 am Hi, I know that there is a lot to read about different IDEs on the net but I have tried a couple and I?m still not pleased. My demands are not that high, when I?m under Windows I?m happy with IDLE (an interactive shell and debug) but the problem is with Mac (Python >= 2.7 and OS 10.7). IDLE had serious problems and TextWrangler had no interactive shell. There?s a lot of other stuff to try and I would be grateful if someone could spare me some time on this. Cheers, Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110929/edee4020/attachment.html> From wprins at gmail.com Thu Sep 29 12:50:51 2011 From: wprins at gmail.com (Walter Prins) Date: Thu, 29 Sep 2011 11:50:51 +0100 Subject: [Tutor] Mac IDE In-Reply-To: <61310E38B60C8F4AB59757E88A3C967723F3021237@UMDAC-CCR2.ad.umu.se> References: <61310E38B60C8F4AB59757E88A3C967723F3021237@UMDAC-CCR2.ad.umu.se> Message-ID: <CANLXbfAx=2Ths9HanDXZ0MEKN9nVTGtz42XGoRhGEOB3bZrZog@mail.gmail.com> Hi On 29 September 2011 10:42, Robert Johansson <robert.johansson at math.umu.se>wrote: > Hi,**** > > ** ** > > I know that there is a lot to read about different IDEs on the net but I > have tried a couple and I?m still not pleased. My demands are not that high, > when I?m under Windows I?m happy with IDLE (an interactive shell and debug) > but the problem is with Mac (Python >= 2.7 and OS 10.7). IDLE had serious > problems and TextWrangler had no interactive shell. There?s a lot of other > stuff to try and I would be grateful if someone could spare me some time on > this. **** > > > Well, if you're prepared to spend a bit of money, I've heard very good things about Wingware, which is also available on Mac (Note, not a user myself currently, but has seen it before and been favourably impressed, enough to suggest it here despite not currently actively using it myself.) Link: http://wingware.com/ In terms of free/open source, there's also of course Eclipse with PyDev, although I don't know how easily/well it integrates into the Mac ecosystem, but suffice it to say Mac is listed as a supported platform. I use Eclipse with PyDev on Linux and Windows and am quite happy with it. Links: http://www.eclipse.org/downloads/packages/eclipse-classic-37/indigor http://pydev.org/index.html HTH Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110929/ecb19a16/attachment.html> From tommy.kaas at kaasogmulvad.dk Thu Sep 29 13:35:24 2011 From: tommy.kaas at kaasogmulvad.dk (Tommy Kaas) Date: Thu, 29 Sep 2011 13:35:24 +0200 Subject: [Tutor] where to look for python codes In-Reply-To: <j61bb8$kig$1@dough.gmane.org> References: <CAJcoiztHOBAwu8fiB7ZCQ+HFw9H93uTpRcxE_ZGweSV_9j=Buw@mail.gmail.com> <j61bb8$kig$1@dough.gmane.org> Message-ID: <015101cc7e9b$e12746a0$a375d3e0$@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: 29. september 2011 10:48 > Til: tutor at python.org > Emne: Re: [Tutor] where to look for python codes > > On 29/09/11 09:27, Praveen Singh wrote: > > i am a beginner in python.i am not asking about any books here.As i > > have heard one essential steps of learning is to look for some good > > python codes.So, can you guys please and please suggest me some sites > > or some small projects where i can find these codes?? please remember > > i am at a BEGINNER's level!! > > > We used to have a site called UselessPython for that but last time I visited it > was down. I don't know if its been resurrected but it was a useful resource > for that kind of thing. Uselesspython is down, but you can reach a lot of the stuff through archive.org: http://web.archive.org/web/20080719092030/http://www.uselesspython.com/ Tommy > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > ----- > Ingen virus fundet i denne meddelelse. > Kontrolleret af AVG - www.avg.com > Version: 10.0.1410 / Virusdatabase: 1520/3925 - Udgivelsesdato: 28-09- > 2011 From waynejwerner at gmail.com Thu Sep 29 13:50:21 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Thu, 29 Sep 2011 06:50:21 -0500 Subject: [Tutor] Mac IDE In-Reply-To: <CANLXbfAx=2Ths9HanDXZ0MEKN9nVTGtz42XGoRhGEOB3bZrZog@mail.gmail.com> References: <61310E38B60C8F4AB59757E88A3C967723F3021237@UMDAC-CCR2.ad.umu.se> <CANLXbfAx=2Ths9HanDXZ0MEKN9nVTGtz42XGoRhGEOB3bZrZog@mail.gmail.com> Message-ID: <CAPM86NcVKyzcYp9DbOc5q+wvLU87uHDyxd0oP+w5W5hmR5CzKA@mail.gmail.com> On Thu, Sep 29, 2011 at 5:50 AM, Walter Prins <wprins at gmail.com> wrote: > On 29 September 2011 10:42, Robert Johansson <robert.johansson at math.umu.se > > wrote: > >> Hi,**** >> >> ** ** >> >> I know that there is a lot to read about different IDEs on the net but I >> have tried a couple and I?m still not pleased. My demands are not that high, >> when I?m under Windows I?m happy with IDLE (an interactive shell and debug) >> but the problem is with Mac (Python >= 2.7 and OS 10.7). IDLE had serious >> problems and TextWrangler had no interactive shell. There?s a lot of other >> stuff to try and I would be grateful if someone could spare me some time on >> this. **** >> >> >> > Well, if you're prepared to spend a bit of money, I've heard very good > things about Wingware, which is also available on Mac (Note, not a user > myself currently, but has seen it before and been favourably impressed, > enough to suggest it here despite not currently actively using it myself.) > Link: http://wingware.com/ I'll second that. If you're really into IDEs, Wingware is a great one - they also have a student/open source license that may be right up your alley. My personal favorite? Two terminal windows - one with Vim, editing my Python scripts, and another with an interactive interpreter. Since you can map keys in Vim, I have <F5> mapped to save and run current file. If you're in the habit of editing multiple files you could set it up to map <F5> to ask which file you want to set as your main .py file. And since you mentioned debug, I usually just use pdb if I need debugging. You could easily map a key such as <F9> to insert a new line and type 'pdb.set_trace()'. Vim has a fairly steep learning curve, but if you spend 30 minutes with the vimtutor you'll be fine. With newer versions of Vim you can also write plugins for them in Python. Of course these capabilities (and many many more) are available with Emacs. I personally recommend that you learn one (or both) of these editors. They will highly improve the speed at which you are able to edit your code. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110929/9bf6f482/attachment-0001.html> From cfuller084 at thinkingplanet.net Thu Sep 29 15:42:52 2011 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Thu, 29 Sep 2011 08:42:52 -0500 Subject: [Tutor] where to look for python codes In-Reply-To: <CAJcoiztHOBAwu8fiB7ZCQ+HFw9H93uTpRcxE_ZGweSV_9j=Buw@mail.gmail.com> References: <CAJcoiztHOBAwu8fiB7ZCQ+HFw9H93uTpRcxE_ZGweSV_9j=Buw@mail.gmail.com> Message-ID: <201109290842.53239.cfuller084@thinkingplanet.net> Unless you are explicitly reading a tutorial, the code you will be looking at isn't going to be beginner-level in general, but you can look at smaller snippets and libraries then work up from that. http://effbot.org/zone/ http://code.activestate.com/recipes/langs/python/ http://pypi.python.org/pypi http://www.doughellmann.com/projects/PyMOTW/ http://www.secnetix.de/olli/Python/ There's plenty of good links right on the Python web site for beginners: http://wiki.python.org/moin/BeginnersGuide Cheers On Thursday 29 September 2011, Praveen Singh wrote: > i am a beginner in python.i am not asking about any books here.As i have > heard one essential steps of learning is to look for some good python > codes.So, can you guys please and please suggest me some sites or some > small projects where i can find these codes?? please remember i am at a > BEGINNER's level!! > > thank you!! From lina.lastname at gmail.com Thu Sep 29 16:22:35 2011 From: lina.lastname at gmail.com (lina) Date: Thu, 29 Sep 2011 22:22:35 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end Message-ID: <CAG9cJmnZy909vkJMi6Xdr1upc9QH8iB+LScLwDAyPpGUkoMf6A@mail.gmail.com> Hi, I want to read a bunch of *.doc file in present working directory, how can I use for to read one by one and do further work, sorry, what's the best reference webpage I can use? I googled, lots of distracting info, and I barely can understand how they think. THanks, -- Best Regards, lina -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110929/5c21e7f8/attachment.html> From mail at timgolden.me.uk Thu Sep 29 16:25:40 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 29 Sep 2011 15:25:40 +0100 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: <CAG9cJmnZy909vkJMi6Xdr1upc9QH8iB+LScLwDAyPpGUkoMf6A@mail.gmail.com> References: <CAG9cJmnZy909vkJMi6Xdr1upc9QH8iB+LScLwDAyPpGUkoMf6A@mail.gmail.com> Message-ID: <4E847FE4.2030602@timgolden.me.uk> On 29/09/2011 15:22, lina wrote: > I want to read a bunch of *.doc file in present working directory, > > how can I use for to read one by one and do further work, > > sorry, > > what's the best reference webpage I can use? > > I googled, lots of distracting info, and I barely can understand how > they think. Try these: http://docs.python.org/library/glob.html http://www.doughellmann.com/PyMOTW/glob/index.html TJG From lina.lastname at gmail.com Thu Sep 29 16:39:36 2011 From: lina.lastname at gmail.com (lina) Date: Thu, 29 Sep 2011 22:39:36 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: <4E847FE4.2030602@timgolden.me.uk> References: <CAG9cJmnZy909vkJMi6Xdr1upc9QH8iB+LScLwDAyPpGUkoMf6A@mail.gmail.com> <4E847FE4.2030602@timgolden.me.uk> Message-ID: <CAG9cJmm_8KQwEt4kCSNrtU4FfEkiaaCJRsPvjY7CG0LduxZX-A@mail.gmail.com> On Thu, Sep 29, 2011 at 10:25 PM, Tim Golden <mail at timgolden.me.uk> wrote: > On 29/09/2011 15:22, lina wrote: > >> I want to read a bunch of *.doc file in present working directory, >> >> how can I use for to read one by one and do further work, >> >> sorry, >> >> what's the best reference webpage I can use? >> >> I googled, lots of distracting info, and I barely can understand how >> they think. >> > > Try these: > > http://docs.python.org/**library/glob.html<http://docs.python.org/library/glob.html> > > http://www.doughellmann.com/**PyMOTW/glob/index.html<http://www.doughellmann.com/PyMOTW/glob/index.html> > Thanks, import glob for FILE in glob.glob('*.xpm'): print FILE How do I not print FILE, I want to put those files in a for loop and then further to read one by one, Thanks, > > TJG > -- Best Regards, lina -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110929/fe34f997/attachment.html> From d at davea.name Thu Sep 29 16:43:13 2011 From: d at davea.name (Dave Angel) Date: Thu, 29 Sep 2011 10:43:13 -0400 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: <CAG9cJmnZy909vkJMi6Xdr1upc9QH8iB+LScLwDAyPpGUkoMf6A@mail.gmail.com> References: <CAG9cJmnZy909vkJMi6Xdr1upc9QH8iB+LScLwDAyPpGUkoMf6A@mail.gmail.com> Message-ID: <4E848401.8060504@davea.name> On 09/29/2011 10:22 AM, lina wrote: > Hi, > > I want to read a bunch of *.doc file in present working directory, > > how can I use for to read one by one and do further work, > > sorry, > > what's the best reference webpage I can use? > > I googled, lots of distracting info, and I barely can understand how they > think. > > THanks, > Look in the os module for things like this. In particular (untested): import os.path for fileName in os.listdir(".") if os.path.isfile(fileName) and os.path.splitext(fileName) == "doc": filedata = open(fileName) xxxdosomething with filedata -- DaveA From tktucker at gmail.com Thu Sep 29 16:43:40 2011 From: tktucker at gmail.com (Tom Tucker) Date: Thu, 29 Sep 2011 10:43:40 -0400 Subject: [Tutor] Mac IDE In-Reply-To: <CAPM86NcVKyzcYp9DbOc5q+wvLU87uHDyxd0oP+w5W5hmR5CzKA@mail.gmail.com> References: <61310E38B60C8F4AB59757E88A3C967723F3021237@UMDAC-CCR2.ad.umu.se> <CANLXbfAx=2Ths9HanDXZ0MEKN9nVTGtz42XGoRhGEOB3bZrZog@mail.gmail.com> <CAPM86NcVKyzcYp9DbOc5q+wvLU87uHDyxd0oP+w5W5hmR5CzKA@mail.gmail.com> Message-ID: <CAGymF1CP4YU_4M-3iTOBLLXJjpYQ4Xgzfdkkm78p6TJ85D-+2A@mail.gmail.com> Another IDE to consider that supports the MAC OS is PyCharm from JetBrains. On Thu, Sep 29, 2011 at 7:50 AM, Wayne Werner <waynejwerner at gmail.com>wrote: > On Thu, Sep 29, 2011 at 5:50 AM, Walter Prins <wprins at gmail.com> wrote: > >> On 29 September 2011 10:42, Robert Johansson < >> robert.johansson at math.umu.se> wrote: >> >>> Hi,**** >>> >>> ** ** >>> >>> I know that there is a lot to read about different IDEs on the net but I >>> have tried a couple and I?m still not pleased. My demands are not that high, >>> when I?m under Windows I?m happy with IDLE (an interactive shell and debug) >>> but the problem is with Mac (Python >= 2.7 and OS 10.7). IDLE had serious >>> problems and TextWrangler had no interactive shell. There?s a lot of other >>> stuff to try and I would be grateful if someone could spare me some time on >>> this. **** >>> >>> >>> >> Well, if you're prepared to spend a bit of money, I've heard very good >> things about Wingware, which is also available on Mac (Note, not a user >> myself currently, but has seen it before and been favourably impressed, >> enough to suggest it here despite not currently actively using it myself.) >> Link: http://wingware.com/ > > > I'll second that. If you're really into IDEs, Wingware is a great one - > they also have a student/open source license that may be right up your > alley. > > My personal favorite? > > Two terminal windows - one with Vim, editing my Python scripts, and another > with an interactive interpreter. Since you can map keys in Vim, I have <F5> > mapped to save and run current file. If you're in the habit of editing > multiple files you could set it up to map <F5> to ask which file you want to > set as your main .py file. And since you mentioned debug, I usually just use > pdb if I need debugging. You could easily map a key such as <F9> to insert a > new line and type 'pdb.set_trace()'. Vim has a fairly steep learning curve, > but if you spend 30 minutes with the vimtutor you'll be fine. With newer > versions of Vim you can also write plugins for them in Python. > > Of course these capabilities (and many many more) are available with Emacs. > > I personally recommend that you learn one (or both) of these editors. They > will highly improve the speed at which you are able to edit your code. > > HTH, > Wayne > > _______________________________________________ > 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: <http://mail.python.org/pipermail/tutor/attachments/20110929/3e7d2a2d/attachment-0001.html> From lina.lastname at gmail.com Thu Sep 29 16:55:30 2011 From: lina.lastname at gmail.com (lina) Date: Thu, 29 Sep 2011 22:55:30 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: <4E848401.8060504@davea.name> References: <CAG9cJmnZy909vkJMi6Xdr1upc9QH8iB+LScLwDAyPpGUkoMf6A@mail.gmail.com> <4E848401.8060504@davea.name> Message-ID: <CAG9cJmmR_bO-UU-hPFneKT3zkSuEEOTEyE8Tgr-p3uk=fP8yFQ@mail.gmail.com> import os.path tokens=['E'] result=[] for fileName in os.listdir("."): if os.path.isfile(fileName) and os.path.splitext(fileName)=="xpm": filedata = open(fileName) text=filedata.readlines() for line in text: How can I read from line 24 and do further looking for "E". Thanks, On Thu, Sep 29, 2011 at 10:43 PM, Dave Angel <d at davea.name> wrote: > On 09/29/2011 10:22 AM, lina wrote: > >> Hi, >> >> I want to read a bunch of *.doc file in present working directory, >> >> how can I use for to read one by one and do further work, >> >> sorry, >> >> what's the best reference webpage I can use? >> >> I googled, lots of distracting info, and I barely can understand how they >> think. >> >> THanks, >> >> Look in the os module for things like this. In particular (untested): > > import os.path > > for fileName in os.listdir(".") > if os.path.isfile(fileName) and os.path.splitext(fileName) == "doc": > filedata = open(fileName) > xxxdosomething with filedata > > > > -- > > DaveA > > -- Best Regards, lina -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110929/d032cb06/attachment.html> From lina.lastname at gmail.com Thu Sep 29 17:06:46 2011 From: lina.lastname at gmail.com (lina) Date: Thu, 29 Sep 2011 23:06:46 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: <CAG9cJmmR_bO-UU-hPFneKT3zkSuEEOTEyE8Tgr-p3uk=fP8yFQ@mail.gmail.com> References: <CAG9cJmnZy909vkJMi6Xdr1upc9QH8iB+LScLwDAyPpGUkoMf6A@mail.gmail.com> <4E848401.8060504@davea.name> <CAG9cJmmR_bO-UU-hPFneKT3zkSuEEOTEyE8Tgr-p3uk=fP8yFQ@mail.gmail.com> Message-ID: <CAG9cJmmJ+TR=N6dBedXXAg+roQrTDRJujWuRZESQy7bjURwF9g@mail.gmail.com> On Thu, Sep 29, 2011 at 10:55 PM, lina <lina.lastname at gmail.com> wrote: > import os.path > > tokens=['E'] > result=[] > > > for fileName in os.listdir("."): > if os.path.isfile(fileName) and os.path.splitext(fileName)=="xpm": > filedata = open(fileName) > text=filedata.readlines() > for line in text: > > > How can I read from line 24 and do further looking for "E". > > Thanks, > > The file starts from line 24 is something like aabbccddEaabb acbbddEbbaaca EabcEabcaaaa aEaaEaaaaaaa so for the first column, I can get 1 E, second column is also 1 E, third is 0, four is 2. namely count the occurence of E in each column. Thanks, > > > On Thu, Sep 29, 2011 at 10:43 PM, Dave Angel <d at davea.name> wrote: > >> On 09/29/2011 10:22 AM, lina wrote: >> >>> Hi, >>> >>> I want to read a bunch of *.doc file in present working directory, >>> >>> how can I use for to read one by one and do further work, >>> >>> sorry, >>> >>> what's the best reference webpage I can use? >>> >>> I googled, lots of distracting info, and I barely can understand how they >>> think. >>> >>> THanks, >>> >>> Look in the os module for things like this. In particular (untested): >> >> import os.path >> >> for fileName in os.listdir(".") >> if os.path.isfile(fileName) and os.path.splitext(fileName) == "doc": >> filedata = open(fileName) >> xxxdosomething with filedata >> >> >> >> -- >> >> DaveA >> >> > > > -- > Best Regards, > > lina > > > -- Best Regards, lina -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110929/104012f1/attachment.html> From lina.lastname at gmail.com Thu Sep 29 17:13:28 2011 From: lina.lastname at gmail.com (lina) Date: Thu, 29 Sep 2011 23:13:28 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: <CAG9cJmmJ+TR=N6dBedXXAg+roQrTDRJujWuRZESQy7bjURwF9g@mail.gmail.com> References: <CAG9cJmnZy909vkJMi6Xdr1upc9QH8iB+LScLwDAyPpGUkoMf6A@mail.gmail.com> <4E848401.8060504@davea.name> <CAG9cJmmR_bO-UU-hPFneKT3zkSuEEOTEyE8Tgr-p3uk=fP8yFQ@mail.gmail.com> <CAG9cJmmJ+TR=N6dBedXXAg+roQrTDRJujWuRZESQy7bjURwF9g@mail.gmail.com> Message-ID: <CAG9cJmnMVPzznziZeeYcK8WpsRxWu=aeZLbFqC-gJGFJ7Bs8AQ@mail.gmail.com> mport os.path tokens=['E'] result=[] for fileName in os.listdir("."): if os.path.isfile(fileName) and os.path.splitext(fileName)=="xpm": filedata = open(fileName,'r') text=filedata.readlines() for line in text: print line why here I print nothing out? There is .xpm file there with content. Thanks, On Thu, Sep 29, 2011 at 11:06 PM, lina <lina.lastname at gmail.com> wrote: > > > On Thu, Sep 29, 2011 at 10:55 PM, lina <lina.lastname at gmail.com> wrote: > >> import os.path >> >> tokens=['E'] >> result=[] >> >> >> for fileName in os.listdir("."): >> if os.path.isfile(fileName) and os.path.splitext(fileName)=="xpm": >> filedata = open(fileName) >> text=filedata.readlines() >> for line in text: >> >> >> How can I read from line 24 and do further looking for "E". >> >> Thanks, >> >> > The file starts from line 24 is something like > > aabbccddEaabb > acbbddEbbaaca > EabcEabcaaaa > aEaaEaaaaaaa > > so for the first column, I can get 1 E, second column is also 1 E, third is > 0, four is 2. > > namely count the occurence of E in each column. > > Thanks, > > >> >> >> On Thu, Sep 29, 2011 at 10:43 PM, Dave Angel <d at davea.name> wrote: >> >>> On 09/29/2011 10:22 AM, lina wrote: >>> >>>> Hi, >>>> >>>> I want to read a bunch of *.doc file in present working directory, >>>> >>>> how can I use for to read one by one and do further work, >>>> >>>> sorry, >>>> >>>> what's the best reference webpage I can use? >>>> >>>> I googled, lots of distracting info, and I barely can understand how >>>> they >>>> think. >>>> >>>> THanks, >>>> >>>> Look in the os module for things like this. In particular (untested): >>> >>> import os.path >>> >>> for fileName in os.listdir(".") >>> if os.path.isfile(fileName) and os.path.splitext(fileName) == "doc": >>> filedata = open(fileName) >>> xxxdosomething with filedata >>> >>> >>> >>> -- >>> >>> DaveA >>> >>> >> >> >> -- >> Best Regards, >> >> lina >> >> >> > > > -- > Best Regards, > > lina > > > -- Best Regards, lina -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110929/8df9629b/attachment.html> From wprins at gmail.com Thu Sep 29 17:18:49 2011 From: wprins at gmail.com (Walter Prins) Date: Thu, 29 Sep 2011 16:18:49 +0100 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: <CAG9cJmnMVPzznziZeeYcK8WpsRxWu=aeZLbFqC-gJGFJ7Bs8AQ@mail.gmail.com> References: <CAG9cJmnZy909vkJMi6Xdr1upc9QH8iB+LScLwDAyPpGUkoMf6A@mail.gmail.com> <4E848401.8060504@davea.name> <CAG9cJmmR_bO-UU-hPFneKT3zkSuEEOTEyE8Tgr-p3uk=fP8yFQ@mail.gmail.com> <CAG9cJmmJ+TR=N6dBedXXAg+roQrTDRJujWuRZESQy7bjURwF9g@mail.gmail.com> <CAG9cJmnMVPzznziZeeYcK8WpsRxWu=aeZLbFqC-gJGFJ7Bs8AQ@mail.gmail.com> Message-ID: <CANLXbfAQd7cKmJ_6Og8ubCWtnH=u8jZLa3-b+55WgxGJyVq6Lw@mail.gmail.com> On 29 September 2011 16:13, lina <lina.lastname at gmail.com> wrote: > mport os.path > > tokens=['E'] > result=[] > > for fileName in os.listdir("."): > if os.path.isfile(fileName) and os.path.splitext(fileName)=="xpm": > filedata = open(fileName,'r') > > text=filedata.readlines() > for line in text: > print line > > why here I print nothing out? > > There is .xpm file there with content. > > Thanks, > > Is your .xpm files actually text files? Or are they binary (e.g. maybe graphics) files? (XPM is normally the extension of a graphics filetype.) Treating a binary file as if its text is not liable to work very well. Also can you please confirm whether this task is homework/study related? Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110929/30b33edb/attachment-0001.html> From lina.lastname at gmail.com Thu Sep 29 17:25:19 2011 From: lina.lastname at gmail.com (lina) Date: Thu, 29 Sep 2011 23:25:19 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: <CANLXbfAQd7cKmJ_6Og8ubCWtnH=u8jZLa3-b+55WgxGJyVq6Lw@mail.gmail.com> References: <CAG9cJmnZy909vkJMi6Xdr1upc9QH8iB+LScLwDAyPpGUkoMf6A@mail.gmail.com> <4E848401.8060504@davea.name> <CAG9cJmmR_bO-UU-hPFneKT3zkSuEEOTEyE8Tgr-p3uk=fP8yFQ@mail.gmail.com> <CAG9cJmmJ+TR=N6dBedXXAg+roQrTDRJujWuRZESQy7bjURwF9g@mail.gmail.com> <CAG9cJmnMVPzznziZeeYcK8WpsRxWu=aeZLbFqC-gJGFJ7Bs8AQ@mail.gmail.com> <CANLXbfAQd7cKmJ_6Og8ubCWtnH=u8jZLa3-b+55WgxGJyVq6Lw@mail.gmail.com> Message-ID: <CAG9cJmmqvxTXT+JkzA3cdP5LTUOAM=2vCK6BPSADh4QcVR5NVQ@mail.gmail.com> On Thu, Sep 29, 2011 at 11:18 PM, Walter Prins <wprins at gmail.com> wrote: > > > On 29 September 2011 16:13, lina <lina.lastname at gmail.com> wrote: > >> mport os.path >> >> tokens=['E'] >> result=[] >> >> for fileName in os.listdir("."): >> if os.path.isfile(fileName) and os.path.splitext(fileName)=="xpm": >> filedata = open(fileName,'r') >> >> text=filedata.readlines() >> for line in text: >> print line >> >> why here I print nothing out? >> >> There is .xpm file there with content. >> >> Thanks, >> >> > Is your .xpm files actually text files? Or are they binary (e.g. maybe > graphics) files? (XPM is normally the extension of a graphics filetype.) > Treating a binary file as if its text is not liable to work very well. > > Also can you please confirm whether this task is homework/study related? > I have some awk script to achieve this. I can assure you it's not homework. LOL ... I have never attended some python course. sometimes it's hard for you to image how hard I persuade myself to use/think in python way, forget what is-already-relatively-easy-for-me-to-use bash script. the xpm file an read, I just text f=open('1.xpm','r') for line in f.readlines(): print line f.close() I am google-ing how to get the line index, so will use those after 24. > > Walter > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Best Regards, lina -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110929/0499c006/attachment.html> From ramit.prasad at jpmorgan.com Thu Sep 29 16:57:42 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 29 Sep 2011 10:57:42 -0400 Subject: [Tutor] map one file and print it out following the sequence In-Reply-To: <CAG9cJmkJX_b3NN2XvuBNfagUzaF+AS-Z3ULkR3nYyAi8Ob-frw@mail.gmail.com> References: <CAG9cJmm7nR-qYR7r8B=6Ea5mRTpm2s+DyOHx-7Kkq8J9LZbvfQ@mail.gmail.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20D811A3@EMARC112VS01.exchad.jpmchase.net> <CAG9cJmkJX_b3NN2XvuBNfagUzaF+AS-Z3ULkR3nYyAi8Ob-frw@mail.gmail.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20EB121E@EMARC112VS01.exchad.jpmchase.net> From: tutor-bounces+ramit.prasad=jpmorgan.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of lina Sent: Tuesday, September 27, 2011 10:35 PM Cc: tutor Subject: Re: [Tutor] map one file and print it out following the sequence Hi, Thanks for both of your reply. File 1 is: 3 C 1 CUR C19 1 0.200 12.0110 4 CR1 1 CUR C20 1 -0.060 12.0110 5 HC 1 CUR H20 1 0.060 1.0080 File 2 is: ATOM 2 H20 CUR 1 30.338 28.778 -6.812 1.00 0.00 ATOM 4 C20 CUR 1 31.394 28.922 -7.039 1.00 0.00 ATOM 5 C19 CUR 1 31.790 29.357 -8.323 1.00 0.00 I wish to get: ATOM 5 C19 CUR 1 31.790 29.357 -8.323 1.00 0.00 ATOM 4 C20 CUR 1 31.394 28.922 -7.039 1.00 0.00 ATOM 2 H20 CUR 1 30.338 28.778 -6.812 1.00 0.00 The dictionary is C19 C20 H20 sequence read from file 1 field 5. rearrange the file 2 field 3 following the sequence of C19, C20, H20. Thanks. =================================================================== This is something I wrote *really* quick and is untested. Hopefully someone on this list can spot any error I made. mapping={} with open("cur.itp") as f: for line in f.readlines(): parts=line.strip().split() if len(parts)==8: mapping[parts[4]]=parts[0] with open("processedpdb") as f: proccessed = [ line.split() for line in f.readlines() ] processed.sort( key=lambda x: mapping.get( x[2], 0 ) ) # use 0 to put items without a mapping at the # top of the file because they are probably an error For line in array: print ' '.join( line ) Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From d at davea.name Thu Sep 29 17:28:29 2011 From: d at davea.name (Dave Angel) Date: Thu, 29 Sep 2011 11:28:29 -0400 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: <CAG9cJmmR_bO-UU-hPFneKT3zkSuEEOTEyE8Tgr-p3uk=fP8yFQ@mail.gmail.com> References: <CAG9cJmnZy909vkJMi6Xdr1upc9QH8iB+LScLwDAyPpGUkoMf6A@mail.gmail.com> <4E848401.8060504@davea.name> <CAG9cJmmR_bO-UU-hPFneKT3zkSuEEOTEyE8Tgr-p3uk=fP8yFQ@mail.gmail.com> Message-ID: <4E848E9D.3090901@davea.name> (Please don't top-post. Put your remarks AFTER the part you're quoting from the previous message) On 09/29/2011 10:55 AM, lina wrote: > import os.path > > tokens=['E'] > result=[] > > for fileName in os.listdir("."): > if os.path.isfile(fileName) and os.path.splitext(fileName)=="xpm": > filedata = open(fileName) > text=filedata.readlines() > for line in text: > > > How can I read from line 24 and do further looking for "E". > > Thanks, > > As I said in my earlier message, this was untested. It gave you the building blocks, but was not correct. In particular, that if-test will always fail, so you're not seeing any files. import os.path tokens=['E'] result=[] for fileName in os.listdir("."): if os.path.isfile(fileName) and os.path.splitext(fileName)[1]==".xpm": filedata = open(fileName) text=filedata.readlines() for line in text: print line Once you've tested that, then you're ready to just look at line 24. text is a list, so you can refer to line 24 as text[24] Or you can get lines 24-28, with text[24, 29] (look up slices in the Python doc) == DaveA From lina.lastname at gmail.com Thu Sep 29 17:39:44 2011 From: lina.lastname at gmail.com (lina) Date: Thu, 29 Sep 2011 23:39:44 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: <4E848E9D.3090901@davea.name> References: <CAG9cJmnZy909vkJMi6Xdr1upc9QH8iB+LScLwDAyPpGUkoMf6A@mail.gmail.com> <4E848401.8060504@davea.name> <CAG9cJmmR_bO-UU-hPFneKT3zkSuEEOTEyE8Tgr-p3uk=fP8yFQ@mail.gmail.com> <4E848E9D.3090901@davea.name> Message-ID: <CAG9cJmkLUcs21tOoSwJmT7uF2NmBege2MmPkA95kJvRr13+tzA@mail.gmail.com> On Thu, Sep 29, 2011 at 11:28 PM, Dave Angel <d at davea.name> wrote: > (Please don't top-post. Put your remarks AFTER the part you're quoting > from the previous message) > > > On 09/29/2011 10:55 AM, lina wrote: > >> import os.path >> >> tokens=['E'] >> result=[] >> >> for fileName in os.listdir("."): >> if os.path.isfile(fileName) and os.path.splitext(fileName)=="**xpm": >> filedata = open(fileName) >> text=filedata.readlines() >> for line in text: >> >> >> How can I read from line 24 and do further looking for "E". >> >> Thanks, >> >> >> > As I said in my earlier message, this was untested. It gave you the > building blocks, but was not correct. > > In particular, that if-test will always fail, so you're not seeing any > files. > > > import os.path > > tokens=['E'] > result=[] > > for fileName in os.listdir("."): > > if os.path.isfile(fileName) and os.path.splitext(fileName)[1]=** > =".xpm": > > filedata = open(fileName) > text=filedata.readlines() > for line in text: > print line > > > Once you've tested that, then you're ready to just look at line 24. > > text is a list, so you can refer to line 24 as text[24] > > Or you can get lines 24-28, with text[24, 29] (look up slices in the > Python doc) > >>> print splitext.__doc__ Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'splitext' is not defined >>> print slices.__doc__ Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'slices' is not defined >>> print slices._doc_ Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'slices' is not defined Thanks, > > == > DaveA > > > -- Best Regards, lina -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110929/3ef4d0f3/attachment-0001.html> From tim at akwebsoft.com Thu Sep 29 17:53:08 2011 From: tim at akwebsoft.com (Tim Johnson) Date: Thu, 29 Sep 2011 07:53:08 -0800 Subject: [Tutor] Mac IDE In-Reply-To: <CAPM86NcVKyzcYp9DbOc5q+wvLU87uHDyxd0oP+w5W5hmR5CzKA@mail.gmail.com> References: <61310E38B60C8F4AB59757E88A3C967723F3021237@UMDAC-CCR2.ad.umu.se> <CANLXbfAx=2Ths9HanDXZ0MEKN9nVTGtz42XGoRhGEOB3bZrZog@mail.gmail.com> <CAPM86NcVKyzcYp9DbOc5q+wvLU87uHDyxd0oP+w5W5hmR5CzKA@mail.gmail.com> Message-ID: <20110929155308.GX19422@johnsons-web.com> * Wayne Werner <waynejwerner at gmail.com> [110929 03:52]: > > My personal favorite? > > Two terminal windows - one with Vim, editing my Python scripts, and another > with an interactive interpreter. Since you can map keys in Vim, I have <F5> > mapped to save and run current file. If you're in the habit of editing > multiple files you could set it up to map <F5> to ask which file you want to > set as your main .py file. And since you mentioned debug, I usually just use > pdb if I need debugging. You could easily map a key such as <F9> to insert a > new line and type 'pdb.set_trace()'. Vim has a fairly steep learning curve, > but if you spend 30 minutes with the vimtutor you'll be fine. With newer > versions of Vim you can also write plugins for them in Python. I'll second that. Vim (not vi - more on that later) is my IDE. I have customized it using vimscript and what I have is as feature - rich as any out-of-the-box IDE - but with differences. > Of course these capabilities (and many many more) are available with Emacs. I used Emacs extensively in the past. Vim is my preference, but emacs has a feature that is not present (yet) in vim : the ability to run interpreters - as an example the terminal shell and the python - asynchronously inside of the application. This is a very handy feature, eliminating the second application window. > I personally recommend that you learn one (or both) of these editors. They > will highly improve the speed at which you are able to edit your code. I would not wish vim or emacs on anyone who doesn't wish to use them. But for someone with an open mind, some points : . 'vim' is not 'vi', but is 'descended from' vi. . There is 'vim' - teminal mode and 'gvim' - vim with gui. I use vim as my default midnight command editor, gvim as my 'IDE' . Emacs can be run in terminal mode also, with greater speed, but less features. . There are 'easy' modes available for both, enabling a new user to find themselves in a more familiar environment. . The python interpreter can be compiled into vim. On ubuntu it is the default. This gives the user the ability to customize vim using python code. . Some call emacs and vim 'arcane'. Some ridicule vim's 'modal' style of editing. Neither are arcane, they are very up to date and are a parallel way of doing things. vim modal editing is a thing of beauty. Watching a adept vim user work can be breathtaking to observe. The corollary would be that some consider python weird because it is column-sensitive. Just sayin' .... -- Tim tim at tee jay forty nine dot com or akwebsoft dot com http://www.akwebsoft.com From ramit.prasad at jpmorgan.com Thu Sep 29 17:49:53 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 29 Sep 2011 11:49:53 -0400 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: <CAG9cJmkLUcs21tOoSwJmT7uF2NmBege2MmPkA95kJvRr13+tzA@mail.gmail.com> References: <CAG9cJmnZy909vkJMi6Xdr1upc9QH8iB+LScLwDAyPpGUkoMf6A@mail.gmail.com> <4E848401.8060504@davea.name> <CAG9cJmmR_bO-UU-hPFneKT3zkSuEEOTEyE8Tgr-p3uk=fP8yFQ@mail.gmail.com> <4E848E9D.3090901@davea.name> <CAG9cJmkLUcs21tOoSwJmT7uF2NmBege2MmPkA95kJvRr13+tzA@mail.gmail.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20EB13D0@EMARC112VS01.exchad.jpmchase.net> Or you can get lines 24-28, with ?text[24, 29] ? (look up slices in the Python doc) ?>>> print splitext.__doc__ Traceback (most recent call last): ? File "<stdin>", line 1, in <module> NameError: name 'splitext' is not defined >>> print slices.__doc__ Traceback (most recent call last): ? File "<stdin>", line 1, in <module> NameError: name 'slices' is not defined >>> print slices._doc_ Traceback (most recent call last): ? File "<stdin>", line 1, in <module> NameError: name 'slices' is not defined =================================================================== I think he meant something like: http://docs.python.org/tutorial/introduction.html (see the section on strings around half way down) or http://docs.python.org/release/2.3.5/whatsnew/section-slices.html Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From wprins at gmail.com Thu Sep 29 17:57:15 2011 From: wprins at gmail.com (Walter Prins) Date: Thu, 29 Sep 2011 16:57:15 +0100 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: <CAG9cJmkLUcs21tOoSwJmT7uF2NmBege2MmPkA95kJvRr13+tzA@mail.gmail.com> References: <CAG9cJmnZy909vkJMi6Xdr1upc9QH8iB+LScLwDAyPpGUkoMf6A@mail.gmail.com> <4E848401.8060504@davea.name> <CAG9cJmmR_bO-UU-hPFneKT3zkSuEEOTEyE8Tgr-p3uk=fP8yFQ@mail.gmail.com> <4E848E9D.3090901@davea.name> <CAG9cJmkLUcs21tOoSwJmT7uF2NmBege2MmPkA95kJvRr13+tzA@mail.gmail.com> Message-ID: <CANLXbfAFVv=YAMfgWGq9+rs39_SmcYKfsf1=GCsZR+Qs5hCb8w@mail.gmail.com> Hi, On 29 September 2011 16:39, lina <lina.lastname at gmail.com> wrote: > > Or you can get lines 24-28, with text[24, 29] (look up slices in the >> Python doc) >> > Dave probably meant: text[24:29] > >>> print splitext.__doc__ > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > NameError: name 'splitext' is not defined > >>> print slices.__doc__ > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > NameError: name 'slices' is not defined > >>> print slices._doc_ > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > NameError: name 'slices' is not defined > You should probably be looking in the documentation, not trying to feed it into the interpreter. (If you want to get help on a specific entity in Python it's usually better to use the "help()" function, e.g: >>> import os.path >>> help (os.path.splitext) Help on function splitext in module ntpath: splitext(p) Split the extension from a pathname. Extension is everything from the last dot to the end, ignoring leading dots. Returns "(root, ext)"; ext may be empty. >>> Note, trying to do "help(os.path.splitext)" would not have worked before I imported the "os.path" module. (Differently put: Whatever you want to get help() on, must be known to the interpreter, so must either be built in or previously imported.) Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110929/26f0a183/attachment.html> From wprins at gmail.com Thu Sep 29 18:00:56 2011 From: wprins at gmail.com (Walter Prins) Date: Thu, 29 Sep 2011 17:00:56 +0100 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: <CAG9cJmkLUcs21tOoSwJmT7uF2NmBege2MmPkA95kJvRr13+tzA@mail.gmail.com> References: <CAG9cJmnZy909vkJMi6Xdr1upc9QH8iB+LScLwDAyPpGUkoMf6A@mail.gmail.com> <4E848401.8060504@davea.name> <CAG9cJmmR_bO-UU-hPFneKT3zkSuEEOTEyE8Tgr-p3uk=fP8yFQ@mail.gmail.com> <4E848E9D.3090901@davea.name> <CAG9cJmkLUcs21tOoSwJmT7uF2NmBege2MmPkA95kJvRr13+tzA@mail.gmail.com> Message-ID: <CANLXbfC7NnecnH4pedRn4BzdqpqwTq6_=wc4QFFbAV1Ys=nBog@mail.gmail.com> Hi, On 29 September 2011 16:39, lina <lina.lastname at gmail.com> wrote: > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > NameError: name 'slices' is not defined > Sorry I meant to include a link to relevant documentation: http://docs.python.org/tutorial/introduction.html (And apologies for forgetting to remove ther other recipients from the email. By the way, a question to the list adminstrators: why does the default reply to address for this mailing list not default to the mailing list? All my other mailing lists operate like that, it's only the Python list that's peculiar in this way... ) Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110929/309bf813/attachment.html> From lina.lastname at gmail.com Thu Sep 29 18:07:00 2011 From: lina.lastname at gmail.com (lina) Date: Fri, 30 Sep 2011 00:07:00 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: <CANLXbfAFVv=YAMfgWGq9+rs39_SmcYKfsf1=GCsZR+Qs5hCb8w@mail.gmail.com> References: <CAG9cJmnZy909vkJMi6Xdr1upc9QH8iB+LScLwDAyPpGUkoMf6A@mail.gmail.com> <4E848401.8060504@davea.name> <CAG9cJmmR_bO-UU-hPFneKT3zkSuEEOTEyE8Tgr-p3uk=fP8yFQ@mail.gmail.com> <4E848E9D.3090901@davea.name> <CAG9cJmkLUcs21tOoSwJmT7uF2NmBege2MmPkA95kJvRr13+tzA@mail.gmail.com> <CANLXbfAFVv=YAMfgWGq9+rs39_SmcYKfsf1=GCsZR+Qs5hCb8w@mail.gmail.com> Message-ID: <CAG9cJmnv0A6Bb-VN9dPpLmvQ8Zi+kVunQ=rGe5eZ-n-4Hj_MTg@mail.gmail.com> On Thu, Sep 29, 2011 at 11:57 PM, Walter Prins <wprins at gmail.com> wrote: > Hi, > > On 29 September 2011 16:39, lina <lina.lastname at gmail.com> wrote: > >> >> Or you can get lines 24-28, with text[24, 29] (look up slices in the >>> Python doc) >>> >> > Dave probably meant: text[24:29] > > > >> >>> print splitext.__doc__ >> Traceback (most recent call last): >> File "<stdin>", line 1, in <module> >> NameError: name 'splitext' is not defined >> >>> print slices.__doc__ >> Traceback (most recent call last): >> File "<stdin>", line 1, in <module> >> NameError: name 'slices' is not defined >> >>> print slices._doc_ >> Traceback (most recent call last): >> File "<stdin>", line 1, in <module> >> NameError: name 'slices' is not defined >> > > You should probably be looking in the documentation, not trying to feed it > into the interpreter. (If you want to get help on a specific entity in > Python it's usually better to use the "help()" function, e.g: > > >>> import os.path > >>> help (os.path.splitext) > Help on function splitext in module ntpath: > > splitext(p) > Split the extension from a pathname. > > Extension is everything from the last dot to the end, ignoring > leading dots. Returns "(root, ext)"; ext may be empty. > > >>> > > Note, trying to do "help(os.path.splitext)" would not have worked before I > imported the "os.path" module. (Differently put: Whatever you want to get > help() on, must be known to the interpreter, so must either be built in or > previously imported.) > > Walter > > > Thanks all for your time, I found one thing a bit weird, Here is the one: import os.path tokens=['E'] result=[] """ for fileName in os.listdir("."): if os.path.isfile(fileName) and os.path.splitext(fileName)[1]==".xpm": """ filedata = open("1.xpm") text=filedata.readlines() for line in text[23]: print line 1] $ python try2.py | wc -l 206 now changed to: for line in text[23:24]: print line 2] $ python try2.py | wc -l 2 for line in text[23:25]: print line 3] $ python try2.py | wc -l 4 the situation 1 is supposed to be 1, while it's 206, it's just tilted 90 degree of this one line, kind of split. (if I am right here). 2] is correct. 3] is supposed to be 3, right, why it's 4? and I want to check the correctness before using for line in text[23:len(text)-1]: print line I upload the 1.xpm in below link, really appreciate for the guidance. https://docs.google.com/leaf?id=0B93SVRfpVVg3NzQxNWU4ZjktNzkwZi00ZDI5LWI1YzAtZTBkZGUzNzJmNGJh&sort=name&layout=list&num=50 -- Best Regards, lina -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110930/91bba7f0/attachment-0001.html> From wprins at gmail.com Thu Sep 29 18:31:53 2011 From: wprins at gmail.com (Walter Prins) Date: Thu, 29 Sep 2011 17:31:53 +0100 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: <CAG9cJmnv0A6Bb-VN9dPpLmvQ8Zi+kVunQ=rGe5eZ-n-4Hj_MTg@mail.gmail.com> References: <CAG9cJmnZy909vkJMi6Xdr1upc9QH8iB+LScLwDAyPpGUkoMf6A@mail.gmail.com> <4E848401.8060504@davea.name> <CAG9cJmmR_bO-UU-hPFneKT3zkSuEEOTEyE8Tgr-p3uk=fP8yFQ@mail.gmail.com> <4E848E9D.3090901@davea.name> <CAG9cJmkLUcs21tOoSwJmT7uF2NmBege2MmPkA95kJvRr13+tzA@mail.gmail.com> <CANLXbfAFVv=YAMfgWGq9+rs39_SmcYKfsf1=GCsZR+Qs5hCb8w@mail.gmail.com> <CAG9cJmnv0A6Bb-VN9dPpLmvQ8Zi+kVunQ=rGe5eZ-n-4Hj_MTg@mail.gmail.com> Message-ID: <CANLXbfAd=uii__Zm4RaOo40PzK=+gG7-E_CbrAUUZnEQigv7Mw@mail.gmail.com> Hi, On 29 September 2011 17:07, lina <lina.lastname at gmail.com> wrote: > I found one thing a bit weird, Here is the one: > > import os.path > > tokens=['E'] > result=[] > > """ > for fileName in os.listdir("."): > if os.path.isfile(fileName) and os.path.splitext(fileName)[1]==".xpm": > """ > filedata = open("1.xpm") > text=filedata.readlines() > for line in text[23]: > print line > > 1] $ python try2.py | wc -l > 206 > Please go and carefully study how strings, lists etc work -- you don't seem to grasp what "text[23]" returns vs what text[23:24] etc returns etc. To spell it out: If the variable text refers to a list of strings, then text[23] is the 24th string. 24th, because the index starts from 0. text[23:24] by contrast, is a sublist (called a slice) that contains strings 24 and 25 from the original list. So, if text[23] is already itself a single string, what can the following code possibly mean? Eg in general, what does s[0] give you if s is a string? A: The first character in s. So then, what does the following do: for x in text[23]: print x a: It steps through the letters in text[23] and prints each in turn (on a new line.) So what you then do when you "wc -l" text[23], is to effectively count the number of characters in line 24.... You should probably just have run the script without the wc -l and this would've become very clear very quickly on inspecting the output. ;) The other results are similarly explainable, by examining the output. (To be exact, the lines in the sublists/slices include newline characters. When you print them seperately, you therefore end up with more lines than you think. Try "print line.strip()" to get rid of the newline. Try the following in the python interpreter: f=open('C:\\Users\\walterp\\Desktop\\1.xpm') >>> lines=f.readlines() >>> slice1=lines[23] >>> slice2=lines[23:24] >>> slice3=lines[23:25] >>> print slice1 >>> print slice2 >>> print slice3 >>> print len(slice3) etc. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110929/df5a9f0f/attachment.html> From lina.lastname at gmail.com Thu Sep 29 18:39:15 2011 From: lina.lastname at gmail.com (lina) Date: Fri, 30 Sep 2011 00:39:15 +0800 Subject: [Tutor] map one file and print it out following the sequence In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20EB121E@EMARC112VS01.exchad.jpmchase.net> References: <CAG9cJmm7nR-qYR7r8B=6Ea5mRTpm2s+DyOHx-7Kkq8J9LZbvfQ@mail.gmail.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20D811A3@EMARC112VS01.exchad.jpmchase.net> <CAG9cJmkJX_b3NN2XvuBNfagUzaF+AS-Z3ULkR3nYyAi8Ob-frw@mail.gmail.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20EB121E@EMARC112VS01.exchad.jpmchase.net> Message-ID: <CAG9cJmkQo4WVNEgsKAfqpnAO4YweV+cVEDB1Bax5D+CEhV0moQ@mail.gmail.com> On Thu, Sep 29, 2011 at 10:57 PM, Prasad, Ramit <ramit.prasad at jpmorgan.com>wrote: > From: tutor-bounces+ramit.prasad=jpmorgan.com at python.org [mailto: > tutor-bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of lina > Sent: Tuesday, September 27, 2011 10:35 PM > Cc: tutor > Subject: Re: [Tutor] map one file and print it out following the sequence > > Hi, > > Thanks for both of your reply. > > File 1 is: > > 3 C 1 CUR C19 1 0.200 12.0110 > 4 CR1 1 CUR C20 1 -0.060 12.0110 > 5 HC 1 CUR H20 1 0.060 1.0080 > > File 2 is: > ATOM 2 H20 CUR 1 30.338 28.778 -6.812 1.00 0.00 > ATOM 4 C20 CUR 1 31.394 28.922 -7.039 1.00 0.00 > ATOM 5 C19 CUR 1 31.790 29.357 -8.323 1.00 0.00 > > I wish to get: > > ATOM 5 C19 CUR 1 31.790 29.357 -8.323 1.00 0.00 > ATOM 4 C20 CUR 1 31.394 28.922 -7.039 1.00 0.00 > ATOM 2 H20 CUR 1 30.338 28.778 -6.812 1.00 0.00 > > The dictionary is C19 C20 H20 sequence read from file 1 field 5. > rearrange the file 2 field 3 following the sequence of C19, C20, H20. > > Thanks. > > =================================================================== > > This is something I wrote *really* quick and is untested. Hopefully someone > on this list can spot any error I made. > > mapping={} > with open("cur.itp") as f: > for line in f.readlines(): > parts=line.strip().split() > if len(parts)==8: > mapping[parts[4]]=parts[0] > with open("processedpdb") as f: > proccessed = [ line.split() for line in f.readlines() ] > processed.sort( key=lambda x: mapping.get( x[2], 0 ) ) # use 0 to put items > without a mapping at the > # top of the file because > they are probably an error > For line in array: > print ' '.join( line ) > > I checked, :::::::::::::: proAB_processed.pdb :::::::::::::: ATOM 1 H52 CUR 1 33.502 30.958 -9.831 -0.71 -0.23 H the output added: :::::::::::::: proAB_processed.pdb :::::::::::::: without truly sorting, but I do think you understand correctly. Thanks, > > > > Ramit > > > Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology > 712 Main Street | Houston, TX 77002 > work phone: 713 - 216 - 5423 > > > This email is confidential and subject to important disclaimers and > conditions including on offers for the purchase or sale of > securities, accuracy and completeness of information, viruses, > confidentiality, legal privilege, and legal entity disclaimers, > available at http://www.jpmorgan.com/pages/disclosures/email. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Best Regards, lina -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110930/12cb3a47/attachment.html> From lina.lastname at gmail.com Thu Sep 29 18:51:10 2011 From: lina.lastname at gmail.com (lina) Date: Fri, 30 Sep 2011 00:51:10 +0800 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: <CANLXbfAd=uii__Zm4RaOo40PzK=+gG7-E_CbrAUUZnEQigv7Mw@mail.gmail.com> References: <CAG9cJmnZy909vkJMi6Xdr1upc9QH8iB+LScLwDAyPpGUkoMf6A@mail.gmail.com> <4E848401.8060504@davea.name> <CAG9cJmmR_bO-UU-hPFneKT3zkSuEEOTEyE8Tgr-p3uk=fP8yFQ@mail.gmail.com> <4E848E9D.3090901@davea.name> <CAG9cJmkLUcs21tOoSwJmT7uF2NmBege2MmPkA95kJvRr13+tzA@mail.gmail.com> <CANLXbfAFVv=YAMfgWGq9+rs39_SmcYKfsf1=GCsZR+Qs5hCb8w@mail.gmail.com> <CAG9cJmnv0A6Bb-VN9dPpLmvQ8Zi+kVunQ=rGe5eZ-n-4Hj_MTg@mail.gmail.com> <CANLXbfAd=uii__Zm4RaOo40PzK=+gG7-E_CbrAUUZnEQigv7Mw@mail.gmail.com> Message-ID: <CAG9cJmnURhPRKZrRCs5Rnwy6501d1JUH2o6BZdJ7B6ky3GkgLA@mail.gmail.com> On Fri, Sep 30, 2011 at 12:31 AM, Walter Prins <wprins at gmail.com> wrote: > Hi, > > On 29 September 2011 17:07, lina <lina.lastname at gmail.com> wrote: > >> I found one thing a bit weird, Here is the one: >> >> import os.path >> >> tokens=['E'] >> result=[] >> >> """ >> for fileName in os.listdir("."): >> if os.path.isfile(fileName) and os.path.splitext(fileName)[1]==".xpm": >> """ >> filedata = open("1.xpm") >> text=filedata.readlines() >> for line in text[23]: >> print line >> > >> 1] $ python try2.py | wc -l >> 206 >> > > Please go and carefully study how strings, lists etc work -- you don't seem > to grasp what "text[23]" returns vs what text[23:24] etc returns etc. To > spell it out: If the variable text refers to a list of strings, then > text[23] is the 24th string. 24th, because the index starts from 0. > text[23:24] by contrast, is a sublist (called a slice) that contains strings > 24 and 25 from the original list. > > So, if text[23] is already itself a single string, what can the following > code possibly mean? Eg in general, what does s[0] give you if s is a > string? A: The first character in s. So then, what does the following do: > > for x in text[23]: > print x > > a: It steps through the letters in text[23] and prints each in turn (on a > new line.) > > So what you then do when you "wc -l" text[23], is to effectively count the > number of characters in line 24.... > > You should probably just have run the script without the wc -l and this > would've become very clear very quickly on inspecting the output. ;) > > The other results are similarly explainable, by examining the output. (To > be exact, the lines in the sublists/slices include newline characters. When > you print them seperately, you therefore end up with more lines than you > think. Try "print line.strip()" to get rid of the newline. Try the > following in the python interpreter: > > f=open('C:\\Users\\walterp\\Desktop\\1.xpm') > >>> lines=f.readlines() > >>> slice1=lines[23] > >>> slice2=lines[23:24] > >>> slice3=lines[23:25] > >>> print slice1 > >>> print slice2 > >>> print slice3 > >>> print len(slice3) > Thanks, I truly understand now. There was a "blank line", and the strip() works. (I learned C 10 years ago, but barely used. so can understand something very basic. Thanks again for your explaination) Now I am facing how to read each column about the occurence of some letter. Long time ago, my senior left me a script with the following line, for line in text: result.append({t:line.count(t) for t in tokens}) for index,r in enumerate(result): print(index,"-----",r) I don't understand how it works, kinda of transpose a matrix? > etc. > > > Walter > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Best Regards, lina -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110930/105c7658/attachment-0001.html> From alan.gauld at btinternet.com Thu Sep 29 18:57:24 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 29 Sep 2011 17:57:24 +0100 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: <CAG9cJmnZy909vkJMi6Xdr1upc9QH8iB+LScLwDAyPpGUkoMf6A@mail.gmail.com> References: <CAG9cJmnZy909vkJMi6Xdr1upc9QH8iB+LScLwDAyPpGUkoMf6A@mail.gmail.com> Message-ID: <j6281k$82i$1@dough.gmane.org> On 29/09/11 15:22, lina wrote: > I want to read a bunch of *.doc file in present working directory, What format are the doc files? If they are word processor files they may well be in binary format so you will need to either decode them (using struct?) or find a module that can read them, or a tool that can convert them to something you can read. Once you figure out how to read a single file reading multiple files can be done in a number of ways including using os.walk() and a for loop (or the fileinput module). for root,dirs,files in os.walk(path): docs = [f for f in files if f.endswith '.doc'] # or use glob for line in fileinput.input(docs): #process line But the hardest bit is likely going to be the reading of the files if they are not plain text. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Sep 29 19:12:18 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 29 Sep 2011 18:12:18 +0100 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: <CANLXbfC7NnecnH4pedRn4BzdqpqwTq6_=wc4QFFbAV1Ys=nBog@mail.gmail.com> References: <CAG9cJmnZy909vkJMi6Xdr1upc9QH8iB+LScLwDAyPpGUkoMf6A@mail.gmail.com> <4E848401.8060504@davea.name> <CAG9cJmmR_bO-UU-hPFneKT3zkSuEEOTEyE8Tgr-p3uk=fP8yFQ@mail.gmail.com> <4E848E9D.3090901@davea.name> <CAG9cJmkLUcs21tOoSwJmT7uF2NmBege2MmPkA95kJvRr13+tzA@mail.gmail.com> <CANLXbfC7NnecnH4pedRn4BzdqpqwTq6_=wc4QFFbAV1Ys=nBog@mail.gmail.com> Message-ID: <j628tj$enq$1@dough.gmane.org> On 29/09/11 17:00, Walter Prins wrote: > email. By the way, a question to the list adminstrators: why does the > default reply to address for this mailing list not default to the > mailing list? This is an oft debated issue and there are arguments for both options. The current setup allows easier replies to either originator or list by simply selecting which Reply button you use. If you set default reply to the list how do you reply to just the originator when you want to? OTOH if your mail tool doesn't have a ReplyAll button its slightly less convenient. The upshot of all the debates (see the archive!) has been that it is the way it was set up so that's the way it is. > All my other mailing lists operate like that, it's only > the Python list that's peculiar in this way... ) I'm the opposite, all my lists work this way. I think the older lists tend to work like Python because all the older list managers (eg listserv etc) tend to work thataway. With the advent of web mail systems lists seem to be swinging the other way, but most of my mailing lists pre-date the web by a long way! :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Sep 29 19:21:55 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 29 Sep 2011 18:21:55 +0100 Subject: [Tutor] Mac IDE In-Reply-To: <CAPM86NcVKyzcYp9DbOc5q+wvLU87uHDyxd0oP+w5W5hmR5CzKA@mail.gmail.com> References: <61310E38B60C8F4AB59757E88A3C967723F3021237@UMDAC-CCR2.ad.umu.se> <CANLXbfAx=2Ths9HanDXZ0MEKN9nVTGtz42XGoRhGEOB3bZrZog@mail.gmail.com> <CAPM86NcVKyzcYp9DbOc5q+wvLU87uHDyxd0oP+w5W5hmR5CzKA@mail.gmail.com> Message-ID: <j629fj$iuf$1@dough.gmane.org> On 29/09/11 12:50, Wayne Werner wrote: > Two terminal windows - one with Vim, editing my Python scripts, and > another with an interactive interpreter.... > > Of course these capabilities (and many many more) are available with Emacs. > > I personally recommend that you learn one (or both) of these editors. > They will highly improve the speed at which you are able to edit your code. Unfortunately vim isn't available by default on MAcOS - at least not the last time I looked. They had elvis installed as a "vi". But Emacs is there in console mode, I think you need to install X to get it in GUI mode - in which case you might as well install Emacs for Aqua... But I haven't used the most recent OS X releases (post Tiger) (I'm still on a G3 iBook!) so the tool selection may have changed. Netbeans is another option that works on a Mac. There is a plugin for Python. From memory this includes an interpreter window. Finally, I can also add that the native MacOS developer tools, including XCode work with Python, but it doesn't include an integrated interpreter. You need to install/configure XCode to work with Python, visit the Mac Python pages for details. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From ramit.prasad at jpmorgan.com Thu Sep 29 19:51:52 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 29 Sep 2011 13:51:52 -0400 Subject: [Tutor] map one file and print it out following the sequence In-Reply-To: <CAG9cJmkQo4WVNEgsKAfqpnAO4YweV+cVEDB1Bax5D+CEhV0moQ@mail.gmail.com> References: <CAG9cJmm7nR-qYR7r8B=6Ea5mRTpm2s+DyOHx-7Kkq8J9LZbvfQ@mail.gmail.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20D811A3@EMARC112VS01.exchad.jpmchase.net> <CAG9cJmkJX_b3NN2XvuBNfagUzaF+AS-Z3ULkR3nYyAi8Ob-frw@mail.gmail.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20EB121E@EMARC112VS01.exchad.jpmchase.net> <CAG9cJmkQo4WVNEgsKAfqpnAO4YweV+cVEDB1Bax5D+CEhV0moQ@mail.gmail.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20EB172A@EMARC112VS01.exchad.jpmchase.net> >For line in array: >? ?print ' '.join( line ) Sorry this it should be: for line in processed: print ' '.join( line ) This worked for me. >>> pprint.pprint( processed) # Note in the email I have changed the format but not the data [['ATOM', '2', 'H20', 'CUR', '1', '30.338', '28.778', '-6.812', '1.00', '0.00'], ['ATOM', '4', 'C20', 'CUR', '1', '31.394', '28.922', '-7.039', '1.00', '0.00'], ['ATOM', '5', 'C19', 'CUR', '1', '31.790', '29.357', '-8.323', '1.00', '0.00']] >>> pprint.pprint( sorted( processed, key= lambda x: mapping.get( x[2], 0 ) ) ) # I use sorted instead of processed in case it did not sort correctly (that way I still have the original list) [['ATOM', '5', 'C19', 'CUR', '1', '31.790', '29.357', '-8.323', '1.00', '0.00'], ['ATOM', '4', 'C20', 'CUR', '1', '31.394', '28.922', '-7.039', '1.00', '0.00'], ['ATOM', '2', 'H20', 'CUR', '1', '30.338', '28.778', '-6.812', '1.00', '0.00']] You should note, that I just used "print" I did not write to file. You will need to actually create/open a file, run through the list (e.g. processed) and write to the file, and then finally close it. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 From: tutor-bounces+ramit.prasad=jpmorgan.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of lina Sent: Thursday, September 29, 2011 11:39 AM To: tutor Subject: Re: [Tutor] map one file and print it out following the sequence This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From ramit.prasad at jpmorgan.com Thu Sep 29 20:01:28 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 29 Sep 2011 14:01:28 -0400 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: <j628tj$enq$1@dough.gmane.org> References: <CAG9cJmnZy909vkJMi6Xdr1upc9QH8iB+LScLwDAyPpGUkoMf6A@mail.gmail.com> <4E848401.8060504@davea.name> <CAG9cJmmR_bO-UU-hPFneKT3zkSuEEOTEyE8Tgr-p3uk=fP8yFQ@mail.gmail.com> <4E848E9D.3090901@davea.name> <CAG9cJmkLUcs21tOoSwJmT7uF2NmBege2MmPkA95kJvRr13+tzA@mail.gmail.com> <CANLXbfC7NnecnH4pedRn4BzdqpqwTq6_=wc4QFFbAV1Ys=nBog@mail.gmail.com> <j628tj$enq$1@dough.gmane.org> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20EB1767@EMARC112VS01.exchad.jpmchase.net> >This is an oft debated issue and there are arguments for both options. >The current setup allows easier replies to either originator or list by >simply selecting which Reply button you use. If you set default reply to >the list how do you reply to just the originator when you want to? I would have preferred it to set the list as the TO and the originator as the reply CC. Not sure if that works with the email standards if it just "appears" to work that way from Outlook. That way I can reply by default to the list and if I want to send to the originator I can also do reply all. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From bodsda at googlemail.com Thu Sep 29 20:03:45 2011 From: bodsda at googlemail.com (bodsda at googlemail.com) Date: Thu, 29 Sep 2011 18:03:45 +0000 Subject: [Tutor] where to look for python codes In-Reply-To: <CAJcoiztHOBAwu8fiB7ZCQ+HFw9H93uTpRcxE_ZGweSV_9j=Buw@mail.gmail.com> References: <CAJcoiztHOBAwu8fiB7ZCQ+HFw9H93uTpRcxE_ZGweSV_9j=Buw@mail.gmail.com> Message-ID: <621996491-1317319427-cardhu_decombobulator_blackberry.rim.net-825542263-@b28.c12.bise7.blackberry> I would suggest looking on http://ubuntuforums.org for the ?Beginner programming challenges? - there is an index of past challenges as a sticky in the programming talk subforum. A large number of entries for these challenges are in python, and as the name implies, the submissions are usually written by beginners. The code will not be enterprise standard, but it should be a good insight into how others write python programs Hope this helps, Bodsda, Ubuntu beginners team P.S: sorry for the top post, smartphone limitation Sent from my BlackBerry? wireless device -----Original Message----- From: Praveen Singh <c2praveen30jun at gmail.com> Sender: tutor-bounces+bodsda=googlemail.com at python.org Date: Thu, 29 Sep 2011 13:57:46 To: <tutor at python.org> Subject: [Tutor] where to look for python codes _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From robert.johansson at math.umu.se Thu Sep 29 20:30:27 2011 From: robert.johansson at math.umu.se (Robert Johansson) Date: Thu, 29 Sep 2011 20:30:27 +0200 Subject: [Tutor] Mac IDE In-Reply-To: <CAGymF1CP4YU_4M-3iTOBLLXJjpYQ4Xgzfdkkm78p6TJ85D-+2A@mail.gmail.com> References: <61310E38B60C8F4AB59757E88A3C967723F3021237@UMDAC-CCR2.ad.umu.se> <CANLXbfAx=2Ths9HanDXZ0MEKN9nVTGtz42XGoRhGEOB3bZrZog@mail.gmail.com> <CAPM86NcVKyzcYp9DbOc5q+wvLU87uHDyxd0oP+w5W5hmR5CzKA@mail.gmail.com> <CAGymF1CP4YU_4M-3iTOBLLXJjpYQ4Xgzfdkkm78p6TJ85D-+2A@mail.gmail.com> Message-ID: <61310E38B60C8F4AB59757E88A3C967723F3021295@UMDAC-CCR2.ad.umu.se> Wing IDE looks promising on my windows machine. I will start by checking out their trial under OSX. Thanks for all suggestions, Robert Fr?n: tutor-bounces+robert.johansson=math.umu.se at python.org [mailto:tutor-bounces+robert.johansson=math.umu.se at python.org] F?r Tom Tucker Skickat: den 29 september 2011 16:44 Till: Wayne Werner Kopia: tutor at python.org ?mne: Re: [Tutor] Mac IDE Another IDE to consider that supports the MAC OS is PyCharm from JetBrains. On Thu, Sep 29, 2011 at 7:50 AM, Wayne Werner <waynejwerner at gmail.com<mailto:waynejwerner at gmail.com>> wrote: On Thu, Sep 29, 2011 at 5:50 AM, Walter Prins <wprins at gmail.com<mailto:wprins at gmail.com>> wrote: On 29 September 2011 10:42, Robert Johansson <robert.johansson at math.umu.se<mailto:robert.johansson at math.umu.se>> wrote: Hi, I know that there is a lot to read about different IDEs on the net but I have tried a couple and I'm still not pleased. My demands are not that high, when I'm under Windows I'm happy with IDLE (an interactive shell and debug) but the problem is with Mac (Python >= 2.7 and OS 10.7). IDLE had serious problems and TextWrangler had no interactive shell. There's a lot of other stuff to try and I would be grateful if someone could spare me some time on this. Well, if you're prepared to spend a bit of money, I've heard very good things about Wingware, which is also available on Mac (Note, not a user myself currently, but has seen it before and been favourably impressed, enough to suggest it here despite not currently actively using it myself.) Link: http://wingware.com/ I'll second that. If you're really into IDEs, Wingware is a great one - they also have a student/open source license that may be right up your alley. My personal favorite? Two terminal windows - one with Vim, editing my Python scripts, and another with an interactive interpreter. Since you can map keys in Vim, I have <F5> mapped to save and run current file. If you're in the habit of editing multiple files you could set it up to map <F5> to ask which file you want to set as your main .py file. And since you mentioned debug, I usually just use pdb if I need debugging. You could easily map a key such as <F9> to insert a new line and type 'pdb.set_trace()'. Vim has a fairly steep learning curve, but if you spend 30 minutes with the vimtutor you'll be fine. With newer versions of Vim you can also write plugins for them in Python. Of course these capabilities (and many many more) are available with Emacs. I personally recommend that you learn one (or both) of these editors. They will highly improve the speed at which you are able to edit your code. HTH, Wayne _______________________________________________ Tutor maillist - Tutor at python.org<mailto: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: <http://mail.python.org/pipermail/tutor/attachments/20110929/f664d8f4/attachment.html> From tim at akwebsoft.com Thu Sep 29 21:01:04 2011 From: tim at akwebsoft.com (Tim Johnson) Date: Thu, 29 Sep 2011 11:01:04 -0800 Subject: [Tutor] Mac IDE In-Reply-To: <j629fj$iuf$1@dough.gmane.org> References: <61310E38B60C8F4AB59757E88A3C967723F3021237@UMDAC-CCR2.ad.umu.se> <CANLXbfAx=2Ths9HanDXZ0MEKN9nVTGtz42XGoRhGEOB3bZrZog@mail.gmail.com> <CAPM86NcVKyzcYp9DbOc5q+wvLU87uHDyxd0oP+w5W5hmR5CzKA@mail.gmail.com> <j629fj$iuf$1@dough.gmane.org> Message-ID: <20110929190104.GA2683@johnsons-web.com> * Alan Gauld <alan.gauld at btinternet.com> [110929 09:29]: > On 29/09/11 12:50, Wayne Werner wrote: > > >Two terminal windows - one with Vim, editing my Python scripts, and > >another with an interactive interpreter.... > > > >Of course these capabilities (and many many more) are available with Emacs. > > > >I personally recommend that you learn one (or both) of these editors. > >They will highly improve the speed at which you are able to edit your code. > > Unfortunately vim isn't available by default on MAcOS - at least not > the last time I looked. They had elvis installed as a "vi". > > But Emacs is there in console mode, I think you need to install X to > get it in GUI mode - in which case you might as well install Emacs > for Aqua... I just got a 2011 mac mini with the last OS ... time doesn't permit me to fire it up until tomorrow at the soonest, but I will report back on emacs and vim as defaults. A distribution call macvim is available and vim can also be custom built. cheers -- Tim tim at tee jay forty nine dot com or akwebsoft dot com http://www.akwebsoft.com From wprins at gmail.com Thu Sep 29 21:10:52 2011 From: wprins at gmail.com (Walter Prins) Date: Thu, 29 Sep 2011 20:10:52 +0100 Subject: [Tutor] a quick Q: how to use for loop to read a series of files with .doc end In-Reply-To: <j628tj$enq$1@dough.gmane.org> References: <CAG9cJmnZy909vkJMi6Xdr1upc9QH8iB+LScLwDAyPpGUkoMf6A@mail.gmail.com> <4E848401.8060504@davea.name> <CAG9cJmmR_bO-UU-hPFneKT3zkSuEEOTEyE8Tgr-p3uk=fP8yFQ@mail.gmail.com> <4E848E9D.3090901@davea.name> <CAG9cJmkLUcs21tOoSwJmT7uF2NmBege2MmPkA95kJvRr13+tzA@mail.gmail.com> <CANLXbfC7NnecnH4pedRn4BzdqpqwTq6_=wc4QFFbAV1Ys=nBog@mail.gmail.com> <j628tj$enq$1@dough.gmane.org> Message-ID: <CANLXbfDfBUUj+5WnoD6gGaz21B2DzS0=tS0iUUCMAADAsvOqNg@mail.gmail.com> Hi Alan, On 29 September 2011 18:12, Alan Gauld <alan.gauld at btinternet.com> wrote: > On 29/09/11 17:00, Walter Prins wrote: > > email. By the way, a question to the list adminstrators: why does the >> default reply to address for this mailing list not default to the >> mailing list? >> > > This is an oft debated issue and there are arguments for both options. > The current setup allows easier replies to either originator or list by > simply selecting which Reply button you use. If you set default reply to the > list how do you reply to just the originator when you want to? > Well, for that particular (comparatively rare) case, with copy and paste. (Which is in any case basically what I have to remember to do each and every time I reply to the list-only currently, assuming I've also remembered to click reply-all instead of reply...) IMHO, ideally things should work exactly as they are except that "Reply" goes to the list, "Reply-all" sends to the list as well as anyone else (which then allows copying and pasting/re-arranging of addresses etc if only some people are meant to get the response.) As I say, this would be consistent with how most other mailing lists (that I'm on anyway) works. IMHO the current default behaviour makes the most common use-case more work than it would otherwise be, but fine, if the powers that be actually want it like it is, then who am I to argue. :) > > > > All my other mailing lists operate like that, it's only > >> the Python list that's peculiar in this way... ) >> > > I'm the opposite, all my lists work this way. > I think the older lists tend to work like Python because all the > older list managers (eg listserv etc) tend to work thataway. > With the advent of web mail systems lists seem to be swinging > the other way, but most of my mailing lists pre-date the web > by a long way! :-) Yes... well I don't want to start an argument, but I can't help but point out that just because things might've in sometimes in the past been set up to work like that doesn't mean it's neccesarily the most appropriate way it should be done today, in general, or on this list in particular. But, as I say, I don't want to start an argument -- if this has been debated before (and you've just told me it has), and so has been deliberately and intentionally set to the current behaviour then that's fine. I'll not say another word about it. :) (I'll however reserve the right to have a few choice thoughts about it next time I again forget to swap around the addresses on reply-all, or when I again robotically click reply instead of reply-all when responding to this list and end up sending a reply to the person only instead of to the list and then have to go dig the reply out the sent box again and forward it on to the list manually... ;) ) Best, Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110929/b9710713/attachment-0001.html> From ramit.prasad at jpmorgan.com Thu Sep 29 21:55:34 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 29 Sep 2011 15:55:34 -0400 Subject: [Tutor] Mailing list archive oddity? Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F66B85@EMARC112VS01.exchad.jpmchase.net> So I wanted to reference a post I had already deleted and I looked at the archive (http://mail.python.org/pipermail/tutor/). My question...how do I get a future capable email client like the archive? :) Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From jeanpierreda at gmail.com Thu Sep 29 22:10:38 2011 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Thu, 29 Sep 2011 16:10:38 -0400 Subject: [Tutor] Mailing list archive oddity? In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F66B85@EMARC112VS01.exchad.jpmchase.net> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F66B85@EMARC112VS01.exchad.jpmchase.net> Message-ID: <CABicbJ+6cCVJO3icSmADz=960bMU27QSULX7TGQHdCjJ3zeCXA@mail.gmail.com> > So I wanted to reference a post I had already deleted and I looked at the archive (http://mail.python.org/pipermail/tutor/). > > My question...how do I get a future capable email client like the archive? :) What mail client do you use? Does it offer a way to move posts out of the inbox, without deleting them? That's what I do, but I use gmail. Devin On Thu, Sep 29, 2011 at 3:55 PM, Prasad, Ramit <ramit.prasad at jpmorgan.com> wrote: > So I wanted to reference a post I had already deleted and I looked at the archive (http://mail.python.org/pipermail/tutor/). > > My question...how do I get a future capable email client like the archive? :) > > Ramit > > > Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology > 712 Main Street | Houston, TX 77002 > work phone: 713 - 216 - 5423 > > > > This email is confidential and subject to important disclaimers and > conditions including on offers for the purchase or sale of > securities, accuracy and completeness of information, viruses, > confidentiality, legal privilege, and legal entity disclaimers, > available at http://www.jpmorgan.com/pages/disclosures/email. > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From ramit.prasad at jpmorgan.com Thu Sep 29 22:25:30 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 29 Sep 2011 16:25:30 -0400 Subject: [Tutor] Mailing list archive oddity? In-Reply-To: <CABicbJ+6cCVJO3icSmADz=960bMU27QSULX7TGQHdCjJ3zeCXA@mail.gmail.com> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F66B85@EMARC112VS01.exchad.jpmchase.net> <CABicbJ+6cCVJO3icSmADz=960bMU27QSULX7TGQHdCjJ3zeCXA@mail.gmail.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F66C36@EMARC112VS01.exchad.jpmchase.net> -----Original Message----- From: Devin Jeanpierre [mailto:jeanpierreda at gmail.com] Sent: Thursday, September 29, 2011 3:11 PM To: Prasad, Ramit Cc: tutor at python.org Subject: Re: [Tutor] Mailing list archive oddity? > So I wanted to reference a post I had already deleted and I looked at the archive (http://mail.python.org/pipermail/tutor/). > > My question...how do I get a future capable email client like the archive? :) What mail client do you use? Does it offer a way to move posts out of the inbox, without deleting them? That's what I do, but I use gmail. Devin -------------------------------------------------------------------------- I think you misunderstood my question. The web archive of the list has a few entries that have not occurred yet (which you may have noticed if you visited the link). January 2027: [ Thread ] [ Subject ] [ Author ] [ Date ] [ Gzip'd Text 597 bytes ] November 2012: [ Thread ] [ Subject ] [ Author ] [ Date ] [ Gzip'd Text 2 KB ] I was asking (facetiously) if there was an email client that could receive email from the future. I am curious to how this happened, but I am not sure anyone on this list is a list administrator and would know. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From jeanpierreda at gmail.com Thu Sep 29 22:48:54 2011 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Thu, 29 Sep 2011 16:48:54 -0400 Subject: [Tutor] Mailing list archive oddity? In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F66C36@EMARC112VS01.exchad.jpmchase.net> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F66B85@EMARC112VS01.exchad.jpmchase.net> <CABicbJ+6cCVJO3icSmADz=960bMU27QSULX7TGQHdCjJ3zeCXA@mail.gmail.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F66C36@EMARC112VS01.exchad.jpmchase.net> Message-ID: <CABicbJKEU4DAMTt80YMQT_FhYeONUUyg=yi2FUnbKz337nd1VQ@mail.gmail.com> > I think you misunderstood my question. The web archive of the list has a few entries that have not occurred yet (which you may have noticed if you visited the link). Ah. I have an unfortunate medical condition where I only click hyperlinks when they don't matter. Devin On Thu, Sep 29, 2011 at 4:25 PM, Prasad, Ramit <ramit.prasad at jpmorgan.com> wrote: > -----Original Message----- > From: Devin Jeanpierre [mailto:jeanpierreda at gmail.com] > Sent: Thursday, September 29, 2011 3:11 PM > To: Prasad, Ramit > Cc: tutor at python.org > Subject: Re: [Tutor] Mailing list archive oddity? > >> So I wanted to reference a post I had already deleted and I looked at the archive (http://mail.python.org/pipermail/tutor/). >> >> My question...how do I get a future capable email client like the archive? :) > > What mail client do you use? Does it offer a way to move posts out of > the inbox, without deleting them? > > That's what I do, but I use gmail. > > Devin > > -------------------------------------------------------------------------- > > I think you misunderstood my question. The web archive of the list has a few entries that have not occurred yet (which you may have noticed if you visited the link). > > January 2027: ? [ Thread ] [ Subject ] [ Author ] [ Date ] ? ? ?[ Gzip'd Text 597 bytes ] > November 2012: ?[ Thread ] [ Subject ] [ Author ] [ Date ] ? ? ?[ Gzip'd Text 2 KB ] > > I was asking (facetiously) if there was an email client that could receive email from the future. I am curious to how this happened, but I am not sure anyone on this list is a list administrator and would know. > > Ramit > > > Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology > 712 Main Street | Houston, TX 77002 > work phone: 713 - 216 - 5423 > > > > > This email is confidential and subject to important disclaimers and > conditions including on offers for the purchase or sale of > securities, accuracy and completeness of information, viruses, > confidentiality, legal privilege, and legal entity disclaimers, > available at http://www.jpmorgan.com/pages/disclosures/email. > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From hugo.yoshi at gmail.com Thu Sep 29 23:08:19 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Thu, 29 Sep 2011 23:08:19 +0200 Subject: [Tutor] Mailing list archive oddity? In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F66C36@EMARC112VS01.exchad.jpmchase.net> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F66B85@EMARC112VS01.exchad.jpmchase.net> <CABicbJ+6cCVJO3icSmADz=960bMU27QSULX7TGQHdCjJ3zeCXA@mail.gmail.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F66C36@EMARC112VS01.exchad.jpmchase.net> Message-ID: <CAJmBOf=Jqdk9_oYJk3PQRE2hLnvX5oFJifNX228gFXMVnojW_g@mail.gmail.com> On Thu, Sep 29, 2011 at 10:25 PM, Prasad, Ramit <ramit.prasad at jpmorgan.com> wrote: > > I think you misunderstood my question. The web archive of the list has a few entries that have not occurred yet (which you may have noticed if you visited the link). > > January 2027: ? [ Thread ] [ Subject ] [ Author ] [ Date ] ? ? ?[ Gzip'd Text 597 bytes ] > November 2012: ?[ Thread ] [ Subject ] [ Author ] [ Date ] ? ? ?[ Gzip'd Text 2 KB ] > > I was asking (facetiously) if there was an email client that could receive email from the future. I am curious to how this happened, but I am not sure anyone on this list is a list administrator and would know. > > Ramit > In fact, every e-mail client is technically capable of receiving messages from the future! Unfortunately, there are as of this writing no clients that can send messages into the past :( The archives go by the date header found in the e-mail. This is supposed to indicate the time that the e-mail was sent. So we are left with two options: * someone from the future is in need of python help and is sending messages back in time. * someone has their system clock set wrong. Hugo From quasipedia at gmail.com Thu Sep 29 23:29:13 2011 From: quasipedia at gmail.com (Mac Ryan) Date: Thu, 29 Sep 2011 23:29:13 +0200 Subject: [Tutor] Mailing list archive oddity? In-Reply-To: <CAJmBOf=Jqdk9_oYJk3PQRE2hLnvX5oFJifNX228gFXMVnojW_g@mail.gmail.com> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F66B85@EMARC112VS01.exchad.jpmchase.net> <CABicbJ+6cCVJO3icSmADz=960bMU27QSULX7TGQHdCjJ3zeCXA@mail.gmail.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F66C36@EMARC112VS01.exchad.jpmchase.net> <CAJmBOf=Jqdk9_oYJk3PQRE2hLnvX5oFJifNX228gFXMVnojW_g@mail.gmail.com> Message-ID: <20110929232913.7dce6183@jabbar> On Thu, 29 Sep 2011 23:08:19 +0200 Hugo Arts <hugo.yoshi at gmail.com> wrote: > * someone from the future is in need of python help and is sending > messages back in time. I told Guido that Python version 5.2 sucked, but he wouldn't / will not listen! :-/ /mac From carroll at tjc.com Thu Sep 29 23:18:49 2011 From: carroll at tjc.com (Terry Carroll) Date: Thu, 29 Sep 2011 14:18:49 -0700 (PDT) Subject: [Tutor] Mailing list archive oddity? In-Reply-To: <CAJmBOf=Jqdk9_oYJk3PQRE2hLnvX5oFJifNX228gFXMVnojW_g@mail.gmail.com> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F66B85@EMARC112VS01.exchad.jpmchase.net> <CABicbJ+6cCVJO3icSmADz=960bMU27QSULX7TGQHdCjJ3zeCXA@mail.gmail.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F66C36@EMARC112VS01.exchad.jpmchase.net> <CAJmBOf=Jqdk9_oYJk3PQRE2hLnvX5oFJifNX228gFXMVnojW_g@mail.gmail.com> Message-ID: <alpine.LRH.2.00.1109291418240.20049@aqua.rahul.net> On Thu, 29 Sep 2011, Hugo Arts wrote: > * someone from the future is in need of python help and is sending > messages back in time. I'm betting this is Guido and his time machine again. From fsalamero at gmail.com Fri Sep 30 07:12:23 2011 From: fsalamero at gmail.com (Fernando Salamero) Date: Fri, 30 Sep 2011 07:12:23 +0200 Subject: [Tutor] Mac IDE In-Reply-To: <mailman.7476.1317312422.27777.tutor@python.org> References: <mailman.7476.1317312422.27777.tutor@python.org> Message-ID: <2E3A2033-79E1-421D-BBD9-1A71EEC69700@gmail.com> Another great IDE is NINJA-IDE, http://www.ninja-ide.org , but they are still searching for somebody who makes an installer. Any volunteer? From kellyadrian at hotmail.com Fri Sep 30 14:04:58 2011 From: kellyadrian at hotmail.com (ADRIAN KELLY) Date: Fri, 30 Sep 2011 12:04:58 +0000 Subject: [Tutor] guess age programme (please help) Message-ID: <DUB103-W50F578DDCA31182EA255DCA9F70@phx.gbl> Hi all, can anyone help me with the attached programme. it is fairly basic (like me) i want it to ask the user to guess the age and countdown when making incorrect guesses. it doesn't seem to count the first attempt (run it and see please). i also want to know how to go about setting a condition so that when the guesses = 0, the programme closes or stops etc. any advice would be very grateful (particularly the correct code) i am learning if's and loops so please keep explanations as simple as possible. i really appreciate everyones help adrian -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110930/7fbf6ce6/attachment.html> -------------- next part -------------- A non-text attachment was scrubbed... Name: guess age_game(broken) Type: application/octet-stream Size: 601 bytes Desc: not available URL: <http://mail.python.org/pipermail/tutor/attachments/20110930/7fbf6ce6/attachment.obj> From bodsda at googlemail.com Fri Sep 30 14:17:56 2011 From: bodsda at googlemail.com (bodsda at googlemail.com) Date: Fri, 30 Sep 2011 12:17:56 +0000 Subject: [Tutor] guess age programme (please help) In-Reply-To: <DUB103-W50F578DDCA31182EA255DCA9F70@phx.gbl> References: <DUB103-W50F578DDCA31182EA255DCA9F70@phx.gbl> Message-ID: <1915990691-1317385079-cardhu_decombobulator_blackberry.rim.net-1351998710-@b28.c12.bise7.blackberry> Hi, I haven't checked your code because I am on my phone, but here is a tip for the loop condition Use the guess in your loop condition e.g. while guesses != 0: Do stuff That way, when guesses does equal 0, the loop condition will be false and therefore the loop will not run. If you don't want to do that, look into the 'break' statement. while someOtherCondition: Do stuff if guesses == 0: break Hope this helps, Bodsda Sent from my BlackBerry? wireless device -----Original Message----- From: ADRIAN KELLY <kellyadrian at hotmail.com> Sender: tutor-bounces+bodsda=googlemail.com at python.org Date: Fri, 30 Sep 2011 12:04:58 To: <tutor at python.org> Subject: [Tutor] guess age programme (please help) _______________________________________________ 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 Fri Sep 30 14:31:52 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Fri, 30 Sep 2011 14:31:52 +0200 Subject: [Tutor] guess age programme (please help) In-Reply-To: <DUB103-W50F578DDCA31182EA255DCA9F70@phx.gbl> References: <DUB103-W50F578DDCA31182EA255DCA9F70@phx.gbl> Message-ID: <4E85B6B8.60907@compuscan.co.za> On 2011/09/30 02:04 PM, ADRIAN KELLY wrote: > Hi all, > can anyone help me with the attached programme. it is fairly basic > (like me) i want it to ask the user to guess the age and countdown > when making incorrect guesses. it doesn't seem to count the first > attempt (run it and see please). i also want to know how to go about > setting a condition so > that when the guesses = 0, the programme closes or stops etc. > any advice would be very grateful (particularly the correct code) i am > learning if's and loops so please keep explanations as > simple as possible. > > i really appreciate everyones help > > adrian > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Your program does count the first guess, but you print out the remaining number of tries before you subtract the attempt from your counter so if you move your `tries=tries-1` up before your if statements it will reflect the correct number of attempts left to the user. I would suggest changing your while loop to read `while tries > 0:` so it exits when you've exhausted your attempts. You also do not test for equality of your age and the guess in your if statements so if the user guesses the correct age it will tell them that the number is higher. And if the user guesses the correct number you should `break` from the loop else it will carry on going till the number of attempts have been exhausted. -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110930/0c45fbc4/attachment.html> From kellyadrian at hotmail.com Fri Sep 30 21:18:15 2011 From: kellyadrian at hotmail.com (ADRIAN KELLY) Date: Fri, 30 Sep 2011 19:18:15 +0000 Subject: [Tutor] guess age programme (still stuck!!!!!) In-Reply-To: <4E85B6B8.60907@compuscan.co.za> References: <DUB103-W50F578DDCA31182EA255DCA9F70@phx.gbl>, <4E85B6B8.60907@compuscan.co.za> Message-ID: <DUB103-W52622E7E2119510CE5F830A9F70@phx.gbl> please guys still stuck on this problem and i have been at it for hours so please if anyone can help. it nearly works. am i looking at it from the wrong angle? i have tried everyone's suggestions but i am stuck still... correct code would be nice............. thanksadrian (new pythoner) print("\tWelcome to 'Guess My Number'!")print("I'm thinking of a number between 1 and 100.")print("Try to guess it in as few attempts as possible.\n") # set the initial valuesage = 35guess = " "tries = 5 # guessing loopwhile guess!=age and tries>0: tries=tries-1 guess = input("Take a guess: ") if guess > age and tries>0: print "Lower...",tries,"left" elif guess < age and tries>0: print "Higher...",tries,"left" elif guess == age and tries>0: print "Correct...well done!!" else: break print "Out of attempts" print "\n\nGood guess!!" input ("\n\nPress the enter key to exit.") Date: Fri, 30 Sep 2011 14:31:52 +0200 From: cwitts at compuscan.co.za To: kellyadrian at hotmail.com CC: tutor at python.org Subject: Re: [Tutor] guess age programme (please help) On 2011/09/30 02:04 PM, ADRIAN KELLY wrote: Hi all, can anyone help me with the attached programme. it is fairly basic (like me) i want it to ask the user to guess the age and countdown when making incorrect guesses. it doesn't seem to count the first attempt (run it and see please). i also want to know how to go about setting a condition so that when the guesses = 0, the programme closes or stops etc. any advice would be very grateful (particularly the correct code) i am learning if's and loops so please keep explanations as simple as possible. i really appreciate everyones help adrian _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Your program does count the first guess, but you print out the remaining number of tries before you subtract the attempt from your counter so if you move your `tries=tries-1` up before your if statements it will reflect the correct number of attempts left to the user. I would suggest changing your while loop to read `while tries > 0:` so it exits when you've exhausted your attempts. You also do not test for equality of your age and the guess in your if statements so if the user guesses the correct age it will tell them that the number is higher. And if the user guesses the correct number you should `break` from the loop else it will carry on going till the number of attempts have been exhausted. -- Email Signature Christian Witts Python Developer -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110930/ccacdb6b/attachment-0001.html> From cmacleod170 at gmail.com Fri Sep 30 21:24:29 2011 From: cmacleod170 at gmail.com (Cameron Macleod) Date: Fri, 30 Sep 2011 20:24:29 +0100 Subject: [Tutor] Input Message-ID: <CAExoPr2qWVUhSoax33hTSkLY-325h04NN3m0A1NDiz52hkHUQA@mail.gmail.com> Hi, When you type Input("\n\nPress The Enter Key To Exit") it forces you to press the enter key to close the program. Why is it the enter key instead of e.g. the 'esc' key? -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110930/03c6007b/attachment.html> From bodsda at googlemail.com Fri Sep 30 22:05:51 2011 From: bodsda at googlemail.com (bodsda at googlemail.com) Date: Fri, 30 Sep 2011 20:05:51 +0000 Subject: [Tutor] guess age programme (still stuck!!!!!) In-Reply-To: <DUB103-W52622E7E2119510CE5F830A9F70@phx.gbl> References: <DUB103-W50F578DDCA31182EA255DCA9F70@phx.gbl>, <4E85B6B8.60907@compuscan.co.za><DUB103-W52622E7E2119510CE5F830A9F70@phx.gbl> Message-ID: <1530933565-1317413151-cardhu_decombobulator_blackberry.rim.net-1927368204-@b28.c12.bise7.blackberry> If I enter 35 at the prompt in your program, does python see this: 35 Or this: ?35? ? Hope this helps, Bodsda Sent from my BlackBerry? wireless device -----Original Message----- From: ADRIAN KELLY <kellyadrian at hotmail.com> Sender: tutor-bounces+bodsda=googlemail.com at python.org Date: Fri, 30 Sep 2011 19:18:15 To: <cwitts at compuscan.co.za> Cc: <tutor at python.org> Subject: Re: [Tutor] guess age programme (still stuck!!!!!) _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From d at davea.name Fri Sep 30 22:21:09 2011 From: d at davea.name (Dave Angel) Date: Fri, 30 Sep 2011 16:21:09 -0400 Subject: [Tutor] guess age programme (still stuck!!!!!) In-Reply-To: <DUB103-W52622E7E2119510CE5F830A9F70@phx.gbl> References: <DUB103-W50F578DDCA31182EA255DCA9F70@phx.gbl>, <4E85B6B8.60907@compuscan.co.za> <DUB103-W52622E7E2119510CE5F830A9F70@phx.gbl> Message-ID: <4E8624B5.3020305@davea.name> (Please don't top-post. Place your remarks after whatever quoting you do from the previous message. And trim the parts that are no longer relevant) On 09/30/2011 03:18 PM, ADRIAN KELLY wrote: > please guys > still stuck on this problem and i have been at it for hours so please if anyone can help. it nearly works. am i looking at it from the wrong angle? i have tried everyone's suggestions but i am stuck still... > correct code would be nice............. > thanksadrian (new pythoner) > > print("\tWelcome to 'Guess My Number'!")print("I'm thinking of a number between 1 and 100.")print("Try to guess it in as few attempts as possible.\n") > # set the initial valuesage = 35guess = " "tries = 5 > # guessing loopwhile guess!=age and tries>0: tries=tries-1 guess = input("Take a guess: ") if guess> age and tries>0: print "Lower...",tries,"left" elif guess< age and tries>0: print "Higher...",tries,"left" elif guess == age and tries>0: print "Correct...well done!!" else: break print "Out of attempts" > print "\n\nGood guess!!" > input ("\n\nPress the enter key to exit.") Please adjust your email program to text mode. Wordwrapping python source code doesn't work very well. input() returns a character string. If you want an integer, you need to use int() function. Currently you're comparing an integer 35 to a string like "4". That comparison is effectively indeterminate. (there are rules for it, but they vary by both version and implementation, so it's better to always make sure you have the same type on both sides of the comparison operator. -- DaveA From d at davea.name Fri Sep 30 22:23:12 2011 From: d at davea.name (Dave Angel) Date: Fri, 30 Sep 2011 16:23:12 -0400 Subject: [Tutor] Input In-Reply-To: <CAExoPr2qWVUhSoax33hTSkLY-325h04NN3m0A1NDiz52hkHUQA@mail.gmail.com> References: <CAExoPr2qWVUhSoax33hTSkLY-325h04NN3m0A1NDiz52hkHUQA@mail.gmail.com> Message-ID: <4E862530.2070708@davea.name> On 09/30/2011 03:24 PM, Cameron Macleod wrote: > Hi, > > When you type > > Input("\n\nPress The Enter Key To Exit") > > it forces you to press the enter key to close the program. Why is it the > enter key instead of e.g. the 'esc' key? > > The input() function (not the Input()) function accepts a line of text from the user. That line is terminated by a newline, generated by the enter key. If you're trying to just wait for an "any-key", I don't know of any portable way to do it. There is a way in Windows, however. -- DaveA From mlybrand at gmail.com Fri Sep 30 22:27:27 2011 From: mlybrand at gmail.com (Mark Lybrand) Date: Fri, 30 Sep 2011 13:27:27 -0700 Subject: [Tutor] Input In-Reply-To: <4E862530.2070708@davea.name> References: <CAExoPr2qWVUhSoax33hTSkLY-325h04NN3m0A1NDiz52hkHUQA@mail.gmail.com> <4E862530.2070708@davea.name> Message-ID: <CALsUBty-aHz789dX_Q0jETTowTtu2Kgbct0iGmvsUNozrWWoaw@mail.gmail.com> There is apparently a livewires package that may be of someuse. On Sep 30, 2011 1:25 PM, "Dave Angel" <d at davea.name> wrote: > On 09/30/2011 03:24 PM, Cameron Macleod wrote: >> Hi, >> >> When you type >> >> Input("\n\nPress The Enter Key To Exit") >> >> it forces you to press the enter key to close the program. Why is it the >> enter key instead of e.g. the 'esc' key? >> >> > > The input() function (not the Input()) function accepts a line of text > from the user. That line is terminated by a newline, generated by the > enter key. > > If you're trying to just wait for an "any-key", I don't know of any > portable way to do it. There is a way in Windows, however. > > > > -- > > DaveA > > _______________________________________________ > 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: <http://mail.python.org/pipermail/tutor/attachments/20110930/12faae31/attachment.html> From bodsda at googlemail.com Fri Sep 30 22:33:21 2011 From: bodsda at googlemail.com (bodsda at googlemail.com) Date: Fri, 30 Sep 2011 20:33:21 +0000 Subject: [Tutor] Input In-Reply-To: <CALsUBty-aHz789dX_Q0jETTowTtu2Kgbct0iGmvsUNozrWWoaw@mail.gmail.com> References: <CAExoPr2qWVUhSoax33hTSkLY-325h04NN3m0A1NDiz52hkHUQA@mail.gmail.com><4E862530.2070708@davea.name><CALsUBty-aHz789dX_Q0jETTowTtu2Kgbct0iGmvsUNozrWWoaw@mail.gmail.com> Message-ID: <1447802630-1317414800-cardhu_decombobulator_blackberry.rim.net-840780913-@b28.c12.bise7.blackberry> You could also use something like pygame to wait and test for keypresses Bodsda (Top post is phone limitation, sorry) Sent from my BlackBerry? wireless device -----Original Message----- From: Mark Lybrand <mlybrand at gmail.com> Sender: tutor-bounces+bodsda=googlemail.com at python.org Date: Fri, 30 Sep 2011 13:27:27 To: <d at davea.name> Cc: <tutor at python.org> Subject: Re: [Tutor] Input _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From anol2900 at student.su.se Thu Sep 29 21:10:46 2011 From: anol2900 at student.su.se (Anna Olofsson) Date: Thu, 29 Sep 2011 21:10:46 +0200 Subject: [Tutor] Tables Message-ID: <d52844448ab913f6805e2f51d418efb4@localhost> Hi, I'm a beginner at Python and I have tried to read the Python manual, but I still can't figure out how to extract columns from a table and then create a new table by merge these extracted tables together. Best, Anna From japhy at pearachute.com Sat Sep 24 16:51:58 2011 From: japhy at pearachute.com (Japhy Bartlett) Date: Sat, 24 Sep 2011 10:51:58 -0400 Subject: [Tutor] Infinite Loop In-Reply-To: <CAExoPr2gG8q5WFEkZB8zScuOJHH+iwhRyTOjcQCmSwFzJKi32g@mail.gmail.com> References: <CAExoPr2gG8q5WFEkZB8zScuOJHH+iwhRyTOjcQCmSwFzJKi32g@mail.gmail.com> Message-ID: <CANTsVHKEijKsC=NU42N1yXtKbjsmOUgBB9UqA+Ht4udJgNm8Xw@mail.gmail.com> If the guess is larger than the number, your code will never prompt for a new guess in the while loop. Try removing one indent on the input() line. On Sep 24, 2011 10:44 AM, "Cameron Macleod" <cmacleod170 at gmail.com> wrote: Hi, I've been trying to code a simple guess my number game as a starter programming project but I've generated an infinite loop accidentally. Since I'm new to programming in general, I can't really figure out what's causing it. Thanks ======================= import random print("\tWelcome to 'Guess my Number'!") print("\nI'm thinking of a number between 1 and 100.") print("Try to guess it in as few attempts as possible.\n") #set the initial values the_number = random.randint(1, 100) guess = int(input("Take a guess: ")) tries = 1 # guessing loop while guess != the_number: if guess > the_number: print("Lower...") else: print("Higher...") guess = int(input("Take a guess: ")) tries += 1 print("You guessed it! The number was", the_number) print("And it only took you", tries, "tries!\n") if tries <= 5: print("I didn't know roadrunners could type!") elif tries >= 99: print("P'raps 'Only' wasn't the right word...") elif tries == 100: print("0_0 You are the unluckiest person in the world. Or the stupidest...") 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 -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110924/a133bbee/attachment.html> From lina.lastname at gmail.com Tue Sep 27 15:47:33 2011 From: lina.lastname at gmail.com (lina) Date: Tue, 27 Sep 2011 21:47:33 +0800 Subject: [Tutor] map one file and print it out following the sequence In-Reply-To: <CAG9cJmm7nR-qYR7r8B=6Ea5mRTpm2s+DyOHx-7Kkq8J9LZbvfQ@mail.gmail.com> References: <CAG9cJmm7nR-qYR7r8B=6Ea5mRTpm2s+DyOHx-7Kkq8J9LZbvfQ@mail.gmail.com> Message-ID: <CAG9cJm=LJHaV8oNGdO7tMmNiRZKLRe_OAYo6ug_0zd+rm9PD5A@mail.gmail.com> I attached the two files. Thanks for your time, best regards, lina -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110927/16a14528/attachment-0001.html> -------------- next part -------------- A non-text attachment was scrubbed... Name: cur.itp Type: application/octet-stream Size: 18395 bytes Desc: not available URL: <http://mail.python.org/pipermail/tutor/attachments/20110927/16a14528/attachment-0001.obj> -------------- next part -------------- A non-text attachment was scrubbed... Name: processed.pdb Type: chemical/x-pdb Size: 69339 bytes Desc: not available URL: <http://mail.python.org/pipermail/tutor/attachments/20110927/16a14528/attachment-0001.pdb> From stevenhennessy at sbcglobal.net Mon Sep 26 19:00:12 2011 From: stevenhennessy at sbcglobal.net (StevenJ Hennessy) Date: Mon, 26 Sep 2011 10:00:12 -0700 (PDT) Subject: [Tutor] Fw: Issues With Map Reduce Message-ID: <1317056412.83537.YahooMailRC@web81608.mail.mud.yahoo.com> Hello, ??? I am currently struggling with a homework assignment. I need to use Map reduce to create a dictionary of palendromes -> number of palendrome for example: the string "bab bab bab cab cac dad" would output: bab 3 cab 1 dad 1 here is what I have so far def palendrome(string): ? ?palendromes = [] ? ?for word in string.split(" "): ????? if (word == word[::-1]): ????????????? palendromes.append(word) ?? return palendromes string = "abc abd bab tab cab tat yay uaefdfdu" print map(lambda x: palendrome(x), ["bab abc dab bab bab dad crap pap pap "]) #returns a list of lists [['bab', 'bab', 'bab', 'dad', 'pap', 'pap', '']] #Here is my attempt so far at the reduce section def p(lists): ?? for list in lists: ???? ???? set_h = set(list)? ?? ?? return set_h #with the p function I want to create a?set of all palendromes found. Then run a count of the?palendroms on the list and make a dict #out of this ? print reduce(p, [['bab', 'bab', 'bab', 'dad', 'pap', 'pap', '']]) ? ---------------------- ? Am I on the right track? ? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20110926/97b98b4b/attachment.html>