From dyoo at hashcollision.org Tue Mar 1 03:42:24 2016 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 1 Mar 2016 00:42:24 -0800 Subject: [Tutor] saving webpage as webarchive In-Reply-To: <1DB0625D-FDC3-4BAC-9154-70D57D31A25C@gmail.com> References: <1DB0625D-FDC3-4BAC-9154-70D57D31A25C@gmail.com> Message-ID: > I want to save a webpage as a webarchive, and not just get the text. > I hope there?s a way to do it without saving all of the images separately. > And even if I do have to download them separately, then how would I combine everything into the HTM webarchive? If I understand your question properly, I think you're asking for something like the use of the 'wget' utility, which knows how to download an entire web site: http://www.linuxjournal.com/content/downloading-entire-web-site-wget Trying to do this as a Python program is not a simple task; it's equivalent to writing a web crawler. http://www-rohan.sdsu.edu/~gawron/python_for_ss/course_core/book_draft/web/web_intro.html explains some basic ideas. From alan.gauld at btinternet.com Tue Mar 1 04:28:00 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 1 Mar 2016 09:28:00 +0000 Subject: [Tutor] saving webpage as webarchive In-Reply-To: <1DB0625D-FDC3-4BAC-9154-70D57D31A25C@gmail.com> References: <1DB0625D-FDC3-4BAC-9154-70D57D31A25C@gmail.com> Message-ID: On 01/03/16 04:32, Benjamin Fishbein wrote: > This seems like it should be simple, but I can?t find any answer with the docs or google. > I?m on a Mac. OSX Yosemite 10.10.5 > I want to save a webpage as a webarchive, and not just get the text. > I hope there?s a way to do it without saving all of the images separately. The Webarchive format is unique to Apple Safari. As such you will likely have to use some kind of Apple/MacOS library to create it. I don't know what that interface looks like but you might find something on the Apple developer site. You should try asking on the MacPython forums too, since they may know if the required API exists in a Python module. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From dimitarxivanov at gmail.com Tue Mar 1 11:28:49 2016 From: dimitarxivanov at gmail.com (Dimitar Ivanov) Date: Tue, 1 Mar 2016 18:28:49 +0200 Subject: [Tutor] If loop conditions Message-ID: Hello everyone! First time using this mailing list so please excuse me in advance if this mail is not structured properly. I'm going through a Python course by Google, so far I've gotten to the lists chapter and I've been trying to wrap my head around an exercise all afternoon long, eventually was forced to look up the answer. In the following exercise, Google requires you to look up words from a list and count how many of the words are longer or equal to 2 characters where the first and last letter match. I've been trying to assign string slices to variables and then use those variables inside the following if statement: def match_ends(words): + for word in words: + length=len(word) + newList=[] + firstChar=word[0:] + lastChar=word[:-1] + if [ length >= 2 and firstChar == lastChar ]: + newList.append(word) + else: + break + newListCount=len(newList) + return newListCount This was returning quite funky results such as counting each letter within a word as a different word, not picking up the start/end of string etc. Eventually I looked up the solution since I tracked down my problem to how I made my if statement and, of course, it turned out to be much simpler than usual. + if len(word) >= 2 and word[0] == word[-1]: I tried putting brackets around the conditions and that broke the result again so I came to wonder what's the difference between statements written without brackets and those within brackets (such as my original code block)? I'm sorry if I didn't make it completely clear, please let me know if you need any further information. Thank you! Dimitar -- Thanks, Dimitar *Twitter:* @winterchillz *Facebook: */dimitarxivanov From alan.gauld at btinternet.com Tue Mar 1 11:52:59 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 1 Mar 2016 16:52:59 +0000 Subject: [Tutor] If loop conditions In-Reply-To: References: Message-ID: On 01/03/16 16:28, Dimitar Ivanov wrote: > First time using this mailing list so please excuse me in advance if this > mail is not structured properly. No worries, you've done a pretty good job of telling us what we need to know. > In the following exercise, Google requires you to look up words from a list > and count how many of the words are longer or equal to 2 characters where > the first and last letter match. > > I've been trying to assign string slices to variables and then use those > variables inside the following if statement: You probably don't need slices here. They are cool features but not always the right thing to use. > def match_ends(words): > + for word in words: > + length=len(word) > + newList=[] > + firstChar=word[0:] > + lastChar=word[:-1] You only want the first and last character, not a slice. So just use indexes. firstChar=word[0] lastChar=word[-1] > + if [ length >= 2 and firstChar == lastChar ]: You don;t need the brackets. And in fact in this case you are creating a list containing the bollean result of your test. A non empty list (regardless of the value inside) is always going to be "true"... Just write it as: if length >= 2 and (firstChar == lastChar): The () just make it clear that its a and (b == c) rather than (a and b) == c > + newList.append(word) > + else: > + break break exits the loop, you don't want that, instead you want to go back to the start of the loop to process the next word. The command for that is continue > + newListCount=len(newList) > + return newListCount > Eventually I looked up the solution since I tracked down my problem to how > I made my if statement and, of course, it turned out to be much simpler > than usual. > > + if len(word) >= 2 and word[0] == word[-1]: > > I tried putting brackets around the conditions and that broke the result > again so I came to wonder what's the difference between statements written > without brackets and those within brackets (such as my original code block)? It all depends on the type of brackets. Using square brackets as you did creates a list with a single value like: [42] or in your case, either [True] or [False] The if statement(not loop) then treats any non empty list as True. But if you had used () instead of [] then it would probably work as you expected. if (len(word) >= 2 and word[0] == word[-1]): But you don;t really need them in Python (unlike C or Java) You can however make the intention clearer for your readers by grouping sub tests with params like: if (length >= 2) and (firstChar == lastChar): HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From aminatane at hotmail.fr Tue Mar 1 13:45:16 2016 From: aminatane at hotmail.fr (Gaston) Date: Tue, 1 Mar 2016 19:45:16 +0100 Subject: [Tutor] recursivity and lists Message-ID: Hello everyone ! I was trying to do this little exercise: # E. Given two lists sorted in increasing order, create and return a merged # list of all the elements in sorted order. You may modify the passed in lists. # Ideally, the solution should work in "linear" time, making a single # pass of both lists. I wanted to try doing it in a recursive way. Here is my function: def linear_merge(list1, list2): if list1==[]: return list2 #initial case 1 elif list2==[]:return list1 #initial case 2 elif list1[-1]>list2[-1]: #recursive case 1 a=list1.pop() return linear_merge(list1,list2).append(a) else: #recursive case 2 a=list2.pop() return linear_merge(list1,list2).append(a) So I add the biggest element of the two list to the end of the sorted couple of lists with this element removed. Problem is that python complains that he cannot know the type of the result of this function (list). In C++ I would specify the type, but from what I understood, Python should not need this. What did I miss ? I hope I made myself clear and thank you for your help, Cheers, Gaston From dyoo at hashcollision.org Tue Mar 1 15:36:52 2016 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 1 Mar 2016 12:36:52 -0800 Subject: [Tutor] recursivity and lists In-Reply-To: References: Message-ID: > > Problem is that python complains that he cannot know the type of the result of this function (list). In C++ I would specify the type, but from what I understood, Python should not need this. What did I miss ? Can you copy the exact stack trace of the error? It'll help: you've interpreted what the error means, which is useful, but it's also important to show the unvarnished output too. It will let us look and make our own interpretations. Good luck! From danny.yoo at gmail.com Tue Mar 1 15:40:32 2016 From: danny.yoo at gmail.com (Danny Yoo) Date: Tue, 1 Mar 2016 12:40:32 -0800 Subject: [Tutor] recursivity and lists In-Reply-To: References: Message-ID: Also, as a quick note: Python list append is not functional: it mutates rather than returns a useful return value. You may need to revisit the parts in the code where it assumes a different behavior from functional append. On Mar 1, 2016 12:36 PM, "Danny Yoo" wrote: > > > > > Problem is that python complains that he cannot know the type of the > result of this function (list). In C++ I would specify the type, but from > what I understood, Python should not need this. What did I miss ? > > Can you copy the exact stack trace of the error? It'll help: you've > interpreted what the error means, which is useful, but it's also important > to show the unvarnished output too. It will let us look and make our own > interpretations. > > Good luck! > From alan.gauld at btinternet.com Wed Mar 2 04:37:06 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 2 Mar 2016 09:37:06 +0000 Subject: [Tutor] Fwd: Re: If loop conditions In-Reply-To: References: Message-ID: <56D6B442.2050104@btinternet.com> Forwarding to tutor list. Please use Reply All or Reply List when responding to tutor mails. -------- Forwarded Message -------- Subject: Re: [Tutor] If loop conditions Date: Wed, 2 Mar 2016 07:31:57 +0530 From: D.V.N.Sarma ??.??.???.???? To: Alan Gauld The newList = [] statement must be above the for loop just after the function definition. regards, Sarma. On Tue, Mar 1, 2016 at 10:22 PM, Alan Gauld wrote: > On 01/03/16 16:28, Dimitar Ivanov wrote: >> First time using this mailing list so please excuse me in advance if this >> mail is not structured properly. > > No worries, you've done a pretty good job of telling us > what we need to know. > >> In the following exercise, Google requires you to look up words from a list >> and count how many of the words are longer or equal to 2 characters where >> the first and last letter match. >> >> I've been trying to assign string slices to variables and then use those >> variables inside the following if statement: > > You probably don't need slices here. They are cool features > but not always the right thing to use. > >> def match_ends(words): >> + for word in words: >> + length=len(word) >> + newList=[] >> + firstChar=word[0:] >> + lastChar=word[:-1] > > You only want the first and last character, not a slice. > So just use indexes. > > firstChar=word[0] > lastChar=word[-1] > >> + if [ length >= 2 and firstChar == lastChar ]: > > You don;t need the brackets. And in fact in this case > you are creating a list containing the bollean result > of your test. A non empty list (regardless of the > value inside) is always going to be "true"... > > Just write it as: > > if length >= 2 and (firstChar == lastChar): > > The () just make it clear that its > > a and (b == c) > > rather than > > (a and b) == c > >> + newList.append(word) >> + else: >> + break > > break exits the loop, you don't want that, instead you want > to go back to the start of the loop to process the next word. > The command for that is > > continue > >> + newListCount=len(newList) >> + return newListCount > >> Eventually I looked up the solution since I tracked down my problem to how >> I made my if statement and, of course, it turned out to be much simpler >> than usual. >> >> + if len(word) >= 2 and word[0] == word[-1]: >> >> I tried putting brackets around the conditions and that broke the result >> again so I came to wonder what's the difference between statements written >> without brackets and those within brackets (such as my original code block)? > > It all depends on the type of brackets. > Using square brackets as you did creates a list with a single value > > like: [42] or in your case, either [True] or [False] > > The if statement(not loop) then treats any non empty list as True. > > But if you had used () instead of [] then it would probably > work as you expected. > > if (len(word) >= 2 and word[0] == word[-1]): > > But you don;t really need them in Python (unlike C or Java) > > You can however make the intention clearer for your readers > by grouping sub tests with params like: > > if (length >= 2) and (firstChar == lastChar): > > HTH > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > http://www.flickr.com/photos/alangauldphotos > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From aminatane at hotmail.fr Wed Mar 2 05:24:58 2016 From: aminatane at hotmail.fr (Gaston) Date: Wed, 2 Mar 2016 11:24:58 +0100 Subject: [Tutor] recursivity and lists In-Reply-To: References: Message-ID: Thanks a lot for your help. This was the problem. I fixed it this way : def linear_merge(list1, list2): if list1==[]: return list2 elif list2==[]: return list1 elif list1[-1]>list2[-1]: a=list1.pop() linear_merge(list1,list2).append(a) return linear_merge(list1,list2) else: a=list2.pop() linear_merge(list1,list2).append(a) return linear_merge(list1,list2) I use append and then return the result, as list.append is not a query. Thank you ! On 03/01/2016 09:40 PM, Danny Yoo wrote: > > Also, as a quick note: Python list append is not functional: it > mutates rather than returns a useful return value. You may need to > revisit the parts in the code where it assumes a different behavior > from functional append. > > On Mar 1, 2016 12:36 PM, "Danny Yoo" > wrote: > > > > > > Problem is that python complains that he cannot know the type of > the result of this function (list). In C++ I would specify the > type, but from what I understood, Python should not need this. > What did I miss ? > > Can you copy the exact stack trace of the error? It'll help: > you've interpreted what the error means, which is useful, but it's > also important to show the unvarnished output too. It will let us > look and make our own interpretations. > > Good luck! > From lwaters at flinthill.org Wed Mar 2 13:26:11 2016 From: lwaters at flinthill.org (Lisa Hasler Waters) Date: Wed, 2 Mar 2016 13:26:11 -0500 Subject: [Tutor] Recommendations for best tool to write/run Python Message-ID: Hello everyone, I am new to Python, as are my middle school students. We are using Python 3.5.1 IDLE to write and run our (simple) code. However, this tool does not seem to be the best way to write longer code or to be able to re-edit code that has been saved/closed/reopened. Eventually, we hope to build some projects that we can "use" and share with others. Could you please recommend the best Python tools for writing and running our code for the long term? Also, we are hoping to find free tools! Thanks so very much! Lisa PS We have tried to use Aptana Studio 3 but it is not easy to work in. -- Lisa Waters, PhD Technology Integration Flint Hill School From ben+python at benfinney.id.au Wed Mar 2 13:58:59 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 03 Mar 2016 05:58:59 +1100 Subject: [Tutor] Recommendations for best tool to write/run Python References: Message-ID: <85mvqgvh8s.fsf@benfinney.id.au> Lisa Hasler Waters writes: > Could you please recommend the best Python tools for writing and > running our code for the long term? How much of a learning curve are you willing to accept? The best tools for the long term are inevitably those which require some investment of time to learn. -- \ ?Unix is an operating system, OS/2 is half an operating system, | `\ Windows is a shell, and DOS is a boot partition virus.? ?Peter | _o__) H. Coffin | Ben Finney From lwaters at flinthill.org Wed Mar 2 14:26:22 2016 From: lwaters at flinthill.org (Lisa Hasler Waters) Date: Wed, 2 Mar 2016 14:26:22 -0500 Subject: [Tutor] Recommendations for best tool to write/run Python In-Reply-To: <85mvqgvh8s.fsf@benfinney.id.au> References: <85mvqgvh8s.fsf@benfinney.id.au> Message-ID: Thanks so much Ben and Jon for your input. Ben, in terms of time for learning curve, I suppose we do have some limitations as we are up against school schedules. However, if it is something I could learn in a reasonable time that I could then more quickly walk my students through then I'd be up for the challenge! On Wed, Mar 2, 2016 at 1:58 PM, Ben Finney wrote: > Lisa Hasler Waters writes: > > > Could you please recommend the best Python tools for writing and > > running our code for the long term? > > How much of a learning curve are you willing to accept? The best tools > for the long term are inevitably those which require some investment of > time to learn. > > -- > \ ?Unix is an operating system, OS/2 is half an operating system, | > `\ Windows is a shell, and DOS is a boot partition virus.? ?Peter | > _o__) H. Coffin | > Ben Finney > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Lisa Waters, PhD Technology Integration Flint Hill School From ben+python at benfinney.id.au Wed Mar 2 14:50:10 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 03 Mar 2016 06:50:10 +1100 Subject: [Tutor] Recommendations for best tool to write/run Python References: <85mvqgvh8s.fsf@benfinney.id.au> Message-ID: <85io14vevh.fsf@benfinney.id.au> Lisa Hasler Waters writes: > Ben, in terms of time for learning curve, I suppose we do have some > limitations as we are up against school schedules. However, if it is > something I could learn in a reasonable time that I could then more > quickly walk my students through then I'd be up for the challenge! In that case, my recommendation is to learn a good programmer's editor, and let your students gain exposure to that. Emacs and Vim are the unchallenged masters here; community-owned, free-software, cross-platform, mature and highly flexible with support for a huge range of editing tasks. Learning either of those will reward the student with a tool they can use broadly throughout whatever computing career they choose. They aren't a small investment, though. That ?mature? comes at the cost of an entire ecosystem that evolved in decades past; concepts and commands are idiosynratic in each of them. It is highly profitable for any programmer to learn at least one of Emacs or Vim to competence, but it may be too much to confront a middle-school student in limited class time. Maybe let the class know they exist, at least. Short of those, I'd still recommend a community-owned, free-software, highly flexible programmer's editor. If you're on GNU+Linux, use the Kate or GEdit editors; they integrate very nicely with the default desktop environment and are well-maintained broadly applicable text editors. GEdit in particular has good Python support. I would recommend staying away from any language-specific IDE. Teaching its idiosyncracies will still be a large time investment, but will not be worth it IMO because the tool is so limited in scope. Better to teach a powerfuly general-purpose programmer's editor, and use the operating system's facilities for managing files and processes. -- \ ?Humanity has advanced, when it has advanced, not because it | `\ has been sober, responsible, and cautious, but because it has | _o__) been playful, rebellious, and immature.? ?Tom Robbins | Ben Finney From ben+python at benfinney.id.au Wed Mar 2 16:37:20 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 03 Mar 2016 08:37:20 +1100 Subject: [Tutor] Recommendations for best tool to write/run Python References: <85mvqgvh8s.fsf@benfinney.id.au> <85io14vevh.fsf@benfinney.id.au> Message-ID: <85a8mgv9wv.fsf@benfinney.id.au> Ben Finney writes: > Short of [the heavyweights Vim and Emacs], I'd still recommend a > community-owned, free-software, highly flexible programmer's editor. > If you're on GNU+Linux, use the Kate or GEdit editors; they integrate > very nicely with the default desktop environment and are > well-maintained broadly applicable text editors. GEdit in particular > has good Python support. In particular, when teaching students, please steer them away from proprietary software, regardless of price. Non-free software such as Sublime Text, PyCharms, Wing IDE, and the like, sometimes have a zero-dollar license, but your students should not be encouraged to use tools they are forbidden to learn about and share. In education, please use free-software tools ? that is, software with license to inspect, modify, and share the changes ? so your students can learn at any level their interest takes them. -- \ ?What I resent is that the range of your vision should be the | `\ limit of my action.? ?Henry James | _o__) | Ben Finney From ben+python at benfinney.id.au Wed Mar 2 17:16:38 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 03 Mar 2016 09:16:38 +1100 Subject: [Tutor] Recommendations for best tool to write/run Python References: <85mvqgvh8s.fsf@benfinney.id.au> <85io14vevh.fsf@benfinney.id.au> Message-ID: <8560x4v83d.fsf@benfinney.id.au> Ben Finney writes: > In that case, my recommendation is to learn a good programmer's > editor, and let your students gain exposure to that. > > Emacs and Vim are the unchallenged masters here [?] > > They aren't a small investment, though. [?] it may be too much to > confront a middle-school student in limited class time. Maybe let the > class know they exist, at least. > > Short of those, I'd still recommend a community-owned, free-software, > highly flexible programmer's editor. I have never used Atom , but it meets the criteria I would recommend. It is free software, community owned, has support for a broad variety of contemporary editing tasks, is cross-platform. On top of that it has advantages over Vim and Emacs: its terminology matches what today's computer users expect; it is written in and extensible with a commonly-used programming language; it UI is designed to match contemporary user expectations. The few reservations I have ? it is not yet mature enough to have support for pretty much every editing tasks; it does not appear to have a text console mode (for use across an SSH link); it is presently dominated by a single corporation ? should not stop you from presenting it to your students as a fine programmer's editor for their future. -- \ ?Not using Microsoft products is like being a non-smoker 40 or | `\ 50 years ago: You can choose not to smoke, yourself, but it's | _o__) hard to avoid second-hand smoke.? ?Michael Tiemann | Ben Finney From aneeque.khan at ericsson.com Wed Mar 2 14:43:11 2016 From: aneeque.khan at ericsson.com (Aneeque Khan) Date: Wed, 2 Mar 2016 19:43:11 +0000 Subject: [Tutor] Recommendations for best tool to write/run Python In-Reply-To: References: <85mvqgvh8s.fsf@benfinney.id.au> Message-ID: <9543F11B7EBBF24CBFD5DFC01818F990147F9B@ESESSMB105.ericsson.se> You can go for JetBrain`s PyCharms IDE (community edition), its free and available for Windows, MacOS and Linux. https://www.jetbrains.com/pycharm/download/ For learning purposes community edition will serve all the needs but if you want to do some advanced and professional work go for paid Professional version. Regards, Aneeque -----Original Message----- From: Tutor [mailto:tutor-bounces+aneeque.khan=ericsson.com at python.org] On Behalf Of Lisa Hasler Waters Sent: Thursday, March 03, 2016 12:56 AM To: Ben Finney Cc: tutor at python.org Subject: Re: [Tutor] Recommendations for best tool to write/run Python Thanks so much Ben and Jon for your input. Ben, in terms of time for learning curve, I suppose we do have some limitations as we are up against school schedules. However, if it is something I could learn in a reasonable time that I could then more quickly walk my students through then I'd be up for the challenge! On Wed, Mar 2, 2016 at 1:58 PM, Ben Finney wrote: > Lisa Hasler Waters writes: > > > Could you please recommend the best Python tools for writing and > > running our code for the long term? > > How much of a learning curve are you willing to accept? The best tools > for the long term are inevitably those which require some investment > of time to learn. > > -- > \ ?Unix is an operating system, OS/2 is half an operating system, | > `\ Windows is a shell, and DOS is a boot partition virus.? ?Peter | > _o__) H. Coffin | > Ben Finney > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Lisa Waters, PhD Technology Integration Flint Hill School _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor From lists.davep at gmail.com Wed Mar 2 14:44:51 2016 From: lists.davep at gmail.com (Dave P) Date: Wed, 2 Mar 2016 14:44:51 -0500 Subject: [Tutor] Recommendations for best tool to write/run Python In-Reply-To: References: Message-ID: On Wed, Mar 2, 2016 at 1:26 PM, Lisa Hasler Waters wrote: > Hello everyone, > > I am new to Python, as are my middle school students. We are using Python > 3.5.1 IDLE to write and run our (simple) code. However, this tool does not > seem to be the best way to write longer code or to be able to re-edit code > that has been saved/closed/reopened. > > Eventually, we hope to build some projects that we can "use" and share with > others. > > Could you please recommend the best Python tools for writing and running > our code for the long term? Also, we are hoping to find free tools! > > Thanks so very much! > > Lisa > > PS We have tried to use Aptana Studio 3 but it is not easy to work in. > I'm a beginner, and I've learned a lot from Visual Studio 2015 (Community Edition) and a third party extension called Python Tools for Visual Studio (PTVS). It's similar to running PyDev in Eclipse or LiClipse. Good luck! From matt.williams45.mw at gmail.com Wed Mar 2 16:25:41 2016 From: matt.williams45.mw at gmail.com (Matt Williams) Date: Wed, 02 Mar 2016 21:25:41 +0000 Subject: [Tutor] Recommendations for best tool to write/run Python In-Reply-To: <85io14vevh.fsf@benfinney.id.au> References: <85mvqgvh8s.fsf@benfinney.id.au> <85io14vevh.fsf@benfinney.id.au> Message-ID: I teach an introductory programming course to medical students (and a few doctors). I would look at Sublime Text 2 if one Windows/ Mac. Has a 'nag' screen to remind you to buy, but feels simple enough when you start it. M On Wed, 2 Mar 2016 19:50 Ben Finney, wrote: > Lisa Hasler Waters writes: > > > Ben, in terms of time for learning curve, I suppose we do have some > > limitations as we are up against school schedules. However, if it is > > something I could learn in a reasonable time that I could then more > > quickly walk my students through then I'd be up for the challenge! > > In that case, my recommendation is to learn a good programmer's editor, > and let your students gain exposure to that. > > Emacs and Vim are the unchallenged masters here; community-owned, > free-software, cross-platform, mature and highly flexible with support > for a huge range of editing tasks. Learning either of those will reward > the student with a tool they can use broadly throughout whatever > computing career they choose. > > They aren't a small investment, though. That ?mature? comes at the cost > of an entire ecosystem that evolved in decades past; concepts and > commands are idiosynratic in each of them. It is highly profitable for > any programmer to learn at least one of Emacs or Vim to competence, but > it may be too much to confront a middle-school student in limited class > time. Maybe let the class know they exist, at least. > > Short of those, I'd still recommend a community-owned, free-software, > highly flexible programmer's editor. If you're on GNU+Linux, use the > Kate or GEdit editors; they integrate very nicely with the default > desktop environment and are well-maintained broadly applicable text > editors. GEdit in particular has good Python support. > > I would recommend staying away from any language-specific IDE. Teaching > its idiosyncracies will still be a large time investment, but will not > be worth it IMO because the tool is so limited in scope. Better to teach > a powerfuly general-purpose programmer's editor, and use the operating > system's facilities for managing files and processes. > > -- > \ ?Humanity has advanced, when it has advanced, not because it | > `\ has been sober, responsible, and cautious, but because it has | > _o__) been playful, rebellious, and immature.? ?Tom Robbins | > Ben Finney > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From matt.williams45.mw at gmail.com Wed Mar 2 16:40:13 2016 From: matt.williams45.mw at gmail.com (Matt Williams) Date: Wed, 02 Mar 2016 21:40:13 +0000 Subject: [Tutor] Recommendations for best tool to write/run Python In-Reply-To: <85a8mgv9wv.fsf@benfinney.id.au> References: <85mvqgvh8s.fsf@benfinney.id.au> <85io14vevh.fsf@benfinney.id.au> <85a8mgv9wv.fsf@benfinney.id.au> Message-ID: Can someone recommend an open-source editor for all 3 platforms? M On Wed, 2 Mar 2016 21:37 Ben Finney, wrote: > Ben Finney writes: > > > Short of [the heavyweights Vim and Emacs], I'd still recommend a > > community-owned, free-software, highly flexible programmer's editor. > > If you're on GNU+Linux, use the Kate or GEdit editors; they integrate > > very nicely with the default desktop environment and are > > well-maintained broadly applicable text editors. GEdit in particular > > has good Python support. > > In particular, when teaching students, please steer them away from > proprietary software, regardless of price. > > Non-free software such as Sublime Text, PyCharms, Wing IDE, and the > like, sometimes have a zero-dollar license, but your students should not > be encouraged to use tools they are forbidden to learn about and share. > > In education, please use free-software tools ? that is, software with > license to inspect, modify, and share the changes ? so your students can > learn at any level their interest takes them. > > -- > \ ?What I resent is that the range of your vision should be the | > `\ limit of my action.? ?Henry James | > _o__) | > Ben Finney > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From mikiozen at gmail.com Wed Mar 2 14:04:13 2016 From: mikiozen at gmail.com (TJ Nelson) Date: Wed, 2 Mar 2016 14:04:13 -0500 Subject: [Tutor] Recommendations for best tool to write/run Python In-Reply-To: <85mvqgvh8s.fsf@benfinney.id.au> References: <85mvqgvh8s.fsf@benfinney.id.au> Message-ID: Check out https://www.continuum.io/downloads Anaconda has a IDE called Spyder this may be a good solution. On Wed, Mar 2, 2016 at 1:58 PM, Ben Finney wrote: > Lisa Hasler Waters writes: > > > Could you please recommend the best Python tools for writing and > > running our code for the long term? > > How much of a learning curve are you willing to accept? The best tools > for the long term are inevitably those which require some investment of > time to learn. > > -- > \ ?Unix is an operating system, OS/2 is half an operating system, | > `\ Windows is a shell, and DOS is a boot partition virus.? ?Peter | > _o__) H. Coffin | > Ben Finney > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From toothpik6 at gmail.com Wed Mar 2 14:01:06 2016 From: toothpik6 at gmail.com (toothpik) Date: Wed, 2 Mar 2016 13:01:06 -0600 Subject: [Tutor] Recommendations for best tool to write/run Python In-Reply-To: References: Message-ID: <20160302190106.GA25468@gmail.com> On Wed, Mar 02, 2016 at 01:26:11PM -0500, Lisa Hasler Waters wrote: > Hello everyone, > I am new to Python, as are my middle school students. We are using Python > 3.5.1 IDLE to write and run our (simple) code. However, this tool does not > seem to be the best way to write longer code or to be able to re-edit code > that has been saved/closed/reopened. > Eventually, we hope to build some projects that we can "use" and share with > others. > Could you please recommend the best Python tools for writing and running > our code for the long term? Also, we are hoping to find free tools! you can do no better than vim for writing, and any given command line for running From alan.gauld at btinternet.com Wed Mar 2 19:20:22 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 3 Mar 2016 00:20:22 +0000 Subject: [Tutor] Recommendations for best tool to write/run Python In-Reply-To: References: Message-ID: On 02/03/16 18:26, Lisa Hasler Waters wrote: > I am new to Python, as are my middle school students. We are using Python > 3.5.1 IDLE to write and run our (simple) code. However, this tool does not > seem to be the best way to write longer code or to be able to re-edit code > that has been saved/closed/reopened. While IDLE is far from perfect it's not really that bad, especially for beginners. Can you be more specific about what you don't like about it? That way we can point you to something more appropriate. There is also IdleX which addresses most of the common complaints - like adding tabbed editors, code context windows, folding of code etc. Its very easy to suggest "professional tools" like vim/emacs/Eclipse or Netbeans (all of which i use) but they all have a steep learning curve and are only needed if you are working on very large projects with many files(like 10+ say). Most Python projects have less than that. So what exactly do you find to be the issues with IDLE? Then we can find the simplest tool that overcomes those issues. > Could you please recommend the best Python tools for writing and running > our code for the long term? Also, we are hoping to find free tools! Free tools are no problem there are dozens. But they all have their own philosophy of what makes a good tool, and you need to find the one that matches you. Do you want: 1) Fastest possible text editing - probably vim? 2) Most customisable environment - emacs or Eclipse? 3) Most automation of coding - Netbeans or Eclipse? 4) Best project management - Ecliose, Nertbeans, Visual studio? 5) Best debugger/version control/GUI designer/ etc...? 6) Simplest to learn - IDLE/Pythonwin/Kate? 7) Multi platform - not Visual studio or Pythonwin... It all depends on your priorities. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From beachkidken at gmail.com Wed Mar 2 19:24:07 2016 From: beachkidken at gmail.com (Ken G.) Date: Wed, 2 Mar 2016 19:24:07 -0500 Subject: [Tutor] Recommendations for best tool to write/run Python In-Reply-To: References: Message-ID: <56D78427.80904@gmail.com> On 03/02/2016 01:26 PM, Lisa Hasler Waters wrote: > Hello everyone, > > I am new to Python, as are my middle school students. We are using Python > 3.5.1 IDLE to write and run our (simple) code. However, this tool does not > seem to be the best way to write longer code or to be able to re-edit code > that has been saved/closed/reopened. > > Eventually, we hope to build some projects that we can "use" and share with > others. > > Could you please recommend the best Python tools for writing and running > our code for the long term? Also, we are hoping to find free tools! > > Thanks so very much! > > Lisa > > PS We have tried to use Aptana Studio 3 but it is not easy to work in. I have been using Geany as my Python work station in my Ubuntu 14.04.4 desktop operating system. Ken > From alan.gauld at btinternet.com Wed Mar 2 19:44:24 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 3 Mar 2016 00:44:24 +0000 Subject: [Tutor] Recommendations for best tool to write/run Python In-Reply-To: References: <85mvqgvh8s.fsf@benfinney.id.au> <85io14vevh.fsf@benfinney.id.au> <85a8mgv9wv.fsf@benfinney.id.au> Message-ID: On 02/03/16 21:40, Matt Williams wrote: > Can someone recommend an open-source editor for all 3 platforms? Several have already been mentioned. vim and emacs are the standards. Geany is popular on Linux but also available on Windows/MacOSX Jedit hasn't had a shout yet but does work cross platform. Fairly lightweight. Eclipse and Netbeans are the heavyweight options - very powerful but need big machines to run them - the more RAM the better. Both have Python plugins. And there are many more.... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From akleider at sonic.net Wed Mar 2 20:48:28 2016 From: akleider at sonic.net (Alex Kleider) Date: Wed, 02 Mar 2016 17:48:28 -0800 Subject: [Tutor] Recommendations for best tool to write/run Python In-Reply-To: <85io14vevh.fsf@benfinney.id.au> References: <85mvqgvh8s.fsf@benfinney.id.au> <85io14vevh.fsf@benfinney.id.au> Message-ID: <1c844c1eecfefcf9dd590e1c260e2589@sonic.net> I've not noticed anyone mention vimtutor which might be helpful. On a Mac or Linux system, from the command line simply type "vimtutor" and with in 1/2 to 1 hour you'll know enough to use vim _and_ be in a position to decide if it's the editor for you. I've been told vim can also be had on the Redmond OS but I've no experience there. Alex From __peter__ at web.de Thu Mar 3 04:25:27 2016 From: __peter__ at web.de (Peter Otten) Date: Thu, 03 Mar 2016 10:25:27 +0100 Subject: [Tutor] Recommendations for best tool to write/run Python References: Message-ID: Lisa Hasler Waters wrote: > I am new to Python, as are my middle school students. We are using Python > 3.5.1 IDLE to write and run our (simple) code. However, this tool does not > seem to be the best way to write longer code or to be able to re-edit code > that has been saved/closed/reopened. Hi Lisa! When Idle opens it shows a window called Shell. That window is meant for experiments with existing modules or as a kind of calculator. It is not for writing scripts. If you want to write a script go to File->New File in the menu and use the window that pops up to write your code. Once you're satisfied and want to try the script go to Run->Run Module (or hit F5). If you didn't save the script before you will be asked to do that now. Once you have saved the script Idle tries to execute it. If there is a syntax error the error is marked and you can fix it. When there are no more syntax errors the script will run, and if it prints anything the output will be shown in the Shell window mentioned above. Let's say you're done and close Idle for now. The next time you open it you can pick the files you worked with recently from the list shown in the menu under File->Recent Files. Did you work with Idle that way? What are your actual complaints? From paradox at pobox.com Thu Mar 3 04:28:15 2016 From: paradox at pobox.com (Thomas C. Hicks) Date: Thu, 3 Mar 2016 17:28:15 +0800 Subject: [Tutor] Recommendations for best tool to write/run Python :p: In-Reply-To: References: <85mvqgvh8s.fsf@benfinney.id.au> <85io14vevh.fsf@benfinney.id.au> Message-ID: <56D803AF.6060600@pobox.com> Matt, As a physician myself just getting into the world of teaching computer programming I would be very interested to know what you teach to the doctors. Feel free to reply off list, would love to discuss this! =============== Thomas C. Hicks, MD, MPH Training Manager Gansu Gateway, Lanzhou, Gansu On 03/03/2016 05:25 AM, Matt Williams wrote: > I teach an introductory programming course to medical students (and a few > doctors). > > I would look at Sublime Text 2 if one Windows/ Mac. Has a 'nag' screen to > remind you to buy, but feels simple enough when you start it. > > M > > On Wed, 2 Mar 2016 19:50 Ben Finney, wrote: > >> Lisa Hasler Waters writes: >> >>> Ben, in terms of time for learning curve, I suppose we do have some >>> limitations as we are up against school schedules. However, if it is >>> something I could learn in a reasonable time that I could then more >>> quickly walk my students through then I'd be up for the challenge! >> In that case, my recommendation is to learn a good programmer's editor, >> and let your students gain exposure to that. >> >> Emacs and Vim are the unchallenged masters here; community-owned, >> free-software, cross-platform, mature and highly flexible with support >> for a huge range of editing tasks. Learning either of those will reward >> the student with a tool they can use broadly throughout whatever >> computing career they choose. >> >> They aren't a small investment, though. That ?mature? comes at the cost >> of an entire ecosystem that evolved in decades past; concepts and >> commands are idiosynratic in each of them. It is highly profitable for >> any programmer to learn at least one of Emacs or Vim to competence, but >> it may be too much to confront a middle-school student in limited class >> time. Maybe let the class know they exist, at least. >> >> Short of those, I'd still recommend a community-owned, free-software, >> highly flexible programmer's editor. If you're on GNU+Linux, use the >> Kate or GEdit editors; they integrate very nicely with the default >> desktop environment and are well-maintained broadly applicable text >> editors. GEdit in particular has good Python support. >> >> I would recommend staying away from any language-specific IDE. Teaching >> its idiosyncracies will still be a large time investment, but will not >> be worth it IMO because the tool is so limited in scope. Better to teach >> a powerfuly general-purpose programmer's editor, and use the operating >> system's facilities for managing files and processes. >> >> -- >> \ ?Humanity has advanced, when it has advanced, not because it | >> `\ has been sober, responsible, and cautious, but because it has | >> _o__) been playful, rebellious, and immature.? ?Tom Robbins | >> Ben Finney >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor >> > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From paradox at pobox.com Thu Mar 3 04:31:12 2016 From: paradox at pobox.com (Thomas C. Hicks) Date: Thu, 3 Mar 2016 17:31:12 +0800 Subject: [Tutor] Recommendations for best tool to write/run Python :p: In-Reply-To: References: Message-ID: <56D80460.5070308@pobox.com> On 03/03/2016 02:26 AM, Lisa Hasler Waters wrote: > Could you please recommend the best Python tools for writing and running > our code for the long term? Also, we are hoping to find free tools! > Most people on this list are a lot smarter than me so there are probably good reasons for it but I have used Ipython (now Jupyter) for teaching my kids programming in middle and high school. =============== Thomas C. Hicks, MD, MPH Training Manager Gansu Gateway, Lanzhou, Gansu From alan.gauld at btinternet.com Thu Mar 3 06:02:44 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 3 Mar 2016 11:02:44 +0000 Subject: [Tutor] Recommendations for best tool to write/run Python :p: In-Reply-To: <56D80460.5070308@pobox.com> References: <56D80460.5070308@pobox.com> Message-ID: On 03/03/16 09:31, Thomas C. Hicks wrote: > On 03/03/2016 02:26 AM, Lisa Hasler Waters wrote: >> Could you please recommend the best Python tools for writing and running >> our code for the long term? Also, we are hoping to find free tools! >> > Most people on this list are a lot smarter than me so there are probably > good reasons for it but I have used Ipython (now Jupyter) for teaching > my kids programming in middle and high school. IPython is great as an interactive environment but the OP specifically mentioned writing longer programs and editing files which is not what IPython does best. I suspect that's why it didn't get a mention earlier. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From lwaters at flinthill.org Thu Mar 3 14:20:55 2016 From: lwaters at flinthill.org (Lisa Hasler Waters) Date: Thu, 3 Mar 2016 14:20:55 -0500 Subject: [Tutor] Recommendations for best tool to write/run Python :p: In-Reply-To: References: <56D80460.5070308@pobox.com> Message-ID: Thanks to everyone for such great tips/advice! Lisa On Thu, Mar 3, 2016 at 6:02 AM, Alan Gauld wrote: > On 03/03/16 09:31, Thomas C. Hicks wrote: > > On 03/03/2016 02:26 AM, Lisa Hasler Waters wrote: > >> Could you please recommend the best Python tools for writing and running > >> our code for the long term? Also, we are hoping to find free tools! > >> > > Most people on this list are a lot smarter than me so there are probably > > good reasons for it but I have used Ipython (now Jupyter) for teaching > > my kids programming in middle and high school. > > IPython is great as an interactive environment but the OP > specifically mentioned writing longer programs and editing > files which is not what IPython does best. I suspect that's > why it didn't get a mention earlier. > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > http://www.flickr.com/photos/alangauldphotos > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Lisa Waters, PhD Technology Integration Flint Hill School From danny.yoo at gmail.com Thu Mar 3 16:29:35 2016 From: danny.yoo at gmail.com (Danny Yoo) Date: Thu, 3 Mar 2016 13:29:35 -0800 Subject: [Tutor] recursivity and lists In-Reply-To: References: Message-ID: Some code comments: The solution you have depends very much on mutation and side effects: I recommend you try to stay as functional as you can in this situation. By mixing mutation into the solution, there are certain things that the program is doing that isn't part of the traditional behavior of a merge sort. For example, it is actively mutating the input lists. That's both surprising and error prone. Also, the purpose for the second internal calls to the merge sort in your current solution have nothing to do with merging, but rather to pick which nonempty list to return as the result. A reader of the code who doesn't look at this code *very* carefully would wonder why the function wasn't infinite-looping. It's a bit too clever for its own good. Hope that makes sense! From david at graniteweb.com Thu Mar 3 16:54:56 2016 From: david at graniteweb.com (David Rock) Date: Thu, 3 Mar 2016 15:54:56 -0600 Subject: [Tutor] Recommendations for best tool to write/run Python :p: In-Reply-To: References: <56D80460.5070308@pobox.com> Message-ID: <20160303215456.GD29623@raspberrypi> * Alan Gauld [2016-03-03 11:02]: > On 03/03/16 09:31, Thomas C. Hicks wrote: > > On 03/03/2016 02:26 AM, Lisa Hasler Waters wrote: > >> Could you please recommend the best Python tools for writing and running > >> our code for the long term? Also, we are hoping to find free tools! > >> > > Most people on this list are a lot smarter than me so there are probably > > good reasons for it but I have used Ipython (now Jupyter) for teaching > > my kids programming in middle and high school. > > IPython is great as an interactive environment but the OP > specifically mentioned writing longer programs and editing > files which is not what IPython does best. I suspect that's > why it didn't get a mention earlier. Very likely, but it's definitely worth mentioning as a runtime environment. It's a big step above the basic built-in CLI -- David Rock david at graniteweb.com From ben+python at benfinney.id.au Thu Mar 3 17:54:10 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 04 Mar 2016 09:54:10 +1100 Subject: [Tutor] Recommendations for best tool to write/run Python :p: References: <56D80460.5070308@pobox.com> Message-ID: <85bn6vtbot.fsf@benfinney.id.au> Lisa Hasler Waters writes: > Thanks to everyone for such great tips/advice! Feel free to write about your actual experience with choosing and teaching your students a tool, and let the Python forum know it . I for one would be very interested to see that. -- \ ?Pinky, are you pondering what I'm pondering?? ?I think so, | `\ Brain, but don't you need a swimming pool to play Marco Polo?? | _o__) ?_Pinky and The Brain_ | Ben Finney From sjeik_appie at hotmail.com Fri Mar 4 03:10:44 2016 From: sjeik_appie at hotmail.com (Albert-Jan Roskam) Date: Fri, 4 Mar 2016 08:10:44 +0000 Subject: [Tutor] Recommendations for best tool to write/run Python :p: In-Reply-To: <20160303215456.GD29623@raspberrypi> References: , <56D80460.5070308@pobox.com> ,<20160303215456.GD29623@raspberrypi> Message-ID: > Date: Thu, 3 Mar 2016 15:54:56 -0600 > From: david at graniteweb.com > To: tutor at python.org > Subject: Re: [Tutor] Recommendations for best tool to write/run Python :p: > > * Alan Gauld [2016-03-03 11:02]: > > On 03/03/16 09:31, Thomas C. Hicks wrote: > > > On 03/03/2016 02:26 AM, Lisa Hasler Waters wrote: > > >> Could you please recommend the best Python tools for writing and running > > >> our code for the long term? Also, we are hoping to find free tools! > > >> > > > Most people on this list are a lot smarter than me so there are probably > > > good reasons for it but I have used Ipython (now Jupyter) for teaching > > > my kids programming in middle and high school. > > > > IPython is great as an interactive environment but the OP > > specifically mentioned writing longer programs and editing > > files which is not what IPython does best. I suspect that's > > why it didn't get a mention earlier. > > Very likely, but it's definitely worth mentioning as a runtime environment. > It's a big step above the basic built-in CLI Yes, IPython is extremely useful, even if only for testing code snippets. IPython Notebook is worth mentioning as well. My favourite IDE currently is Spyder (free). PyScripter is nice (and free) too, but I don't like the way it behaves with pdb (with a little menu). Both come with Python(x, y). PyCharm is great too (maybe even nicer than Spyder), but it's only free for open source projects. It is Java-based, but only Sun Java and not Open JDK (it occasionally frooze with Open JDK so I stoped using it). Albert-Jan From aminatane at hotmail.fr Fri Mar 4 10:00:35 2016 From: aminatane at hotmail.fr (Gaston) Date: Fri, 4 Mar 2016 16:00:35 +0100 Subject: [Tutor] recursivity and lists In-Reply-To: References: Message-ID: Thank you for these comments. Made me realize that I do not fully understand my code, and need to think about it a bit more. I totally understand the huge side effects, and it is true that it would be dangerous if the function was to actually be used. I would like to find a fully functional version, using slices then. I propose this : def linear_merge(list1, list2): if list1==[]: return list2 elif list2==[]: return list1 elif list1[-1]>list2[-1]: return linear_merge(list1[:-1],list2)+[list1[-1]] else: return linear_merge(list1,list2[:-1])+[list2[-1]] Or alternatively: elif list1[-1]>list2[-1]: b=linear_merge(list1[:-1],list2) b.append(list1[-1]) return b Both work but I am not satisfied. Is there not a method that could do the job of '+' operator (namely concatenate in a copy)? As for my first code : def linear_merge1(list1, list2): if list1==[]: return list2 elif list2==[]: return list1 elif list1[-1]>list2[-1]: a=list1.pop() linear_merge(list1,list2).append(a) return linear_merge(list1,list2) else: a=list2.pop() linear_merge(list1,list2).append(a) return linear_merge(list1,list2) I don't get why it works to be fair. It feels like return linear_merge(list1,list2) does not call the function again. If return linear_merge(list1,list2) actually returned linear_merged of the lists, with one of them missing an element, I don't see where this element is actually added. I know find it very weird. I would appreciate if you had an explanation (and if you understood my point) Thank you for your help, Gaston On 03/03/2016 10:29 PM, Danny Yoo wrote: > > Some code comments: The solution you have depends very much on > mutation and side effects: I recommend you try to stay as functional > as you can in this situation. > > By mixing mutation into the solution, there are certain things that > the program is doing that isn't part of the traditional behavior of a > merge sort. > > For example, it is actively mutating the input lists. That's both > surprising and error prone. > > Also, the purpose for the second internal calls to the merge sort in > your current solution have nothing to do with merging, but rather to > pick which nonempty list to return as the result. A reader of the > code who doesn't look at this code *very* carefully would wonder why > the function wasn't infinite-looping. It's a bit too clever for its > own good. > > Hope that makes sense! > From walters.justin01 at gmail.com Fri Mar 4 11:49:23 2016 From: walters.justin01 at gmail.com (justin walters) Date: Fri, 4 Mar 2016 08:49:23 -0800 Subject: [Tutor] Tutor Digest, Vol 145, Issue 7 In-Reply-To: References: Message-ID: I personally use pycharm community edition. It has helped me learn a lot. It is quite heavy though. I think your best bet would be sublime text(mac, windows, and linux) or gedit(linux only I believe). On Mar 3, 2016 9:00 AM, wrote: > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > https://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Re: Recommendations for best tool to write/run Python :p: > (Thomas C. Hicks) > 2. Re: Recommendations for best tool to write/run Python :p: > (Thomas C. Hicks) > 3. Re: Recommendations for best tool to write/run Python :p: > (Alan Gauld) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Thu, 3 Mar 2016 17:28:15 +0800 > From: "Thomas C. Hicks" > To: tutor at python.org > Subject: Re: [Tutor] Recommendations for best tool to write/run Python > :p: > Message-ID: <56D803AF.6060600 at pobox.com> > Content-Type: text/plain; charset=utf-8; format=flowed > > Matt, > > As a physician myself just getting into the world of teaching computer > programming I would be very interested to know what you teach to the > doctors. Feel free to reply off list, would love to discuss this! > > =============== > Thomas C. Hicks, MD, MPH > Training Manager > Gansu Gateway, Lanzhou, Gansu > > On 03/03/2016 05:25 AM, Matt Williams wrote: > > I teach an introductory programming course to medical students (and a few > > doctors). > > > > I would look at Sublime Text 2 if one Windows/ Mac. Has a 'nag' screen to > > remind you to buy, but feels simple enough when you start it. > > > > M > > > > On Wed, 2 Mar 2016 19:50 Ben Finney, wrote: > > > >> Lisa Hasler Waters writes: > >> > >>> Ben, in terms of time for learning curve, I suppose we do have some > >>> limitations as we are up against school schedules. However, if it is > >>> something I could learn in a reasonable time that I could then more > >>> quickly walk my students through then I'd be up for the challenge! > >> In that case, my recommendation is to learn a good programmer's editor, > >> and let your students gain exposure to that. > >> > >> Emacs and Vim are the unchallenged masters here; community-owned, > >> free-software, cross-platform, mature and highly flexible with support > >> for a huge range of editing tasks. Learning either of those will reward > >> the student with a tool they can use broadly throughout whatever > >> computing career they choose. > >> > >> They aren't a small investment, though. That ?mature? comes at the cost > >> of an entire ecosystem that evolved in decades past; concepts and > >> commands are idiosynratic in each of them. It is highly profitable for > >> any programmer to learn at least one of Emacs or Vim to competence, but > >> it may be too much to confront a middle-school student in limited class > >> time. Maybe let the class know they exist, at least. > >> > >> Short of those, I'd still recommend a community-owned, free-software, > >> highly flexible programmer's editor. If you're on GNU+Linux, use the > >> Kate or GEdit editors; they integrate very nicely with the default > >> desktop environment and are well-maintained broadly applicable text > >> editors. GEdit in particular has good Python support. > >> > >> I would recommend staying away from any language-specific IDE. Teaching > >> its idiosyncracies will still be a large time investment, but will not > >> be worth it IMO because the tool is so limited in scope. Better to teach > >> a powerfuly general-purpose programmer's editor, and use the operating > >> system's facilities for managing files and processes. > >> > >> -- > >> \ ?Humanity has advanced, when it has advanced, not because it > | > >> `\ has been sober, responsible, and cautious, but because it has > | > >> _o__) been playful, rebellious, and immature.? ?Tom Robbins | > >> Ben Finney > >> > >> _______________________________________________ > >> Tutor maillist - Tutor at python.org > >> To unsubscribe or change subscription options: > >> https://mail.python.org/mailman/listinfo/tutor > >> > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > https://mail.python.org/mailman/listinfo/tutor > > > > ------------------------------ > > Message: 2 > Date: Thu, 3 Mar 2016 17:31:12 +0800 > From: "Thomas C. Hicks" > To: tutor at python.org > Subject: Re: [Tutor] Recommendations for best tool to write/run Python > :p: > Message-ID: <56D80460.5070308 at pobox.com> > Content-Type: text/plain; charset=windows-1252; format=flowed > > On 03/03/2016 02:26 AM, Lisa Hasler Waters wrote: > > Could you please recommend the best Python tools for writing and running > > our code for the long term? Also, we are hoping to find free tools! > > > Most people on this list are a lot smarter than me so there are probably > good reasons for it but I have used Ipython (now Jupyter) for teaching > my kids programming in middle and high school. > > =============== > Thomas C. Hicks, MD, MPH > Training Manager > Gansu Gateway, Lanzhou, Gansu > > > ------------------------------ > > Message: 3 > Date: Thu, 3 Mar 2016 11:02:44 +0000 > From: Alan Gauld > To: tutor at python.org > Subject: Re: [Tutor] Recommendations for best tool to write/run Python > :p: > Message-ID: > Content-Type: text/plain; charset=utf-8 > > On 03/03/16 09:31, Thomas C. Hicks wrote: > > On 03/03/2016 02:26 AM, Lisa Hasler Waters wrote: > >> Could you please recommend the best Python tools for writing and running > >> our code for the long term? Also, we are hoping to find free tools! > >> > > Most people on this list are a lot smarter than me so there are probably > > good reasons for it but I have used Ipython (now Jupyter) for teaching > > my kids programming in middle and high school. > > IPython is great as an interactive environment but the OP > specifically mentioned writing longer programs and editing > files which is not what IPython does best. I suspect that's > why it didn't get a mention earlier. > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > http://www.flickr.com/photos/alangauldphotos > > > > > ------------------------------ > > Subject: Digest Footer > > _______________________________________________ > Tutor maillist - Tutor at python.org > https://mail.python.org/mailman/listinfo/tutor > > > ------------------------------ > > End of Tutor Digest, Vol 145, Issue 7 > ************************************* > From alan.gauld at btinternet.com Fri Mar 4 13:57:16 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 4 Mar 2016 18:57:16 +0000 Subject: [Tutor] Tutor Digest, Vol 145, Issue 7 In-Reply-To: References: Message-ID: On 04/03/16 16:49, justin walters wrote: > I personally use pycharm community edition. It has helped me learn a lot. > It is quite heavy though. I think your best bet would be sublime text(mac, > windows, and linux) or gedit(linux only I believe). Thanks for the comments Justin but please in future do not send the whole digest message with your answer. WE have all received the messages already, and some people pay by the byte for their access. Also please change the subject line to something meaningful. Thanks Alan G. List moderator. > On Mar 3, 2016 9:00 AM, wrote: > >> Send Tutor mailing list submissions to >> tutor at python.org >> >> To subscribe or unsubscribe via the World Wide Web, visit >> https://mail.python.org/mailman/listinfo/tutor >> or, via email, send a message with subject or body 'help' to >> tutor-request at python.org >> >> You can reach the person managing the list at >> tutor-owner at python.org >> >> When replying, please edit your Subject line so it is more specific >> than "Re: Contents of Tutor digest..." >> >> >> Today's Topics: >> >> 1. Re: Recommendations for best tool to write/run Python :p: >> (Thomas C. Hicks) >> 2. Re: Recommendations for best tool to write/run Python :p: From alan.gauld at btinternet.com Fri Mar 4 14:14:19 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 4 Mar 2016 19:14:19 +0000 Subject: [Tutor] recursivity and lists In-Reply-To: References: Message-ID: On 04/03/16 15:00, Gaston wrote: > Both work but I am not satisfied. Is there not a method that could do > the job of '+' operator (namely concatenate in a copy)? Why would you want a method? An operator is a perfectly legitimate feature and is at least as readable as a method. It is certainly no less "functional". And of course, in Python + usually translates to the __add__() method anyway. As to how your initial function works can I suggest you sit down with a pen and paper and work through the code iteration by iteration. Start with 2 element lists and then try 3 elements. By the time you've done that it should become clear. Keep track of the contents of list1 and list2 and the output for each call of the function. Recursive can be a seductive technique but it can be a real brain twister to work out and debug when things don;t go as expected! The pen/paper manual approach is the most reliable technique I've found. Here is what I mean for a 2 element list pair: list1 list2 f(list1,list2) ----------------------------------------------- [1] [2] f([1],[]).append(2) # first call of f() [1] [] [1].append(2) -> list1 becomes [1,2] [1,2] [] f([1,2],[]) # 2nd call of f() -> [1.2] Now try that for 2 elements per list, then 3. In effect you move elements from list 2 to list 1, or vice versa. And you iterate over the list multiple times. It's very inefficient as well as non intuitive. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Fri Mar 4 14:41:53 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 4 Mar 2016 19:41:53 +0000 Subject: [Tutor] recursivity and lists In-Reply-To: <176115838.3790398.1457119534060.JavaMail.yahoo@mail.yahoo.com> References: <176115838.3790398.1457119534060.JavaMail.yahoo@mail.yahoo.com> Message-ID: <56D9E501.2070007@btinternet.com> On 04/03/16 19:25, sina sareth wrote: > Hi There Hi, welcome to tutor. But please do not hijack an existing thread for a new topic. Post a new message to tutor at python.org. Otherwise the archive gets very confusing for people searching for answers. Or even for people using threaded email/news readers. > I have those projects and I would like to get some directions the way > to tackle them. > Given that you have provided very little information about your knowledge/skill level as well as the problem we can only give very sketchy advice. > Thanks > > 1) XML parsing into database. > For xml parsing use the etree package For a data base we woyuld need to know what kind of database, what you want to store from the XML etc. > 2) Do the same thing but this time, get ALL the quotes and save What kind of quotes? > them as separate database entries (you will have to do a for loop for > this). > > 3) Use Django to build a view where you can download all Quotes in CSV > form. > Consult the Django tutorial/docs for help with Django. Its outside this groups remit. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From danny.yoo at gmail.com Fri Mar 4 16:29:51 2016 From: danny.yoo at gmail.com (Danny Yoo) Date: Fri, 4 Mar 2016 13:29:51 -0800 Subject: [Tutor] recursivity and lists In-Reply-To: References: Message-ID: > Both work but I am not satisfied. Is there not a method that could do the job of '+' operator (namely concatenate in a copy)? > No; unfortunately Python doesn't make functional approaches as convenient as I would personally like. The copy operation on lists itself is expensive to do, so that's why I think the list API encourages a mutational approach. If we were to define our own data structures, we could make the functional approach more natural and efficient. > As for my first code : > > def linear_merge1(list1, list2): > > if list1==[]: return list2 > elif list2==[]: return list1 > elif list1[-1]>list2[-1]: > a=list1.pop() > linear_merge(list1,list2).append(a) > return linear_merge(list1,list2) > else: > a=list2.pop() > linear_merge(list1,list2).append(a) > return linear_merge(list1,list2) > > > I don't get why it works to be fair. It feels like return linear_merge(list1,list2) does not call the function again. That's because the behavior of this version is weird. :) Its contact could be stated as follows: ---------------------------------------- Given two sorted lists, linear_merge1 does the following three things: A. Mutates one of the lists to be empty, B. Mutates the other list have the merge-sorted results, and C. Returns the reference to the merge-sorted list. ---------------------------------------- How can we be sure? We can prove this to ourselves by inductive proof. We'll do the induction based on the combined number of elements list1 and list2. Call this combined size 'n'. Base case: if n = 0, then both list1 and list2 are empty, and all three conditions A, B, and C hold trivially. That's easy enough. Ok, time for the analysis for the n > 0 case. As our induction hypothesis, assume that all three conditions A, B, and C are true when we call linear_merge1 for input with a combined size < n. We want to show that, if we're assuming that the induction hypothesis is true for those smaller input sizes, then those three conditions will continue to hold for the case where the input is of size n. There are two cases we consider, when considering the case where the input size n > 0. We break our case analysis into two situations that cover the gamut of possibility: Case 1: either list1 or list2 is empty. If this is true, then we hit one of the two initial cases in the code that check for emptiness. Since one of the lists is already empty, it doesn't need to be mutated, so condition A holds. Since both input lists were already sorted, then case B holds. Finally, case C holds because it's returning that list. Case 2: neither list1 nor list2 is empty. Let's first consider the case where list1[-1] > list2[-1]. Then when we perform: a = list1.pop() list1 still is a sorted list, though it is smaller. When we call: linear_merge(list1,list2).append(a) then, since the combined size of list1 and list2 is now less than n, we can apply our induction hypothesis. Then we can assume that the following things happen: * either list1 or list2 empties out, due to condition A being applied to the smaller input. * we add the element 'a' to whichever merge-sorted list was returned by the recursive call. After that call, either list1 or list2 contain the merge-sorted results, and the other list is empty. Finally, the funky second call to: return linear_merge(list1, list2) will return either list1 or list2, because we know that, from the prior call, one of those lists is empty due to the operation of that first recursive call. We now know that what gets returned here is the reference to the list that has the merge-sorted results. Ok, that closes that chain of reasoning for the case where list1[-1] > list2[-1]. And since we can make a similar chain of reasoning for the other case, we can stop here. --- That's a rough math proof sketch of why linear_merge1 is working for you. As we can see, we have to do a lot more consideration of what state our values are in, due to all the mutation happening. It also shows that the second recursive call to the linear_merge() is not really using it to merge: it's really trying to select the list that was used to accumulate results. We'd get the same results with: ###################################### def linear_merge1(list1, list2): if list1==[]: return list2 elif list2==[]: return list1 elif list1[-1]>list2[-1]: a=list1.pop() linear_merge(list1,list2).append(a) return list1 or list2 else: a=list2.pop() linear_merge(list1,list2).append(a) return list1 or list2 ###################################### and depend on Python to determine which value is truthy, which in the case of lists, will prefer the non-empty lists. That is, the second recursive calls are red herrings. That's what initially made me do a double-take when I saw it, and I had to reason to myself why in the world it was working: it's all due to the mutational aspects of that approach. So, yeah, the code is *much* too clever for it's own good. :P From danny.yoo at gmail.com Fri Mar 4 16:33:58 2016 From: danny.yoo at gmail.com (Danny Yoo) Date: Fri, 4 Mar 2016 13:33:58 -0800 Subject: [Tutor] recursivity and lists In-Reply-To: References: Message-ID: > As we can see, we have to do a lot more consideration of what state > our values are in, due to all the mutation happening. It also shows > that the second recursive call to the linear_merge() is not really > using it to merge: it's really trying to select the list that was used > to accumulate results. We'd get the same results with: > > ###################################### > def linear_merge1(list1, list2): > if list1==[]: return list2 > elif list2==[]: return list1 > elif list1[-1]>list2[-1]: > a=list1.pop() > linear_merge(list1,list2).append(a) > return list1 or list2 > else: > a=list2.pop() > linear_merge(list1,list2).append(a) > return list1 or list2 > ###################################### Sorry: I made a mistake when typing out the internal recursive calls. Substitute 'linear_merge1' in places where it had 'linear_merge'. ##################################### def linear_merge1(list1, list2): if list1==[]: return list2 elif list2==[]: return list1 elif list1[-1]>list2[-1]: a=list1.pop() linear_merge1(list1,list2).append(a) return list1 or list2 else: a=list2.pop() linear_merge1(list1,list2).append(a) return list1 or list2 ###################################### > So, yeah, the code is *much* too clever for it's own good. :P Substitute "it's" with "its". From sinasareth at yahoo.com Fri Mar 4 14:25:34 2016 From: sinasareth at yahoo.com (sina sareth) Date: Fri, 4 Mar 2016 19:25:34 +0000 (UTC) Subject: [Tutor] recursivity and lists In-Reply-To: References: Message-ID: <176115838.3790398.1457119534060.JavaMail.yahoo@mail.yahoo.com> Hi ThereI have those projects and I would like to get some directions the way to tackle them. Thanks 1) ?XML parsing into database.? 2) Do the same thing but this time, get ALL the quotes and save them as separate database entries (you will have to do a for loop for this).? 3) Use Django to build a view where you can download all Quotes in CSV form.? 4. Use Django to build a view where you can update quote values based on a call to the API (they change every day) On Friday, March 4, 2016 11:14 AM, Alan Gauld wrote: On 04/03/16 15:00, Gaston wrote: > Both work but I am not satisfied. Is there not a method that could do > the job of '+' operator (namely concatenate in a copy)? Why would you want a method? An operator is a perfectly legitimate feature and is at least as readable as a method. It is certainly no less "functional". And of course, in Python + usually translates to the __add__() method anyway. As to how your initial function works can I suggest you sit down with a pen and paper and work through the code iteration by iteration. Start with 2 element lists and then try 3 elements. By the time you've done that it should become clear. Keep track of the contents of list1 and list2 and the output for each call of the function. Recursive can be a seductive technique but it can be a real brain twister to work out and debug when things don;t go as expected! The pen/paper manual approach is the most reliable technique I've found. Here is what I mean for a 2 element list pair: list1??? ??? list2??? ??? f(list1,list2) ----------------------------------------------- [1]??? ??? [2]??? ??? f([1],[]).append(2) # first call of f() [1]??? ??? []??? ??? [1].append(2) -> list1 becomes [1,2] [1,2]? ? ? ? ? []? ? ? ? ? ? ? f([1,2],[])? # 2nd call of f() -> [1.2] Now try that for 2 elements per list, then 3. In effect you move elements from list 2 to list 1, or vice versa. And you iterate over the list multiple times. It's very inefficient as well as non intuitive. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor From nanney.56 at gmail.com Sat Mar 5 08:56:01 2016 From: nanney.56 at gmail.com (Robert Nanney) Date: Sat, 5 Mar 2016 07:56:01 -0600 Subject: [Tutor] recursivity and lists In-Reply-To: References: Message-ID: Would this meet the requirements? merged_list = list1.extend(list2).sort() On Mar 4, 2016 3:34 PM, "Danny Yoo" wrote: > > As we can see, we have to do a lot more consideration of what state > > our values are in, due to all the mutation happening. It also shows > > that the second recursive call to the linear_merge() is not really > > using it to merge: it's really trying to select the list that was used > > to accumulate results. We'd get the same results with: > > > > ###################################### > > def linear_merge1(list1, list2): > > if list1==[]: return list2 > > elif list2==[]: return list1 > > elif list1[-1]>list2[-1]: > > a=list1.pop() > > linear_merge(list1,list2).append(a) > > return list1 or list2 > > else: > > a=list2.pop() > > linear_merge(list1,list2).append(a) > > return list1 or list2 > > ###################################### > > > Sorry: I made a mistake when typing out the internal recursive calls. > Substitute 'linear_merge1' in places where it had 'linear_merge'. > > ##################################### > def linear_merge1(list1, list2): > if list1==[]: return list2 > elif list2==[]: return list1 > elif list1[-1]>list2[-1]: > a=list1.pop() > linear_merge1(list1,list2).append(a) > return list1 or list2 > else: > a=list2.pop() > linear_merge1(list1,list2).append(a) > return list1 or list2 > ###################################### > > > > > So, yeah, the code is *much* too clever for it's own good. :P > > Substitute "it's" with "its". > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From danny.yoo at gmail.com Sat Mar 5 13:46:21 2016 From: danny.yoo at gmail.com (Danny Yoo) Date: Sat, 5 Mar 2016 10:46:21 -0800 Subject: [Tutor] recursivity and lists In-Reply-To: References: Message-ID: On Mar 5, 2016 5:56 AM, "Robert Nanney" wrote: > > Would this meet the requirements? It's doing a sort, but not in a merging way. Merge sort takes advantage of a property of the input lists: the input lists are known to be already sorted. The general sort routine for lists doesn't take much advantage of the existing order in the input, whereas in merge sorting, the major point is to take advantage of the existing order. From breamoreboy at yahoo.co.uk Fri Mar 4 19:55:51 2016 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 5 Mar 2016 00:55:51 +0000 Subject: [Tutor] recursivity and lists In-Reply-To: <176115838.3790398.1457119534060.JavaMail.yahoo@mail.yahoo.com> References: <176115838.3790398.1457119534060.JavaMail.yahoo@mail.yahoo.com> Message-ID: On 04/03/2016 19:25, sina sareth via Tutor wrote: > Hi ThereI have those projects and I would like to get some directions the way to tackle them. > Thanks > 1) XML parsing into database. > 2) Do the same thing but this time, get ALL the quotes and save them as separate database entries (you will have to do a for loop for this). > 3) Use Django to build a view where you can download all Quotes in CSV form. > 4. Use Django to build a view where you can update quote values based on a call to the API (they change every day) > There is no point in hijacking another thread to ask questions about a complicated framework, which is way out of scope for this tutor list, which deals with the core Python language and its standard library. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From robertvstepp at gmail.com Sat Mar 5 18:20:21 2016 From: robertvstepp at gmail.com (boB Stepp) Date: Sat, 5 Mar 2016 17:20:21 -0600 Subject: [Tutor] Why does 01 give a syntax error, but 00 (or 00...0) does not? Message-ID: >>> 01 File "", line 1 01 ^ SyntaxError: invalid token >>> 00 0 >>> -00 0 >>> 000 0 Why do zeros not give a syntax error, but other numbers with a leading zero do give a syntax error? An online search reveals that in Python 2 a leading 0 starts an octal number, but this was changed in Python 3. But then why is 00...0 valid, that is, does not give a syntax error? TIA! -- boB From breamoreboy at yahoo.co.uk Sat Mar 5 14:42:16 2016 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 5 Mar 2016 19:42:16 +0000 Subject: [Tutor] recursivity and lists In-Reply-To: References: Message-ID: On 05/03/2016 18:46, Danny Yoo wrote: > On Mar 5, 2016 5:56 AM, "Robert Nanney" wrote: >> >> Would this meet the requirements? > > It's doing a sort, but not in a merging way. Merge sort takes advantage of > a property of the input lists: the input lists are known to be already > sorted. > > The general sort routine for lists doesn't take much advantage of the > existing order in the input, whereas in merge sorting, the major point is > to take advantage of the existing order. Really? https://en.wikipedia.org/wiki/Timsort -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From s.mbr at hotmail.com Sat Mar 5 14:36:57 2016 From: s.mbr at hotmail.com (Saad Mabror) Date: Sat, 5 Mar 2016 19:36:57 +0000 Subject: [Tutor] Help with an error Message-ID: Hello , So i'm totally new to programming and i decided to start with python , i've installed python 2.7 on my laptop (running windows 7 ) at first i started following a begginer's guide and everything was fine . But later i started receveing syntax error dialogues on IDLE even if i'm writing just one simple line such as ( print "hello world") . I already tried uninstalling and reinstalling but that didn't work , so is there any possible way to fix this ? Thanks in Advance . From robertvstepp at gmail.com Sat Mar 5 18:28:24 2016 From: robertvstepp at gmail.com (boB Stepp) Date: Sat, 5 Mar 2016 17:28:24 -0600 Subject: [Tutor] Help with an error In-Reply-To: References: Message-ID: On Sat, Mar 5, 2016 at 1:36 PM, Saad Mabror wrote: > Hello , So i'm totally new to programming and i decided to start with python , i've installed python 2.7 on my laptop (running windows 7 ) at first i started following a begginer's guide and everything was fine . But later i started receveing syntax error dialogues on IDLE even if i'm writing just one simple line such as ( print "hello world") . I already tried uninstalling and reinstalling but that didn't work , so is there any possible way to fix this ? Thanks in Advance . > _______________________________________________ It would be helpful if you would copy and paste into a plain text email to this group exactly what you typed into IDLE and the full trace back of the error message you receive. On a side note, if you are just starting to learn Python and have no special need for Python 2, then you should work on learning Python 3. -- boB From ben+python at benfinney.id.au Sat Mar 5 18:33:38 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 06 Mar 2016 10:33:38 +1100 Subject: [Tutor] Why does 01 give a syntax error, but 00 (or 00...0) does not? References: Message-ID: <85io10sdnx.fsf@benfinney.id.au> boB Stepp writes: > >>> 01 > File "", line 1 > 01 > ^ > SyntaxError: invalid token As you later explain, this is because in Python 3 the obsolete ?leading 0 for octal notation? is invalid syntax. (Superseded by ?leading ?0o? for octal notation?). > >>> 00 > 0 > >>> -00 > 0 > >>> 000 > 0 > > Why do zeros not give a syntax error, but other numbers with a leading > zero do give a syntax error? Hmm. That is a confusing inconsistency, I agree. It is deliberate, and explicitly documented: Note that leading zeros in a non-zero decimal number are not allowed. This is for disambiguation with C-style octal literals, which Python used before version 3.0. which does not explain why ?non-zero decimal number? was chosen, rather than simply any decimal number. > But then why is 00...0 valid, that is, does not give a syntax error? At one level, the answer is: because the language reference declares those rules for the syntax. At another level, the answer is: I don't know why that decision was made, and on the face of it I disagree. -- \ ?But it is permissible to make a judgment after you have | `\ examined the evidence. In some circles it is even encouraged.? | _o__) ?Carl Sagan, _The Burden of Skepticism_, 1987 | Ben Finney From alan.gauld at btinternet.com Sat Mar 5 19:31:03 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 6 Mar 2016 00:31:03 +0000 Subject: [Tutor] Help with an error In-Reply-To: References: Message-ID: On 05/03/16 19:36, Saad Mabror wrote: > i've installed python 2.7 on my laptop (running windows 7 ) > i started receveing syntax error dialogues on IDLE even > if i'm writing just one simple line such as ( print "hello world") . The most likely reason is that you have somehow installed Python v3 and are trying to run code for v2 in v3. What does the IDLE shell window say when it starts? Look at the message that looks like: Python 2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2] on linux2 Type "copyright", "credits" or "license()" for more information. >>> Is it v2.7 or 3.x? If that's not the problem can you cut 'n paste a full transcript of your code and the error message? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Sat Mar 5 19:37:59 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 6 Mar 2016 00:37:59 +0000 Subject: [Tutor] Why does 01 give a syntax error, but 00 (or 00...0) does not? In-Reply-To: <85io10sdnx.fsf@benfinney.id.au> References: <85io10sdnx.fsf@benfinney.id.au> Message-ID: On 05/03/16 23:33, Ben Finney wrote: >> But then why is 00...0 valid, that is, does not give a syntax error? > > At one level, the answer is: because the language reference declares > those rules for the syntax. > > At another level, the answer is: I don't know why that decision was > made, and on the face of it I disagree. I assume because decimal numbers are the default and without this exception you couldn't type 0 without typing 0?0 Where '?' is whatever code is used for decimal. But since its default you don't normally need a code. I'm not even sure what it is? Is there one? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From ben+python at benfinney.id.au Sat Mar 5 19:42:08 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 06 Mar 2016 11:42:08 +1100 Subject: [Tutor] Why does 01 give a syntax error, but 00 (or 00...0) does not? References: <85io10sdnx.fsf@benfinney.id.au> Message-ID: <85a8mcsahr.fsf@benfinney.id.au> Ben Finney writes: > Hmm. That is a confusing inconsistency, I agree. It is deliberate, and > explicitly documented: > > Note that leading zeros in a non-zero decimal number are not > allowed. This is for disambiguation with C-style octal literals, > which Python used before version 3.0. > > > > which does not explain why ?non-zero decimal number? was chosen, rather > than simply any decimal number. I have reported to try to resolve this ambiguity. -- \ ?They who can give up essential liberty to obtain a little | `\ temporary safety, deserve neither liberty nor safety.? | _o__) ?Benjamin Franklin, 1775-02-17 | Ben Finney From robertvstepp at gmail.com Sat Mar 5 23:25:51 2016 From: robertvstepp at gmail.com (boB Stepp) Date: Sat, 5 Mar 2016 22:25:51 -0600 Subject: [Tutor] Surprised that print("a" "b") gives "ab" Message-ID: I stumbled into finding out that >>> "a" "b" 'ab' or >>> print("a""b") ab Note that there is not even a space required between the two strings. I find this is surprising to me as "a" "b" is much less readable to me than "a" + "b" . And since Python is all about easily readable code, why was this feature implemented? Is there a use case where it is more desirable to not have a string concatenation operator explicitly used? The only thing that comes to my mind are strings spread over multiple lines, say print("This will be a ..." "...very long string...") But is this preferable to print("This will be a ..." + "...very long string...") ? I personally prefer the latter, so I am probably missing something. BTW, I am following through (So far!) on my New Year's resolution to persistently work through some Python books. I've knocked off "Python Crash Course", which I think is a fine beginner's book. Now I am starting "Think Python, 2nd ed.", which is an intro to C.Sc.-type book. So I imagine I may come up more questions along the lines of today's--be forewarned! -- boB From steve at pearwood.info Sun Mar 6 00:24:04 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 6 Mar 2016 16:24:04 +1100 Subject: [Tutor] Surprised that print("a" "b") gives "ab" In-Reply-To: References: Message-ID: <20160306052404.GR12028@ando.pearwood.info> On Sat, Mar 05, 2016 at 10:25:51PM -0600, boB Stepp wrote: > I stumbled into finding out that > > >>> "a" "b" > 'ab' > > or > > >>> print("a""b") > ab > > Note that there is not even a space required between the two strings. This is called "implicit concatenation", as opposed to *explicit* concatenation, "a" + "b". You're not alone in disliking this, many others do too, and not just in Python either. E.g. it's also controversial in the D language: https://issues.dlang.org/show_bug.cgi?id=3827 > I find this is surprising to me as "a" "b" is much less readable to me > than "a" + "b" . And since Python is all about easily readable code, > why was this feature implemented? Is there a use case where it is > more desirable to not have a string concatenation operator explicitly > used? I don't know that I would agree that Python is ALL about easily readable code. Surely there are other factors too, even if they are not weighted as heavily. There are a few reasons for implicit concatenation. On their own, I don't think they would be enough to justify the feature, but taken all together, I think it was enough to justify the feature. Firstly, I think the feature was copied straight out of C/C++ where it does have an rationale: http://stackoverflow.com/questions/2504536/why-allow-concatenation-of-string-literals In the early days of Python, concatenation of string literals using + would take place at runtime, which meant that it could be quite inefficient. Something like this: s = "ab" + "cd" + "ef" + "gh" + "ij" + "kl" would involve making, then destroying, ten temporary strings (plus an eleventh, the final result for s), for a total runtime cost proportional to the number of characters SQUARED. Using implicit concatenation: s = "ab" "cd" "ef" "gh" "ij" "kl" meant that the interpreter could do the work more efficiently at compile-time, generating a single string. (These days, the standard CPython interpreter can do the same with the + operator, although other implementations may not be so smart.) Of course, if you're writing "ab" "cd" "ef" "gh" "ij" "kl" instead of the more sensible "abcdefghijkl" then you deserve to be smacked, but there is a good use for these: mixing quote marks. Suppose I need to build a string with just one kind of quote mark. Then I can use the other quote mark as the delimiter: s = 'the " double quote mark' What if I need both kinds? I can using escaping: s = 'the " double quote mark and the \' single quote mark' but escaping starts to get ugly. I could use *triple* quotes: s = """the " double quote mark and the ' single quote mark""" but what happens if I need to include *triple* quotes of *both* kinds in the same string? Whatever you do, things are getting messy. But, we can do this: s = 'the " double quote mark ' "and the ' single quote mark" Whether you consider that an improvement or not is probably a matter or your own personal taste. These days, I think that most people would agree that implicit concatenation is kept for backwards compatibility, and that if Python was designed from scratch today, for better or worse it probably wouldn't have that feature. -- Steve From steve at pearwood.info Sun Mar 6 00:32:39 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 6 Mar 2016 16:32:39 +1100 Subject: [Tutor] Why does 01 give a syntax error, but 00 (or 00...0) does not? In-Reply-To: References: Message-ID: <20160306053239.GT12028@ando.pearwood.info> On Sat, Mar 05, 2016 at 05:20:21PM -0600, boB Stepp wrote: > Why do zeros not give a syntax error, but other numbers with a leading > zero do give a syntax error? An online search reveals that in Python > 2 a leading 0 starts an octal number, but this was changed in Python > 3. But then why is 00...0 valid, that is, does not give a syntax > error? No reason. It's just a historical accident, and with no real harm done, people decided it's not worth fixing: http://bugs.python.org/issue24668 -- Steve From robertvstepp at gmail.com Sun Mar 6 01:28:45 2016 From: robertvstepp at gmail.com (boB Stepp) Date: Sun, 6 Mar 2016 00:28:45 -0600 Subject: [Tutor] Why does 01 give a syntax error, but 00 (or 00...0) does not? In-Reply-To: <20160306053239.GT12028@ando.pearwood.info> References: <20160306053239.GT12028@ando.pearwood.info> Message-ID: On Sat, Mar 5, 2016 at 11:32 PM, Steven D'Aprano wrote: > On Sat, Mar 05, 2016 at 05:20:21PM -0600, boB Stepp wrote: > >> Why do zeros not give a syntax error, but other numbers with a leading >> zero do give a syntax error? An online search reveals that in Python >> 2 a leading 0 starts an octal number, but this was changed in Python >> 3. But then why is 00...0 valid, that is, does not give a syntax >> error? > > No reason. It's just a historical accident, and with no real harm done, > people decided it's not worth fixing: > > http://bugs.python.org/issue24668 Hmm. Thanks, Steve, as well as your detailed answer to the other question I posed tonight. On this thread, I am curious about one of the statements in the bug report you linked to: Author: Georg Brandl [...] Since the direction we're going is to allow leading zeros for all decimal literals in Python 4 (if it ever comes around), that's another reason for the status quo to win. Sounds like, in retrospect, Python 3 should have had this behavior implemented, but I am guessing that it was thought more important to emphasize the new octal literal syntax in Py 3 and eliminate the leading zero entirely (except for the special case of zero, which must have slipped through the cracks somehow). -- boB From ben+python at benfinney.id.au Sun Mar 6 01:37:44 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 06 Mar 2016 17:37:44 +1100 Subject: [Tutor] Surprised that print("a" "b") gives "ab" References: Message-ID: <8537s4ru13.fsf@benfinney.id.au> boB Stepp writes: > [?] why was this feature implemented? You've been asking that a lot lately :-) This forum is unlikely to be able to give authoritative answers to ?why was the language designed the way it is??. We are more able to explain what justification there is for a behaviour remaining as it is. That's a different question, though. > Is there a use case where it is more desirable to not have a string > concatenation operator explicitly used? The only thing that comes to > my mind are strings spread over multiple lines, say > > print("This will be a ..." > "...very long string...") > > But is this preferable to > > print("This will be a ..." + > "...very long string...") > > ? I personally prefer the latter, so I am probably missing something. It is salient to this issue, that the two cases above are semantically different. The first one is defined (by the syntax for literals) to create a *single* string object. Semantically, the fragments are specifying one object in a single step. The second is semantically (i.e. by the semantics of how such expressions are defined to work) creating two distinct objects, then creating a third using an operation, then discarding the first two. For me, that makes a big difference. When strings need to be split over several lines, it is convenient to be able to express directly in the code ?these fragments are intended to be all part of the same object?. And it helps to see that in other people's code, too. I am sympathetic to the small visible difference between your two examples, and I don't deny that others may not find this feature as convenient or elegant as I do. -- \ ?The long-term solution to mountains of waste is not more | `\ landfill sites but fewer shopping centres.? ?Clive Hamilton, | _o__) _Affluenza_, 2005 | Ben Finney From ben+python at benfinney.id.au Sun Mar 6 01:47:08 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 06 Mar 2016 17:47:08 +1100 Subject: [Tutor] Surprised that print("a" "b") gives "ab" References: <8537s4ru13.fsf@benfinney.id.au> Message-ID: <85y49wqf0z.fsf@benfinney.id.au> Ben Finney writes: > The first one is defined (by the syntax for literals) to create a > *single* string object. Semantically, the fragments are specifying one > object in a single step. > > The second is semantically (i.e. by the semantics of how such > expressions are defined to work) creating two distinct objects, then > creating a third using an operation, then discarding the first two. Because I know there are resident pedants who love to get into the details: I know that's not exactly how it works internally, and it doesn't matter. I'm not talking about what bytecode is produced, I'm talking about the semantics of what the language reference defines: ?+? implies that a new object will be created by calling ?__add__? or ?__radd__?. What the optimiser decides to omit is not relevant to that point: the semantics of the ?+? operator imples that a third object will result from combining two other objects. -- \ Moriarty: ?Forty thousand million billion dollars? That money | `\ must be worth a fortune!? ?The Goon Show, _The Sale of | _o__) Manhattan_ | Ben Finney From robertvstepp at gmail.com Sun Mar 6 02:03:01 2016 From: robertvstepp at gmail.com (boB Stepp) Date: Sun, 6 Mar 2016 01:03:01 -0600 Subject: [Tutor] Surprised that print("a" "b") gives "ab" In-Reply-To: <8537s4ru13.fsf@benfinney.id.au> References: <8537s4ru13.fsf@benfinney.id.au> Message-ID: On Sun, Mar 6, 2016 at 12:37 AM, Ben Finney wrote: > boB Stepp writes: > >> [?] why was this feature implemented? > > You've been asking that a lot lately :-) This forum is unlikely to be > able to give authoritative answers to ?why was the language designed the > way it is??. While I *am* quite interested in the why's of Python's design, my question was actually intended to find out in what situation(s) implicit string concatenation is a better choice than the explicit approach. And you gave me something to think about later in your response. I have to add, though, that I *do* think it is useful in this forum to consider the design choices that led to Python's feature set and syntax. Not at an incredibly deep level, but, instead, to acquire the pythonista's philosophy of programming. I think that understanding such things will help me to use the language more in line with how it is meant to be used. >> Is there a use case where it is more desirable to not have a string >> concatenation operator explicitly used? The only thing that comes to >> my mind are strings spread over multiple lines, say >> >> print("This will be a ..." >> "...very long string...") >> >> But is this preferable to >> >> print("This will be a ..." + >> "...very long string...") >> >> ? I personally prefer the latter, so I am probably missing something. > > It is salient to this issue, that the two cases above are semantically > different. > > The first one is defined (by the syntax for literals) to create a > *single* string object. Semantically, the fragments are specifying one > object in a single step. > > The second is semantically (i.e. by the semantics of how such > expressions are defined to work) creating two distinct objects, then > creating a third using an operation, then discarding the first two. Under the hood, are the two approaches above done in the same way? I get your semantics point, but are there two string objects created in both approaches or does the first in fact create only a single object? If the first truly only creates a single object, then it seems that this is a more efficient approach. -- boB From ben+python at benfinney.id.au Sun Mar 6 02:30:14 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 06 Mar 2016 18:30:14 +1100 Subject: [Tutor] Surprised that print("a" "b") gives "ab" References: <8537s4ru13.fsf@benfinney.id.au> Message-ID: <85twkkqd15.fsf@benfinney.id.au> boB Stepp writes: > Under the hood, are the two approaches above done in the same way? I > get your semantics point, but are there two string objects created in > both approaches or does the first in fact create only a single object? Sometimes, it does. That's an implementation detail, and the behaviour is not guaranteed and can change at any time, even within the exact same program. So it's not something worth considering when writing or reading that code for semantics. > If the first truly only creates a single object, then it seems that > this is a more efficient approach. That's the danger. Consider efficiency of the implementation to be not your job, when learning the language. Far more important are clear expression of intent, and ease of finding errors. -- \ ?You can't have everything; where would you put it?? ?Steven | `\ Wright | _o__) | Ben Finney From steve at pearwood.info Sun Mar 6 10:28:07 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 7 Mar 2016 02:28:07 +1100 Subject: [Tutor] Surprised that print("a" "b") gives "ab" In-Reply-To: <8537s4ru13.fsf@benfinney.id.au> References: <8537s4ru13.fsf@benfinney.id.au> Message-ID: <20160306152807.GV12028@ando.pearwood.info> On Sun, Mar 06, 2016 at 05:37:44PM +1100, Ben Finney wrote: > boB Stepp writes: > > > [?] why was this feature implemented? > > You've been asking that a lot lately :-) This forum is unlikely to be > able to give authoritative answers to ?why was the language designed the > way it is??. Well, some of us have been reading, and contributing to, the python-ideas and python-dev mailing lists for many years, and so may have an idea of the *why* certain features exist. Sometimes the reason is explained in a PEP ("Python Enhancement Proposal") or in the bug tracker, or occasionally in one of Guido's blog posts. So feel free to ask, and if we can answer, we will. > We are more able to explain what justification there is for a behaviour > remaining as it is. That's a different question, though. > > > Is there a use case where it is more desirable to not have a string > > concatenation operator explicitly used? The only thing that comes to > > my mind are strings spread over multiple lines, say > > > > print("This will be a ..." > > "...very long string...") > > > > But is this preferable to > > > > print("This will be a ..." + > > "...very long string...") > > > > ? I personally prefer the latter, so I am probably missing something. > > It is salient to this issue, that the two cases above are semantically > different. Hmmm. Well, maybe. The problem is, if it is a difference that makes no difference, is it still a difference? > The first one is defined (by the syntax for literals) to create a > *single* string object. Semantically, the fragments are specifying one > object in a single step. This part is certainly true. Implicit concatenation must take place during the parsing/compiling stage, before any code is run, which implies that at run time there is only a single string object produced. > The second is semantically (i.e. by the semantics of how such > expressions are defined to work) creating two distinct objects, then > creating a third using an operation, then discarding the first two. This is the "maybe" part. Ben is correct to point out that according to the language rules, a line of code like: s = "Hello " + "World!" is parsed as: create the string "Hello " create the string "World!" call the + operator on those two string literals But the thing is, because they must be string literals and not variables, the compiler also knows that the + operator has to perform string concatenation. There can't be any side-effects (apart from time and memory use). So recent versions of CPython at least (and possibly other Pythons) will perform "constant folding", which is to perform as much of the work at compile-time as possible, and leading to the semantically identical result: create the string "Hello World!" Is that different from what the language semantics state? Yes, but there's no to see that difference (except indirectly, in memory usage and speed). As Ben will point out, this is not a language guarantee, but it is a current feature of at least some implementations, that simple arithmetic expressions and string concatenations involving only literals are done at compile-time, rather than run-time. > For me, that makes a big difference. When strings need to be split over > several lines, it is convenient to be able to express directly in the > code ?these fragments are intended to be all part of the same object?. > And it helps to see that in other people's code, too. I concur with Ben on this. I like to use implicit concatentation for long strings split over multiple lines for readability: class X: def method(self): if some_condition: raise ValueError( "This is a long error message which is too" " long to fit in one line, so I split it into" " shorter fragments, one per line, and allow" " implicit concatenation to join them." ) -- Steve From steve at pearwood.info Sun Mar 6 10:52:39 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 7 Mar 2016 02:52:39 +1100 Subject: [Tutor] Surprised that print("a" "b") gives "ab" In-Reply-To: References: <8537s4ru13.fsf@benfinney.id.au> Message-ID: <20160306155239.GW12028@ando.pearwood.info> On Sun, Mar 06, 2016 at 01:03:01AM -0600, boB Stepp wrote: > Under the hood, are the two approaches above done in the same way? Probably not, but the true answer will surely depend on which implementation and version of Python we are talking about. When you run Python code, there are a number of separate stages that the interpreter/compiler may potentially perform: - lexing and parsing: this is when the interpreter reads the source code and generates "tokens" for futher processing; - the tokens may be then arranged into a parse tree; - which is usually just a temporary intermediate representation prior to being arranged into an abstract syntax tree (which is much easier to process); - the AST is then processed into byte-code for the Python virtual machine (or, in principle, machine-code for a real machine); - finally the virtual machine executes the byte-code, creating any objects need to be created and processing them. In principle, either implicit or explicit concatenation could be performed at *any* of these stages, so long as it is performed. My *guess* is that any Python implementation will perform implicit concatenation during the parsing and lexing stage, because it doesn't make sense to delay it later. On the other hand, explicit concatenation with a plus sign is more likely to be done at the AST level, or possibly even later. Or not optimized at all. > I > get your semantics point, but are there two string objects created in > both approaches or does the first in fact create only a single object? > If the first truly only creates a single object, then it seems that > this is a more efficient approach. In practical terms, in CPython today, there is no difference between the two, or if there is any difference, it's undetectible: by the time the compiler has generated the byte-code, the concatenation has been performed: py> import dis py> code = compile(""" ... a = 'ab' 'cd' ... b = 'ab' + 'cd' ... """, "", "exec") py> dis.dis(code) 2 0 LOAD_CONST 0 ('abcd') 3 STORE_NAME 0 (a) 3 6 LOAD_CONST 4 ('abcd') 9 STORE_NAME 1 (b) 12 LOAD_CONST 3 (None) 15 RETURN_VALUE This may not apply to future versions, or other implementations. -- Steve From eryksun at gmail.com Sun Mar 6 15:48:21 2016 From: eryksun at gmail.com (eryk sun) Date: Sun, 6 Mar 2016 14:48:21 -0600 Subject: [Tutor] Surprised that print("a" "b") gives "ab" In-Reply-To: <20160306155239.GW12028@ando.pearwood.info> References: <8537s4ru13.fsf@benfinney.id.au> <20160306155239.GW12028@ando.pearwood.info> Message-ID: On Sun, Mar 6, 2016 at 9:52 AM, Steven D'Aprano wrote: > On Sun, Mar 06, 2016 at 01:03:01AM -0600, boB Stepp wrote: > >> get your semantics point, but are there two string objects created in >> both approaches or does the first in fact create only a single object? >> If the first truly only creates a single object, then it seems that >> this is a more efficient approach. > > In practical terms, in CPython today, there is no difference between the > two, or if there is any difference, it's undetectible: by the time the > compiler has generated the byte-code, the concatenation has been > performed: > > py> import dis > py> code = compile(""" > ... a = 'ab' 'cd' > ... b = 'ab' + 'cd' > ... """, "", "exec") > py> dis.dis(code) > 2 0 LOAD_CONST 0 ('abcd') > 3 STORE_NAME 0 (a) > > 3 6 LOAD_CONST 4 ('abcd') > 9 STORE_NAME 1 (b) > 12 LOAD_CONST 3 (None) > 15 RETURN_VALUE Note that when CPython's bytecode optimizer folds binary operations on operands that are sized constants, such as strings, the size of the resulting constant is limited to 20 items (e.g. characters in the case of strings). In either case, the original constants are still stored in the resulting code object (and when marshalled in .pyc files) for simplicity since otherwise it would have to track when a constant is no longer referenced by the final code. >>> code = compile('"9876543210" + "0123456789";' ... '"4321098765" + "56789012345"', ... '', 'exec') >>> code.co_consts ('9876543210', '0123456789', '4321098765', '56789012345', None, '98765432100123456789') >>> dis.dis(code) 1 0 LOAD_CONST 5 ('98765432100123456789') 3 POP_TOP 4 LOAD_CONST 2 ('4321098765') 7 LOAD_CONST 3 ('56789012345') 10 BINARY_ADD 11 POP_TOP 12 LOAD_CONST 4 (None) 15 RETURN_VALUE Note that "98765432100123456789" is listed after None in co_consts because it was appended in the optimization stage. From fosiul at gmail.com Sun Mar 6 13:39:54 2016 From: fosiul at gmail.com (Fosiul Alam) Date: Sun, 6 Mar 2016 18:39:54 +0000 Subject: [Tutor] How to compare dates which has (,) Message-ID: Hi , my bellow codes work ok to compare date and time for perticular format example Feb 7 07:33:19 , but I am not understanding how do i capture and compare dates in bellow formate (,) : also, i having trouble to implement this in python : grep -E -A5 -B3 So basically what i am want is : SCAN all log files in last 30 minutes for key word like ERROR and give me out put like grep -E -A5 -B3 bbbbbbbbbbbbbbbbbbbbbbbbbbbbb bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb bbbbbbbbbbbbbbbbbbbbbbbbbb.> bbbbbbbbbbbbbbbbbbbbbbbbbbccc ccccccccccccccccccccccccc..> My curent code which works for bellow format : #Feb 7 07:33:19 xxxx yum[17961]: Installed: vsftpd-2.2.2-14.el6.x86_64 get_date = re.compile('([A-Z-a-z]+ [0-9]+ [0-9]+:[0-9]+:[0-9]+)(.*)') current_time = datetime.datetime.now() lastHourTime = datetime.datetime.now() - datetime.timedelta(hours = 1) def _read_log(): with open (LOG_FILE,'r')as f: content=f.readlines() return content if __name__ == '__main__': log_file=_read_log() last_execution_time=_get_last_log_time() for line in log_file: #GEt the Date only from the log file Feb 7 07:33:19 match=re.search(get_date,line) if match: #Capture only the date field so taht we can compare iet with (current_time and lastHourTime. #log_date= match.group(1).rstrip() log_date = datetime.datetime.strptime(match.group(1).rstrip(), "%b %d %H:%M:%S").replace(year=datetime.date.today().year) #log_date='Feb 7 07:33:19' #print ('Log Date %s' %log_date) #Check if log_date is greater then lastHourTime and less then current_time if log_date < current_time and log_date > lastHourTime : new_log.append(line) print new_log any help will be really appreciate Thanks From syedzaidi85 at hotmail.co.uk Tue Mar 8 02:33:23 2016 From: syedzaidi85 at hotmail.co.uk (syed zaidi) Date: Tue, 8 Mar 2016 07:33:23 +0000 Subject: [Tutor] FASTA FILE SUB-SEQUENCE EXTRACTION In-Reply-To: References: , Message-ID: Hello all, I am stuck in a problem, I hope someone can help me out. I have a FASTA file with multiple sequences and another file with the gene coordinates. SAMPLEFASTA FILE: >EBM_revised_C2034_1 length=611GCAGCAGTGGGGAATATTGCACAATGGGCGCAAGCCTGATGCAGCCATGCCGCGTGTATGAAGAAGGCCTTCGGGTTGTAAAGTACTTTCAGCGGGGAGGAAGGGAGTAAAGTTAATACCTTTGCTCATTGACGTTACCCGCAGAAGAAGCACCGGCTAACTCCGTGCCAGCAGCCGCGGTAATACGGAGGGTGCAAGCGTTAATCGGAATTACTGGGCGTAAAGCGCACGCAGGCGGTTTGTTAAGTCAGATGTGAAATCCCCGGGCTCAACCTGGGAACTGCATCTGATACTGGCAAGCTTGAGTCTCGTAGAGGGGGGTAGAATTCCAGGTGTAGCGGTGAAATGCGTAGAGATCTGGAGGAATACCGGTGGCGAAGGCGGCCCCCTGGACGAAGACTGACGCTCAGGTGCGAAAGCGTGGGGAGCAAACAGGATTAGATACCCTGGTAGTCCACGCCGTAAACGATGTCGACTTGGAGGTTGTGCCCTTGAGGCGTGGCTTCCGGAGCTAACGCGTTAAGTCGACCGCCTGGGGAGTACGGCCGCAAGGTTAAAACTCAAATGAATTGACGGGGGCCCGCACAAGCGGTGGAGCATGTGGTTTAATT>EBM_revised_C2104_1 length=923TCCGAGGGCGGTGGGATGTTGGTGCTGCAGCGGCTTTCGGATGCGCGGCGGTTGGGTCATCCGGTGTTGGCGGTGGTGGTCGGGTCGGCGGTTAATCAGGATGGGGCGTCGAATGGGTTGACCGCGCCTAATGGTCCTTCGCAGCAGCGGGTGGTGCGGGCGGCGTTGGCCAATGCCGGGTTGAGCGCGGCCGAGGTGGATGTGGTGGAGGGGCATGGGACCGGGACCACGTTGGGGGATCCGATTGAGGCTCAGGCGTTGTTGGCCACTTATGGGCAAGATCGGGGGGAGCCGGGAGAACCTTTGTGGTTGGGGTCGGTGAAGTCGAATATGGGTCATACGCAGGCCGCGGCGGGGGTGGCCGGGGTGATCAAGATGGTGTTGGCGATGCGCCATGAGCTGTTGCCGGCGACGTTGCACGTGGATGTGCCTAGCCCGCATGTGGATTGGTCGGCGGGGGCGGTGGAGTTGTTGACCGCGCCGCGGGTGTGGCCTGCTGGTGCTCGGACGCGTCGTGCGGGGGTGTCGTCGTTTGGGATTAGTGGCACTAATGCGCATGTGATTATCGAGGCGGTGCCGGTGGTGCCGCGGCGGGAGGCTGGTTGGGCGGGGCCGGTGGTGCCGTGGGTGGTGTCGGCGAAGTCGGAGTCGGCGTTGCGGGGGCAGGCGGCTCGGTTGGCCGCGTACGTGCGTGGCGATGATGGCCTCGATGTTGCCGATGTGGGGTGGTCGTTGGCGGGTCGTTCGGTTTTTGAGCATCGGGCGGTGGTGGTTGGCGGGGACCGTGATCGGTTGTTGGCCGGGCTCGATGAGCTGGCGGGTGACCAGTTGGGCGGCTCGGTTGTTCGGGGCACGGCGACTGCGGCGGGTAAGACGGTGTTCGTCTTCCCCGGCCAAGGCTCCCAATGGCTGGGCATGGGAAT GENE COORD FILEScaf_name Gene_name DS_St DS_EnEBM_revised_C2034_1 gene1_1 33 99EBM_revised_C2034_1 gene1_1 55 100EBM_revised_C2034_1 gene1_1 111 150EBM_revised_C2104_1 gene1_1 44 70 I want to perform the following steps:compare the scaf_name with the header of fasta sequenceif header matches then process the sequence and extract the sequence by the provided start and end positions. I would appreciate if someone can help Thanks Best Regards Ali > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Tue Mar 8 03:19:40 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 8 Mar 2016 08:19:40 +0000 Subject: [Tutor] FASTA FILE SUB-SEQUENCE EXTRACTION In-Reply-To: References: Message-ID: On 08/03/16 07:33, syed zaidi wrote: > Hello all, Hello, For future reference, please do not hijack an old thread for a new topic - a) it messes up0 the archives for searching b) it means those using threaded readers will probably not see your message > I am stuck in a problem, I hope someone can help me out. I have a FASTA file There are specialist libraries for reading processing fasta data. Are you using one of those, if so which? Thee are also general purpose Bio science libraries within the SciPy and SciKit bundles that may help you. Their support forums are also much more likely to have the specialist knowledge on how to use these tools. This forum is concerned with core Python language issues. It will also help if you tell us which OS and Python version you are using. > .... > I want to perform the following steps: > compare the scaf_name with the header of fasta sequence > if header matches then process the sequence > and extract the sequence by the provided start and end positions. OK, There are three clear steps there. Have you written any code for any of them? If so show us, along with any error messages. Do you have a specific issue where you need help? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From bfishbein79 at gmail.com Tue Mar 8 05:00:10 2016 From: bfishbein79 at gmail.com (Benjamin Fishbein) Date: Tue, 8 Mar 2016 04:00:10 -0600 Subject: [Tutor] simulating key presses Message-ID: <0CC938F6-E55A-4DD7-B301-889644DECAFC@gmail.com> Despite scouring stack overflow and other places, I can?t figure out how to simulate key presses. I?m using Mac 10.10.5. Most answers to this involve sending keys to an element, but my problem is that I have no element to send to; I?m trying to automate key presses for choosing (browsing) a file in the Finder window. Any help is much appreciated. From s.shall at virginmedia.com Tue Mar 8 08:00:33 2016 From: s.shall at virginmedia.com (Sydney Shall) Date: Tue, 8 Mar 2016 13:00:33 +0000 Subject: [Tutor] Fasta Identy Message-ID: <56DECCF1.6030700@virginmedia.com> Dear Ali, I suggest your best way is to use the resource at the EMBL or the National Library of Congress, NIH, resources. There you can compare your FASTA sequences with authentic databases. The programs know about FASTA and will recognise the format. It will identify the gene for you. And it will give you a link to all the available data on that gene. -- Sydney From alan.gauld at btinternet.com Tue Mar 8 11:33:15 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 8 Mar 2016 16:33:15 +0000 Subject: [Tutor] simulating key presses In-Reply-To: <0CC938F6-E55A-4DD7-B301-889644DECAFC@gmail.com> References: <0CC938F6-E55A-4DD7-B301-889644DECAFC@gmail.com> Message-ID: On 08/03/16 10:00, Benjamin Fishbein wrote: > Despite scouring stack overflow and other places, I can?t figure out how to simulate key presses. > I?m using Mac 10.10.5. > Most answers to this involve sending keys to an element, but my problem is that I have no element to send to; I?m trying to automate key presses for choosing (browsing) a file in the Finder window. > Any help is much appreciated. This is specific to your GUI toolkit, in your case Cocoa. You will need to look in the Apple documentation for Cocoa on the Apple develop site then see if the required functionality is made available in the Python Cocoa bindings available from the MacPython community. >From my ObjectiveC Cocoa books it looks like you need to create a Key event using the +(NSEvent*)keyEventWithType: (NSEventType) type method. Another approach would be to use AppleScript via osascript as a subprocess. You can certainly automate the finder via that route. It might be easier than going in via Cocoa. I think there's a Python wrapper for osascript too. Not much direct help but maybe a pointer in the right direction... HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From syedzaidi85 at hotmail.co.uk Tue Mar 8 07:19:47 2016 From: syedzaidi85 at hotmail.co.uk (syed zaidi) Date: Tue, 8 Mar 2016 12:19:47 +0000 Subject: [Tutor] FASTA FILE SUB-SEQUENCE EXTRACTION In-Reply-To: References: , , , Message-ID: Well, fasta is a file format used by biologists to store biological sequencesthe format is as under> sequence information (sequence name, sequence length etc)genomic sequence> sequence information (sequence name, sequence length etc)genomic sequenceI want to match the name of sequence with another list of sequence names and splice the sequence by the provided list of start and end sites for each sequenceso the pseudo code could beif line starts with '>': match the header name with sequence name: if sequence name found: splice from the given start and end positions of that sequence the code I have devised so far is:import oswith open('E:/scaftig.sample - Copy.scaftig','r') as f: header = f.readline() header = header.rstrip(os.linesep) sequence = '' for line in f: line = line.rstrip('\n') if line[0] == '>': header = header[:] print header if line[0] != '>': sequence+= line print sequence, len(sequence)I would appreciate if you can helpThanksBest RegardsAli > Date: Tue, 8 Mar 2016 03:11:42 -0500 > Subject: Re: [Tutor] FASTA FILE SUB-SEQUENCE EXTRACTION > From: wolfrage8765 at gmail.com > To: syedzaidi85 at hotmail.co.uk > > What is FASTA? This seems very specific. Do you have any code thus far > that is failing? > > On Tue, Mar 8, 2016 at 2:33 AM, syed zaidi wrote: > > Hello all, > > I am stuck in a problem, I hope someone can help me out. I have a FASTA file with multiple sequences and another file with the gene coordinates. SAMPLEFASTA FILE: > >>EBM_revised_C2034_1 length=611GCAGCAGTGGGGAATATTGCACAATGGGCGCAAGCCTGATGCAGCCATGCCGCGTGTATGAAGAAGGCCTTCGGGTTGTAAAGTACTTTCAGCGGGGAGGAAGGGAGTAAAGTTAATACCTTTGCTCATTGACGTTACCCGCAGAAGAAGCACCGGCTAACTCCGTGCCAGCAGCCGCGGTAATACGGAGGGTGCAAGCGTTAATCGGAATTACTGGGCGTAAAGCGCACGCAGGCGGTTTGTTAAGTCAGATGTGAAATCCCCGGGCTCAACCTGGGAACTGCATCTGATACTGGCAAGCTTGAGTCTCGTAGAGGGGGGTAGAATTCCAGGTGTAGCGGTGAAATGCGTAGAGATCTGGAGGAATACCGGTGGCGAAGGCGGCCCCCTGGACGAAGACTGACGCTCAGGTGCGAAAGCGTGGGGAGCAAACAGGATTAGATACCCTGGTAGTCCACGCCGTAAACGATGTCGACTTGGAGGTTGTGCCCTTGAGGCGTGGCTTCCGGAGCTAACGCGTTAAGTCGACCGCCTGGGGAGTACGGCCGCAAGGTTAAAACTCAAATGAATTGACGGGGGCCCGCACAAGCGGTGGAGCATGTGGTTTAATT>EBM_revised_C2104_1 length=923TCCGAGGGCGGTGGGATGTTGGTGCTGCAGCGGCTTTCGGATGCGCGGCGGTTGGGTCATCCGGTGTTGGCGGTGGTGGTCGGGTCGGCGGTTAATCAGGATGGGGCGTCGAATGGGTTGACCGCGCCTAATGGTCCTTCGCAGCAGCGGGTGGTGCGGGCGGCGTTGGCCAATGCCGGGTTGAGCGCGGCCGAGGTGGATGTGGTGGAGGGGCATGGGACCGGGACCACGTTGGGGGATCCGATTGAGGCTCAGGCGTTGTTGGCCACTTATGGGCAAGATCGGGGGGAGCCGGGAGAACCTTTGTGGTTGGGGTCGGTGAA > > GTCGAATATGGGTCATACGCAGGCCGCGGCGGGGGTGGCCGGGGTGATCAAGATGGTGTTGGCGATGCGCCATGAGCTGTTGCCGGCGACGTTGCACGTGGATGTGCCTAGCCCGCATGTGGATTGGTCGGCGGGGGCGGTGGAGTTGTTGACCGCGCCGCGGGTGTGGCCTGCTGGTGCTCGGACGCGTCGTGCGGGGGTGTCGTCGTTTGGGATTAGTGGCACTAATGCGCATGTGATTATCGAGGCGGTGCCGGTGGTGCCGCGGCGGGAGGCTGGTTGGGCGGGGCCGGTGGTGCCGTGGGTGGTGTCGGCGAAGTCGGAGTCGGCGTTGCGGGGGCAGGCGGCTCGGTTGGCCGCGTACGTGCGTGGCGATGATGGCCTCGATGTTGCCGATGTGGGGTGGTCGTTGGCGGGTCGTTCGGTTTTTGAGCATCGGGCGGTGGTGGTTGGCGGGGACCGTGATCGGTTGTTGGCCGGGCTCGATGAGCTGGCGGGTGACCAGTTGGGCGGCTCGGTTGTTCGGGGCACGGCGACTGCGGCGGGTAAGACGGTGTTCGTCTTCCCCGGCCAAGGCTCCCAATGGCTGGGCATGGGAAT > > GENE COORD FILEScaf_name Gene_name DS_St DS_EnEBM_revised_C2034_1 gene1_1 33 99EBM_revised_C2034_1 gene1_1 55 100EBM_revised_C2034_1 gene1_1 111 150EBM_revised_C2104_1 gene1_1 44 70 > > I want to perform the following steps:compare the scaf_name with the header of fasta sequenceif header matches then process the sequence and extract the sequence by the provided start and end positions. > > > > I would appreciate if someone can help > > Thanks > > Best Regards > > > > Ali > > > >> _______________________________________________ > >> Tutor maillist - Tutor at python.org > >> To unsubscribe or change subscription options: > >> https://mail.python.org/mailman/listinfo/tutor > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > https://mail.python.org/mailman/listinfo/tutor From paul at whoosh.cn Tue Mar 8 06:56:47 2016 From: paul at whoosh.cn (Paul Z) Date: Tue, 8 Mar 2016 19:56:47 +0800 Subject: [Tutor] how to receive messages form a server? Message-ID: Hi, There is AP with UDP-Server(sending UDP messages). My computer has connected the AP. I know how to receive messages form a client via socket. But, Now, how to receive messages from a server? Thanks! From alan.gauld at btinternet.com Tue Mar 8 16:25:00 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 8 Mar 2016 21:25:00 +0000 Subject: [Tutor] how to receive messages form a server? In-Reply-To: References: Message-ID: On 08/03/16 11:56, Paul Z wrote: > There is AP with UDP-Server(sending UDP messages). > My computer has connected the AP. How did you do that? Via a socket? From Python? > I know how to receive messages form a client via socket. Your terminology confuses me. You send messages from a client to a server. So are you saying you know how to write a server? > But, Now, how to receive messages from a server? Servers don't generally send messages, they send responses to requests from clients. I'm not sure what exactly you are trying to do? Is this a multi-tier application with your code in the middle interacting with clients and servers? Or are you a client accessing a server? Or is it a peer to peer set up? Do you have any code you can share with us? That might clarify things. Also it will definitely help if you tell us which OS and Python version you are using. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Tue Mar 8 16:34:13 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 8 Mar 2016 21:34:13 +0000 Subject: [Tutor] FASTA FILE SUB-SEQUENCE EXTRACTION In-Reply-To: References: Message-ID: On 08/03/16 12:19, syed zaidi wrote: One thing. This is a plain text mailing list and because Python is space dependant you need to post in plain text not HTML/RTF or the layout gets lost in the mail system. (as you see below). The main things you need to tell us are what libraries you are using to read the FASTA data, which OS, and which Python version. > Well, fasta is a file format used by biologists to store > biological sequencesthe format is as under > sequence information (sequence name, sequence length etc)genomic sequence> sequence information (sequence name, sequence length etc)genomic sequenceI want to match the name of sequence with another list of sequence names and splice the sequence by the provided list of start and end sites for each sequenceso the pseudo code could beif line starts with '>': match the header name with sequence name: if sequence name found: splice from the given start and end positions of that sequence the code I have devised so far is:import oswith open('E:/scaftig.sample - Copy.scaftig','r') as f: header = f.readline() header = header.rstrip(os.linesep) sequence = '' > for line in f: line = line.rstrip('\n') if line[0] == '>': header = header[:] print header if line[0] != '>': sequence+= line > print sequence, len(sequence)I would appreciate if you can helpThanksBest RegardsAli -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From danny.yoo at gmail.com Tue Mar 8 19:39:51 2016 From: danny.yoo at gmail.com (Danny Yoo) Date: Tue, 8 Mar 2016 16:39:51 -0800 Subject: [Tutor] FASTA FILE SUB-SEQUENCE EXTRACTION In-Reply-To: References: Message-ID: You should probably look into Biopython: http://biopython.org/wiki/Main_Page Your question should involve fairly straightforward use of the Seq methods of Biopython. You should not try to write your own FASTA parser: Biopython comes with a good one already. Note that the tutor mailing list is not entirely general: the questions here are expected to be beginner-level. Bioinformatics questions are a bit out of scope for tutor @python.org, since they involve a specialized domain that our participants here won't probably be very familiar with. The last times I participated, the Biopython forums were very active. You should check them out: http://biopython.org/wiki/Mailing_lists Good luck! From seighalani at gmail.com Wed Mar 9 01:31:31 2016 From: seighalani at gmail.com (alireza sadeh seighalan) Date: Wed, 9 Mar 2016 10:01:31 +0330 Subject: [Tutor] newbie in programming Message-ID: hi everyone i am very newbie in programming. i want to start with Python. would you guide me ? please introduce me some good python tutorial for a newbie . thanks in advance From syedzaidi85 at hotmail.co.uk Tue Mar 8 22:41:49 2016 From: syedzaidi85 at hotmail.co.uk (syed zaidi) Date: Wed, 9 Mar 2016 11:41:49 +0800 Subject: [Tutor] FASTA FILE SUB-SEQUENCE EXTRACTION Message-ID: Well, I know about it but I want to perform the task using python 2.7 since the tool I'm trying to develop is in 2.7. For some reason I want to do it without biopython please help. .. Sent from my Samsung Galaxy smartphone.
-------- Original message --------
From: Danny Yoo
Date: 3/9/2016 08:39 (GMT+08:00)
To: syed zaidi
Cc: Python Tutor Mailing List
Subject: Re: [Tutor] FASTA FILE SUB-SEQUENCE EXTRACTION
You should probably look into Biopython: http://biopython.org/wiki/Main_Page Your question should involve fairly straightforward use of the Seq methods of Biopython. You should not try to write your own FASTA parser: Biopython comes with a good one already. Note that the tutor mailing list is not entirely general: the questions here are expected to be beginner-level. Bioinformatics questions are a bit out of scope for tutor @python.org, since they involve a specialized domain that our participants here won't probably be very familiar with. The last times I participated, the Biopython forums were very active. You should check them out: http://biopython.org/wiki/Mailing_lists Good luck! From alan.gauld at btinternet.com Wed Mar 9 03:33:10 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 9 Mar 2016 08:33:10 +0000 Subject: [Tutor] newbie in programming In-Reply-To: References: Message-ID: On 09/03/16 06:31, alireza sadeh seighalan wrote: > i am very newbie in programming. i want to start with Python. would you > guide me ? please introduce me some good python tutorial for a newbie . > thanks in advance You could try my tutorial (see below) or there is a list of non-programmers tutorials/books on this page: https://wiki.python.org/moin/BeginnersGuide/NonProgrammers Find the one that suits your style, follow it through and if you get stuck post a question here. Always include your code and any error messages you get. Plus tell us your OS and Python version. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Wed Mar 9 03:36:03 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 9 Mar 2016 08:36:03 +0000 Subject: [Tutor] FASTA FILE SUB-SEQUENCE EXTRACTION In-Reply-To: References: Message-ID: On 09/03/16 03:41, syed zaidi wrote: > ...I want to perform the task using python 2.7 since the tool > I'm trying to develop is in 2.7. OK. That makes sense. > For some reason I want to do it without biopython please help. .. OK, but that makes it much, much harder. There is a Python tutorial for bioinfomatics workers here: http://www.onlamp.com/pub/a/python/2002/10/17/biopython.html It may help you. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From wolfgang.maier at biologie.uni-freiburg.de Wed Mar 9 04:04:09 2016 From: wolfgang.maier at biologie.uni-freiburg.de (Wolfgang Maier) Date: Wed, 9 Mar 2016 10:04:09 +0100 Subject: [Tutor] FASTA FILE SUB-SEQUENCE EXTRACTION In-Reply-To: References: Message-ID: On 09.03.2016 04:41, syed zaidi wrote: > Well, I know about it but I want to perform the task using python 2.7 since the tool I'm trying to develop is in 2.7. For some reason I want to do it without biopython please help. .. > Fair enough. Parsing the fasta and the other (was it gff?) input is not that difficult with just built in functionality and you've described the other necessary steps already. However, as pointed out by Alan, this mailing list is not there for writing scripts for you, but to help you with particular coding and understanding problems. So show us what you've tried so far and what you couldn't get working, then we cann certainly tackle these problems. Best, Wolfgang From lwaters at flinthill.org Wed Mar 9 09:18:51 2016 From: lwaters at flinthill.org (Lisa Hasler Waters) Date: Wed, 9 Mar 2016 09:18:51 -0500 Subject: [Tutor] newbie in programming In-Reply-To: References: Message-ID: Alan, Thanks for pointing us to your extensive, extremely useful website! So much good stuff in their! Many thanks, Lisa On Wed, Mar 9, 2016 at 3:33 AM, Alan Gauld wrote: > On 09/03/16 06:31, alireza sadeh seighalan wrote: > > > i am very newbie in programming. i want to start with Python. would you > > guide me ? please introduce me some good python tutorial for a newbie . > > thanks in advance > > You could try my tutorial (see below) or there is a list of > non-programmers tutorials/books on this page: > > https://wiki.python.org/moin/BeginnersGuide/NonProgrammers > > Find the one that suits your style, follow it through and > if you get stuck post a question here. > > Always include your code and any error messages you get. > Plus tell us your OS and Python version. > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > http://www.flickr.com/photos/alangauldphotos > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Lisa Waters, PhD Technology Integration Flint Hill School From asaad2 at gmail.com Wed Mar 9 09:16:21 2016 From: asaad2 at gmail.com (Bookbag) Date: Wed, 09 Mar 2016 09:16:21 -0500 Subject: [Tutor] newbie in programming In-Reply-To: References: Message-ID: <172408F0-50F6-47AD-9047-B50CF16EEC17@gmail.com> I used "Python programming for the absolute beginner" http://www.amazon.com/Python-Programming-Absolute-Beginner-Edition/dp/1435455002 Easy to understand with practice exercises. It was a good starting point. -------- Original Message -------- From: Alan Gauld Sent: March 9, 2016 3:33:10 AM EST To: tutor at python.org Subject: Re: [Tutor] newbie in programming On 09/03/16 06:31, alireza sadeh seighalan wrote: > i am very newbie in programming. i want to start with Python. would you > guide me ? please introduce me some good python tutorial for a newbie . > thanks in advance You could try my tutorial (see below) or there is a list of non-programmers tutorials/books on this page: https://wiki.python.org/moin/BeginnersGuide/NonProgrammers Find the one that suits your style, follow it through and if you get stuck post a question here. Always include your code and any error messages you get. Plus tell us your OS and Python version. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor From asaad2 at gmail.com Wed Mar 9 09:19:17 2016 From: asaad2 at gmail.com (Bookbag) Date: Wed, 09 Mar 2016 09:19:17 -0500 Subject: [Tutor] newbie in programming In-Reply-To: References: Message-ID: Also I found it helpful to learn python 2.7 first. Since you will need it to analyze old code. -------- Original Message -------- From: Alan Gauld Sent: March 9, 2016 3:33:10 AM EST To: tutor at python.org Subject: Re: [Tutor] newbie in programming On 09/03/16 06:31, alireza sadeh seighalan wrote: > i am very newbie in programming. i want to start with Python. would you > guide me ? please introduce me some good python tutorial for a newbie . > thanks in advance You could try my tutorial (see below) or there is a list of non-programmers tutorials/books on this page: https://wiki.python.org/moin/BeginnersGuide/NonProgrammers Find the one that suits your style, follow it through and if you get stuck post a question here. Always include your code and any error messages you get. Plus tell us your OS and Python version. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor From breamoreboy at yahoo.co.uk Wed Mar 9 16:22:42 2016 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 9 Mar 2016 21:22:42 +0000 Subject: [Tutor] newbie in programming In-Reply-To: References: Message-ID: On 09/03/2016 14:19, Bookbag wrote: > Also I found it helpful to learn python 2.7 first. Since you will need it to analyze old code. > > > -------- Original Message -------- > From: Alan Gauld > Sent: March 9, 2016 3:33:10 AM EST > To: tutor at python.org > Subject: Re: [Tutor] newbie in programming > > On 09/03/16 06:31, alireza sadeh seighalan wrote: > >> i am very newbie in programming. i want to start with Python. would you >> guide me ? please introduce me some good python tutorial for a newbie . >> thanks in advance > > You could try my tutorial (see below) or there is a list of > non-programmers tutorials/books on this page: > > https://wiki.python.org/moin/BeginnersGuide/NonProgrammers > > Find the one that suits your style, follow it through and > if you get stuck post a question here. > > Always include your code and any error messages you get. > Plus tell us your OS and Python version. > I have found it very helpful to follow conversations if people don't top post, but that seems once again to have been completely lost on this list. Is it simply too difficult? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From ben+python at benfinney.id.au Wed Mar 9 19:24:46 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 10 Mar 2016 11:24:46 +1100 Subject: [Tutor] newbie in programming References: Message-ID: <85lh5rnprl.fsf@benfinney.id.au> Mark Lawrence writes: > I have found it very helpful to follow conversations if people don't > top post, but that seems once again to have been completely lost on > this list. Is it simply too difficult? Not too difficult, nor lost. By the nature of this forum, many people have only joined recently; so they do not automatically benefit from past conversations here. -- \ ?DRM doesn't inconvenience [lawbreakers] ? indeed, over time it | `\ trains law-abiding users to become [lawbreakers] out of sheer | _o__) frustration.? ?Charles Stross, 2010-05-09 | Ben Finney From fosiul at gmail.com Thu Mar 10 06:28:52 2016 From: fosiul at gmail.com (Fosiul Alam) Date: Thu, 10 Mar 2016 11:28:52 +0000 Subject: [Tutor] How to compare dates which has (,) In-Reply-To: References: Message-ID: Hi, I am using Python 2.6.6 (r266:84292, Sep 12 2011, 14:03:14) [GCC 4.4.5 20110214 (Red Hat 4.4.5-6)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> On Tue, Mar 8, 2016 at 1:38 PM, Whom Isac wrote: > And it would be helpful if you could provide us about which version of > python you are using, does your code runs an error, format/structure of > your log file and what does your current code returns when you run it. By > the way, if you had imported datetime as :=> import datetime then you don't > have to repeat datetime.datetime.now(). > > On Tue, Mar 8, 2016 at 11:32 PM, Whom Isac wrote: > >> Hi, I am not too good with data handling process but my advice to you to >> check any pickle/cpickle module which may have any function to scan, read >> and write your log files. If not then try the old good Json. These modules >> are good data extraction and data writing. >> >> On Mon, Mar 7, 2016 at 4:39 AM, Fosiul Alam wrote: >> >>> Hi , >>> my bellow codes work ok to compare date and time for perticular format >>> example >>> Feb 7 07:33:19 , >>> but I am not understanding how do i capture and compare dates in bellow >>> formate (,) : >>> >>> >>> also, i having trouble to implement this in python : grep -E -A5 -B3 >>> >>> So basically what i am want is : >>> >>> SCAN all log files in last 30 minutes for key word like ERROR and give me >>> out put like grep -E -A5 -B3 >>> >>> >>> >>> >> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >>> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.> >>> bbbbbbbbbbbbbbbbbbbbbbbbbbbbb >>> bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb >>> bbbbbbbbbbbbbbbbbbbbbbbbbb.> >>> bbbbbbbbbbbbbbbbbbbbbbbbbbccc >>> ccccccccccccccccccccccccc..> >>> >>> >>> My curent code which works for bellow format : >>> >>> #Feb 7 07:33:19 xxxx yum[17961]: Installed: vsftpd-2.2.2-14.el6.x86_64 >>> get_date = re.compile('([A-Z-a-z]+ [0-9]+ [0-9]+:[0-9]+:[0-9]+)(.*)') >>> >>> >>> current_time = datetime.datetime.now() >>> lastHourTime = datetime.datetime.now() - datetime.timedelta(hours = 1) >>> >>> def _read_log(): >>> >>> with open (LOG_FILE,'r')as f: >>> content=f.readlines() >>> return content >>> >>> if __name__ == '__main__': >>> log_file=_read_log() >>> last_execution_time=_get_last_log_time() >>> for line in log_file: >>> #GEt the Date only from the log file Feb 7 07:33:19 >>> match=re.search(get_date,line) >>> if match: >>> #Capture only the date field so taht we can compare iet >>> with (current_time and lastHourTime. >>> #log_date= match.group(1).rstrip() >>> log_date = >>> datetime.datetime.strptime(match.group(1).rstrip(), "%b %d >>> %H:%M:%S").replace(year=datetime.date.today().year) >>> #log_date='Feb 7 07:33:19' >>> >>> #print ('Log Date %s' %log_date) >>> #Check if log_date is greater then lastHourTime and >>> less >>> then current_time >>> if log_date < current_time and log_date > >>> lastHourTime : >>> new_log.append(line) >>> >>> print new_log >>> >>> any help will be really appreciate >>> Thanks >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> https://mail.python.org/mailman/listinfo/tutor >>> >> >> > -- Regards Fosiul Alam From pcraine at lifesitenews.com Thu Mar 10 08:33:26 2016 From: pcraine at lifesitenews.com (Patrick Craine) Date: Thu, 10 Mar 2016 08:33:26 -0500 Subject: [Tutor] Newbie question: programs not printing Message-ID: Hey guys, I?m at the very beginning of learning programming. I started using Khan Academy and now am watching the intro course on MIT OpenCourseWare. I downloaded Python 2.7.11 but for some reason it seems that it's not responding the way it?s supposed to. I haven?t been able to figure out the problem. I?m on Mac OSX 10.11.3. Here?s an example of what?s happening: >>> x = int(raw_input('Enter an integer: ')) if x%2 == 0: print 'Even' else: print 'Odd' if x%3 != 0: print 'And not divisible by 3' Enter an integer: 3 >>> When I put the integer in, I understand it?s supposed to return ?odd? or ?even,? but it?s not giving me anything. Also, at the top of the shell I?m getting this message: WARNING: The version of Tcl/Tk (8.5.9) in use may be unstable. Visit http://www.python.org/download/mac/tcltk/ for current information. I?ve downloaded and installed the program for this. Maybe there?s something else I?m supposed to do? Anyway, as you can tell, I?m very new to this. Thanks for any help you can offer. From marc.tompkins at gmail.com Thu Mar 10 14:44:48 2016 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Thu, 10 Mar 2016 11:44:48 -0800 Subject: [Tutor] Newbie question: programs not printing In-Reply-To: References: Message-ID: On Thu, Mar 10, 2016 at 5:33 AM, Patrick Craine wrote: > >>> x = int(raw_input('Enter an integer: ')) > if x%2 == 0: > print 'Even' > else: > print 'Odd' > if x%3 != 0: > print 'And not divisible by 3' > Enter an integer: 3 > >>> > > It could be your email program that's messing with your indentation, but to me it looks like you're not indenting at all. And that would be a problem - Python is whitespace-aware, and indentation levels are crucial. Try this (if, that is, MY indentation doesn't get trashed!): if x%2 == 0: print 'Even' else: print 'Odd' if x%3 != 0: print 'And not divisible by 3' 0 viruses found. www.avast.com <#DDB4FAA8-2DD7-40BB-A1B8-4E2AA1F9FDF2> From dyoo at hashcollision.org Thu Mar 10 15:50:50 2016 From: dyoo at hashcollision.org (Danny Yoo) Date: Thu, 10 Mar 2016 12:50:50 -0800 Subject: [Tutor] How to compare dates which has (,) In-Reply-To: References: Message-ID: > but I am not understanding how do i capture and compare dates in bellow > formate (,) : > Do you know the name or structure of the format that you're seeing here? I would assume BRT represents some timezone, but I am not sure. Let me check... http://www.timeanddate.com/time/zones/brt OK, so yes, that's the Brasilia time zone. You should be able to use the date time libraries to parse the string. https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior The resulting values should be comparable, if I recall correctly. Yes, https://docs.python.org/2/library/datetime.html#datetime-objects notes that the datetime objects support comparison. I'm away from a keyboard at the moment, so I can't write an example right now. If you can convince whoever is generating those timestamps to use something like ISO 8601 format, then that might also be nice. Good luck! From alan.gauld at btinternet.com Thu Mar 10 17:00:23 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 10 Mar 2016 22:00:23 +0000 Subject: [Tutor] Newbie question: programs not printing In-Reply-To: References: Message-ID: On 10/03/16 13:33, Patrick Craine wrote: > I downloaded Python 2.7.11 but for some reason it seems that it's not > responding the way it?s supposed to. I haven?t been able to figure out the > problem. I?m on Mac OSX 10.11.3. You probably didn't need to download Python because it is installed by default on a Mac. Not to worry. > Here?s an example of what?s happening: > >>>> x = int(raw_input('Enter an integer: ')) > if x%2 == 0: > print 'Even' > else: > print 'Odd' > if x%3 != 0: > print 'And not divisible by 3' > Enter an integer: 3 >>>> Now that looks very strange to me. It starts off with the Python >>> prompt but you should have got the prompt immediately after the first line not at the end. How are you entering the text, are you using the command line tool in a Terminal? Or are you using an IDE like IDLE? Marc has also commented on the lack of indentation(spacing). Python is quite fussy about indenting code you need to follow the visual layout from your tutor. > When I put the integer in, I understand it?s supposed to return ?odd? or > ?even,? but it?s not giving me anything. That's because somehow the prompt is happening after you have already executed all the logic code. If I enter it on my (Linux) PC I get: >>> x = int(raw_input('Enter an integer: ')) Enter an integer: 3 >>> if x%2 == 0: ... print 'Even' ... else: ... print 'Odd' ... Odd >>> if x%3 != 0: ... print 'And not divisible by 3' ... >>> Can you see the differences? The input prompt appears right at the top. > Also, at the top of the shell I?m getting this message: > WARNING: The version of Tcl/Tk (8.5.9) in use may be unstable. > Visit http://www.python.org/download/mac/tcltk/ for current information. Just ignore that for now, it only affects you once you get to writing GUIs, which is a long way down the road yet ;-) The other possible way to run your code is to type it all into a file using Textedit (or some other text editor, not a word processor) and save it as plain text in a folder of your choice (but a new one for your programs might be a good idea!) as a file called something like testnum.py You can then run the file by starting the Terminal application. Then drag the folder you used to save the file into the Terminal (If I recall correctly that should change the active Terminal folder to that one! If not, type cd followed by the folder path) Then type, at the prompt: python testnum.py Hopefully that works. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From benaconklin at gmail.com Thu Mar 10 15:30:45 2016 From: benaconklin at gmail.com (Ben Conklin) Date: Thu, 10 Mar 2016 14:30:45 -0600 Subject: [Tutor] Code Problem Message-ID: Hi, I'm having troubles with my code, specifically at the area with the comment mark. Basically you are to enter three sides of a triangle, and have it show if it is a equilateral, isosceles, or right triangle. I have it so that it makes s1 the longest side, and s2 and s3 the other 2 sides. The right triangle equation should be right, but is not outputting anything. def main(): s1, s2, s3 = eval(input("Enter the three side lengths of a triangle: ")) if s2 > s1: temp = s1 s1 = s2 s2 = temp if s3 > s1: temp = s1 s1 = s3 s3 = temp if s2 + s3 > s1: print("This is a triangle") if s1 == s2 and s2 == s3 and s3 == s1: print("This is an equilateral triangle") elif s1 == s2 or s2 == s3 or s3 == s1: print("This is an isosceles triangle") if s1**2 == s2**2 + s3**2: #This will not output a square triangle when entered print("This is a right triangle") else: print("This is not a triangle") From alan.gauld at btinternet.com Thu Mar 10 20:57:07 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 11 Mar 2016 01:57:07 +0000 Subject: [Tutor] Code Problem In-Reply-To: References: Message-ID: On 10/03/16 20:30, Ben Conklin wrote: > show if it is a equilateral, isosceles, or right triangle. I have it so > that it makes s1 the longest side, and s2 and s3 the other 2 sides. The > right triangle equation should be right, but is not outputting anything. The easiest way to find that is just use the max() function longest = max(s1,s2,s3) > def main(): > s1, s2, s3 = eval(input("Enter the three side lengths of a triangle: ")) Using eval() is a security hazard and you should avoid it. You can convert your input to three strings using the split() function, then convert them to int/float. > if s2 > s1: > temp = s1 > s1 = s2 > s2 = temp In Python you can shortcut all of that reversing code with s1,s2 = s2,s1 > if s3 > s1: > temp = s1 > s1 = s3 > s3 = temp and s1,s3 = s3,s1 You wind up with > if s2 + s3 > s1: > print("This is a triangle") > if s1 == s2 and s2 == s3 and s3 == s1: > print("This is an equilateral triangle") > elif s1 == s2 or s2 == s3 or s3 == s1: > print("This is an isosceles triangle") > if s1**2 == s2**2 + s3**2: #This will not output a square triangle > when entered > print("This is a right triangle") It should work for integer values but possibly not if you entered floats. That's because floating point numbers are not represented exactly in the computer and so testing two floating point numbers for equality often does not work. Other than that it looks to me like it should work. You might also like to add a debugging step to print s1,s2 and s3 just before your if statements, just to check they are the values you expect. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From bariktvr at gmail.com Fri Mar 11 10:14:54 2016 From: bariktvr at gmail.com (Abdul Barik) Date: Fri, 11 Mar 2016 20:44:54 +0530 Subject: [Tutor] Installing package from zip fil Message-ID: I am using python 3.3.3 on windows 8. I downloaded the PyPDF2 package. And I installed it by running the setup.py file. But when I run the my program python terminal shows that there is no such package. Plz help me. From erbatterman at gmail.com Fri Mar 11 10:11:20 2016 From: erbatterman at gmail.com (Ethan Batterman) Date: Fri, 11 Mar 2016 10:11:20 -0500 Subject: [Tutor] Program Arcade Games Help Message-ID: I am really struggling with Lab 9: Functions pt 3 and 4 of program arcade games. Any help or guidance would be greatly appreciated. I am completely lost. Thank you in advance! Ethan From alan.gauld at btinternet.com Fri Mar 11 11:34:44 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 11 Mar 2016 16:34:44 +0000 Subject: [Tutor] Installing package from zip fil In-Reply-To: References: Message-ID: On 11/03/16 15:14, Abdul Barik wrote: > I am using python 3.3.3 on windows 8. I downloaded the PyPDF2 package. And > I installed it by running the setup.py file. But when I run the my program > python terminal shows that there is no such package. Plz help me. Thanks, you've already given us a lot of useful information. But, can you tell us exactly how you ran setup.py? What directory were you in? What prompt were you using (CMD or Python?) Did you specify any options? Did you get any status messages or errors reported? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Fri Mar 11 11:38:01 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 11 Mar 2016 16:38:01 +0000 Subject: [Tutor] Program Arcade Games Help In-Reply-To: References: Message-ID: On 11/03/16 15:11, Ethan Batterman wrote: > I am really struggling with Lab 9: Functions pt 3 and 4 of program arcade games. We have no idea what you are talking about. I assume you are studying some kind of course or book. But which one? What is Lab 9? What are functions pt 3 and 4? What is program arcade games? Without some context we can't start to answer your questions. Also, when you say "completely lost" what exactly do you mean? Do you understand the assignment? Or do you not know where to start? Or have you started and it's not working? The more specific information you can give us the more meaningful our replies can be. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From robertvstepp at gmail.com Fri Mar 11 22:31:31 2016 From: robertvstepp at gmail.com (boB Stepp) Date: Fri, 11 Mar 2016 21:31:31 -0600 Subject: [Tutor] Changing the interpreter prompt symbol from ">>>" to ??? Message-ID: I must be bored tonight. I have to confess that when copying and pasting from the interpreter into a plain text email, I often find it cluttered to confusing by all the ">>>..." that can result from nested quoting. So I poked around on the Internet and found that I can temporarily change the prompt symbol using sys.ps1. My initial trials are: Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:54:25) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.ps1 = '=>' =>sys.ps1 = chr(26) ?sys.ps1 = chr(16) ? I personally like the last of these. My question is, will this show up as a black, filled-in arrowhead pointing to the right on everyone's email? I have yet to delve into Unicode display issues, but I have vague recollections that the old ASCII table values might not always display the same thing from one person's display to another one's. Is this correct? And a related question: I often have the IDLE version of the Python shell open. How can I make this sort of change for IDLE? I have done some Googling on this as well, but haven't found the right search query yet. I also poked into some of the idlelib files, but so far the only ">>>" I've found have been in specialized displays like IDLE debug. TIA! -- boB From robertvstepp at gmail.com Fri Mar 11 22:59:06 2016 From: robertvstepp at gmail.com (boB Stepp) Date: Fri, 11 Mar 2016 21:59:06 -0600 Subject: [Tutor] Changing the interpreter prompt symbol from ">>>" to ??? In-Reply-To: References: Message-ID: On Fri, Mar 11, 2016 at 9:31 PM, boB Stepp wrote: > Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:54:25) [MSC v.1900 > 64 bit (AMD64)] on win32 > Type "help", "copyright", "credits" or "license" for more information. >>>> import sys >>>> sys.ps1 = '=>' > =>sys.ps1 = chr(26) > ?sys.ps1 = chr(16) > ? > > I personally like the last of these. My question is, will this show > up as a black, filled-in arrowhead pointing to the right on everyone's > email? I have yet to delve into Unicode display issues, but I have > vague recollections that the old ASCII table values might not always > display the same thing from one person's display to another one's. Is > this correct? There looks to be the potential for problems. I tried: ?for i in range(256): ... try: ... print(str(i) + ': ' + chr(i)) ... except UnicodeEncodeError as e: ... print(e) which gave in some sections: 126: ~ 127:  'charmap' codec can't encode character '\x80' in position 5: character maps to 'charmap' codec can't encode character '\x81' in position 5: character maps to So how reliable is the chr(16) character on people's displays? boB From wolfrage8765 at gmail.com Fri Mar 11 23:08:53 2016 From: wolfrage8765 at gmail.com (wolfrage8765 at gmail.com) Date: Fri, 11 Mar 2016 23:08:53 -0500 Subject: [Tutor] Changing the interpreter prompt symbol from ">>>" to ??? In-Reply-To: References: Message-ID: On a web based terminal via codeanywhere.com setting sys.ps1 = chr(16) results in no character being displayed. It is literally just a new line. So something to think about. I set it back to sys.ps1 = '>>>' On Fri, Mar 11, 2016 at 10:59 PM, boB Stepp wrote: > On Fri, Mar 11, 2016 at 9:31 PM, boB Stepp wrote: > >> Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:54:25) [MSC v.1900 >> 64 bit (AMD64)] on win32 >> Type "help", "copyright", "credits" or "license" for more information. >>>>> import sys >>>>> sys.ps1 = '=>' >> =>sys.ps1 = chr(26) >> ?sys.ps1 = chr(16) >> ? >> >> I personally like the last of these. My question is, will this show >> up as a black, filled-in arrowhead pointing to the right on everyone's >> email? I have yet to delve into Unicode display issues, but I have >> vague recollections that the old ASCII table values might not always >> display the same thing from one person's display to another one's. Is >> this correct? > > There looks to be the potential for problems. I tried: > > ?for i in range(256): > ... try: > ... print(str(i) + ': ' + chr(i)) > ... except UnicodeEncodeError as e: > ... print(e) > > which gave in some sections: > > 126: ~ > 127: > 'charmap' codec can't encode character '\x80' in position 5: character > maps to > 'charmap' codec can't encode character '\x81' in position 5: character > maps to > > So how reliable is the chr(16) character on people's displays? > > boB > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From wolfrage8765 at gmail.com Fri Mar 11 23:15:20 2016 From: wolfrage8765 at gmail.com (wolfrage8765 at gmail.com) Date: Fri, 11 Mar 2016 23:15:20 -0500 Subject: [Tutor] Changing the interpreter prompt symbol from ">>>" to ??? In-Reply-To: References: Message-ID: I am not surprised since you have set it to a usually non printable character of ascii the data link escape. Perhaps you would have better luck with the extended ascii characters; but not much in there for arrows. I would probably go with chr(175) but that did not display correctly in the web based terminal either; because it looked like an underline at the top of the character block. On Fri, Mar 11, 2016 at 10:59 PM, boB Stepp wrote: > On Fri, Mar 11, 2016 at 9:31 PM, boB Stepp wrote: > >> Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:54:25) [MSC v.1900 >> 64 bit (AMD64)] on win32 >> Type "help", "copyright", "credits" or "license" for more information. >>>>> import sys >>>>> sys.ps1 = '=>' >> =>sys.ps1 = chr(26) >> ?sys.ps1 = chr(16) >> ? >> >> I personally like the last of these. My question is, will this show >> up as a black, filled-in arrowhead pointing to the right on everyone's >> email? I have yet to delve into Unicode display issues, but I have >> vague recollections that the old ASCII table values might not always >> display the same thing from one person's display to another one's. Is >> this correct? > > There looks to be the potential for problems. I tried: > > ?for i in range(256): > ... try: > ... print(str(i) + ': ' + chr(i)) > ... except UnicodeEncodeError as e: > ... print(e) > > which gave in some sections: > > 126: ~ > 127: > 'charmap' codec can't encode character '\x80' in position 5: character > maps to > 'charmap' codec can't encode character '\x81' in position 5: character > maps to > > So how reliable is the chr(16) character on people's displays? > > boB > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From wrw at mac.com Fri Mar 11 23:06:26 2016 From: wrw at mac.com (William Ray Wing) Date: Fri, 11 Mar 2016 23:06:26 -0500 Subject: [Tutor] Changing the interpreter prompt symbol from ">>>" to ??? In-Reply-To: References: Message-ID: <2570BD77-1614-4852-8058-7057ADA2CFC7@mac.com> > On Mar 11, 2016, at 10:31 PM, boB Stepp wrote: > > I must be bored tonight. I have to confess that when copying and > pasting from the interpreter into a plain text email, I often find it > cluttered to confusing by all the ">>>..." that can result from nested > quoting. So I poked around on the Internet and found that I can > temporarily change the prompt symbol using sys.ps1. My initial trials > are: > > Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:54:25) [MSC v.1900 > 64 bit (AMD64)] on win32 > Type "help", "copyright", "credits" or "license" for more information. >>>> import sys >>>> sys.ps1 = '=>' > =>sys.ps1 = chr(26) > ?sys.ps1 = chr(16) > ? > > I personally like the last of these. My question is, will this show > up as a black, filled-in arrowhead pointing to the right on everyone's > email? Can't answer for "everyone" but it certainly shows up that way in Apple Mail. And I agree, I rather like it too, and for the same reason: false interpretation of the standard prompt as nested quotes. -Bill > I have yet to delve into Unicode display issues, but I have > vague recollections that the old ASCII table values might not always > display the same thing from one person's display to another one's. Is > this correct? > > And a related question: I often have the IDLE version of the Python > shell open. How can I make this sort of change for IDLE? I have done > some Googling on this as well, but haven't found the right search > query yet. I also poked into some of the idlelib files, but so far > the only ">>>" I've found have been in specialized displays like IDLE > debug. > > TIA! > > -- > boB > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From cs at zip.com.au Sat Mar 12 00:02:21 2016 From: cs at zip.com.au (Cameron Simpson) Date: Sat, 12 Mar 2016 16:02:21 +1100 Subject: [Tutor] Changing the interpreter prompt symbol from ">>>" to ??? In-Reply-To: References: Message-ID: <20160312050221.GA88471@cskk.homeip.net> On 11Mar2016 21:31, boB Stepp wrote: >I must be bored tonight. I have to confess that when copying and >pasting from the interpreter into a plain text email, I often find it >cluttered to confusing by all the ">>>..." that can result from nested >quoting. So I poked around on the Internet and found that I can >temporarily change the prompt symbol using sys.ps1. My initial trials >are: > >Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:54:25) [MSC v.1900 >64 bit (AMD64)] on win32 >Type "help", "copyright", "credits" or "license" for more information. >>>> import sys >>>> sys.ps1 = '=>' >=>sys.ps1 = chr(26) >?sys.ps1 = chr(16) >? > >I personally like the last of these. My question is, will this show >up as a black, filled-in arrowhead pointing to the right on everyone's >email? I have yet to delve into Unicode display issues, but I have >vague recollections that the old ASCII table values might not always >display the same thing from one person's display to another one's. Is >this correct? For 16 and 26, yes. They are not printable characters; I'm surprised they render as visible symbols at all. Certainly other terminals are under no obligation to render them this way. When I run your code above I get empty appearing prompts as I would have expected - these are control characters and not printable. This leads me to ask: what is your environment? Mine is Mac OSX in an iTerm, which renders Unicode. Interestingly, your _email_ showing your code is presented to me as right-pointing triangle for chr(16) and a little arrow for chr(26), so your environment has translated your cut/paste from your display into something that renders. Your email message, as received here, is in UTF-8. Decoding that Unicode says your right-arrow is codepoint 0x2192 and your triangle is 0x25ba. Let's write a little program: #!/usr/bin/python3 import sys import unicodedata s=sys.stdin.read() for c in s: try: uname = unicodedata.name(c) except ValueError as e: uname = "UNNAMED: %s" % (e,) print("0x%04x %s" % (ord(c), uname)) Echoing your text into it says, for the right arrow and the triangle respectively: 0x2192 RIGHTWARDS ARROW 0x25ba BLACK RIGHT-POINTING POINTER So it seems that your environment has chosen to transcribe your chr(26) and chr(16) into some glyphs for display, and matched those glyphs with suitable Unicode codepoints. (Well, "suitable" if you also see a right-arrow and a right pointing triangle; do you?) So: I would not rely on your stuff being presented nicely if you use 16 and 26 because they are not printable to start with, and you just got lucky. If, OTOH, you figure out some nice glyphs and their Unicode points, then many environments will render them sensibly. Though, of course, not a pure ACII terminal - those are rare these days though. Finally, I would also recommend that whatever prompt you use has a trailing space so that people can more easily separate it from the code. From wolfrage8765 at gmail.com Sat Mar 12 00:19:10 2016 From: wolfrage8765 at gmail.com (wolfrage8765 at gmail.com) Date: Sat, 12 Mar 2016 00:19:10 -0500 Subject: [Tutor] Changing the interpreter prompt symbol from ">>>" to ??? In-Reply-To: <20160312050221.GA88471@cskk.homeip.net> References: <20160312050221.GA88471@cskk.homeip.net> Message-ID: Also before I get called out; sorry for the top post; I blame G-Mail's Interface. And good luck finding a better option; perhaps detecting if Unicode is supported on the system then we could use something such as Right Facing Triangle. From cs at zip.com.au Sat Mar 12 00:46:19 2016 From: cs at zip.com.au (Cameron Simpson) Date: Sat, 12 Mar 2016 16:46:19 +1100 Subject: [Tutor] avoiding top-posting in GMail (was: Changing the interpreter prompt symbol from ">>>" to ???) In-Reply-To: References: Message-ID: <20160312054619.GA16197@cskk.homeip.net> On 12Mar2016 00:19, wolfrage8765 at gmail.com wrote: >Also before I get called out; sorry for the top post; I blame G-Mail's >Interface. I once worked in a place where GMail was pretty much the standard mail tool (guess where that might be:-) We took GMail's cursor-at-the-top style to be a cue that you should start trimming quoted junk there, and insert your remarks, blank line delimited, under each remaining relevant untrimmed quoted material snippet. Which leads to exactly what we all want here: inline posted replies with irrelevant stuff cleaned up for maximum contextual relevance. >And good luck finding a better option; perhaps detecting if Unicode is >supported on the system then we could use something such as Right >Facing Triangle. % locale LANG="en_GB.UTF-8" LC_COLLATE="C" LC_CTYPE="en_GB.UTF-8" LC_MESSAGES="en_GB.UTF-8" LC_MONETARY="en_GB.UTF-8" LC_NUMERIC="en_GB.UTF-8" LC_TIME="en_GB.UTF-8" LC_ALL= I think my terminal might be Unicode friendly... Cheers, Cameron Simpson From robertvstepp at gmail.com Sat Mar 12 01:46:38 2016 From: robertvstepp at gmail.com (boB Stepp) Date: Sat, 12 Mar 2016 00:46:38 -0600 Subject: [Tutor] Changing the interpreter prompt symbol from ">>>" to ??? In-Reply-To: <20160312050221.GA88471@cskk.homeip.net> References: <20160312050221.GA88471@cskk.homeip.net> Message-ID: On Fri, Mar 11, 2016 at 11:02 PM, Cameron Simpson wrote: > On 11Mar2016 21:31, boB Stepp wrote: >> >> I must be bored tonight. I have to confess that when copying and >> pasting from the interpreter into a plain text email, I often find it >> cluttered to confusing by all the ">>>..." that can result from nested >> quoting. So I poked around on the Internet and found that I can >> temporarily change the prompt symbol using sys.ps1. My initial trials >> are: >> >> Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:54:25) [MSC v.1900 >> 64 bit (AMD64)] on win32 >> Type "help", "copyright", "credits" or "license" for more information. >>>>> >>>>> import sys >>>>> sys.ps1 = '=>' >> >> =>sys.ps1 = chr(26) >> ?sys.ps1 = chr(16) >> ? >> >> I personally like the last of these. My question is, will this show >> up as a black, filled-in arrowhead pointing to the right on everyone's >> email? I have yet to delve into Unicode display issues, but I have >> vague recollections that the old ASCII table values might not always >> display the same thing from one person's display to another one's. Is >> this correct? > > > For 16 and 26, yes. They are not printable characters; I'm surprised they > render as visible symbols at all. Certainly other terminals are under no > obligation to render them this way. > > When I run your code above I get empty appearing prompts as I would have > expected - these are control characters and not printable. > > This leads me to ask: what is your environment? Mine is Mac OSX in an iTerm, > which renders Unicode. Win7-64bit, Py 3.5.1 [...] > 0x25ba BLACK RIGHT-POINTING POINTER > > So it seems that your environment has chosen to transcribe your chr(26) and > chr(16) into some glyphs for display, and matched those glyphs with suitable > Unicode codepoints. (Well, "suitable" if you also see a right-arrow and a > right pointing triangle; do you?) I did with the non-printing control character, but not with '\u25ba' ! So I had to go through some contortions after some research to get my Win7 cmd.exe and PowerShell to display the desired prompt using '\u25ba' as the character with utf-8 encoding. My new pythonstartup.py file (Which PYTHONSTARTUP now points to) follows: #!/usr/bin/env python3 import os import sys os.system('chcp 65001') # cmd.exe and PowerShell require the code page to be changed. sys.ps1 = '\u25ba ' # I remembered to add the additional space. Additionally, one must set the font for cmd.exe and PowerShell to "Lucida Console" or the above will not work. > So: I would not rely on your stuff being presented nicely if you use 16 and > 26 because they are not printable to start with, and you just got lucky. If, > OTOH, you figure out some nice glyphs and their Unicode points, then many > environments will render them sensibly. Though, of course, not a pure ACII > terminal - those are rare these days though. So let's see if this copies and pastes into a plain text Gmail and is visible to "many environments": Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:54:25) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. Active code page: 65001 ? print("Can everyone read the prompt?") Can everyone read the prompt? ? It looks good to me in Gmail. Any issues? Angry users of pure ASCII terminals? ~(:>) I still have not figured out how to make this change in IDLE. Research will continue... -- boB From robertvstepp at gmail.com Sat Mar 12 01:53:17 2016 From: robertvstepp at gmail.com (boB Stepp) Date: Sat, 12 Mar 2016 00:53:17 -0600 Subject: [Tutor] Changing the interpreter prompt symbol from ">>>" to ??? In-Reply-To: References: Message-ID: On Fri, Mar 11, 2016 at 10:08 PM, wolfrage8765 at gmail.com wrote: > On a web based terminal via codeanywhere.com setting sys.ps1 = > chr(16) results in no character being displayed. It is literally just > a new line. So something to think about. I set it back to sys.ps1 = > '>>>' Thanks for the feedback. I tried out your link, codeanywhere.com . I have to confess my experience was not a good one. Firstly, the environment supplied would not accept my space bar characters! So I could not type any import statements. However, I did try: print('\u25ba'), which did not require any spaces and received an error stating that it would not accept values greater than hex ff. So it is pretty clear that following Cameron's suggestion is not (At least on the surface.) doable in the codeanywhere environment. Might I suggest pythonanywhere? All of this works fine with utf-8 there. boB From sjeik_appie at hotmail.com Sat Mar 12 03:17:11 2016 From: sjeik_appie at hotmail.com (Albert-Jan Roskam) Date: Sat, 12 Mar 2016 08:17:11 +0000 Subject: [Tutor] Pmw/Tkinter question Message-ID: Hello, Below is a slightly modified example about Pmw/Tkinter from http://pmw.sourceforge.net/doc/howtouse.html. I changed the geometry manager from 'pack' to 'grid', because I use that in all other parts of my program. The problem is, 'broccoli' won't display nicely under vege_menu. I want it to left-align, not center (I don't case that it's truncated). In plain Tkinter I could do "self.vege_menu.configure(anchor=Tkinter.W)" but this raises a KeyError in Pmw. The real reason for switching from Tkinter to Pmw is that Pmw is more compact, and it has an 'index' method that I could use to link two optionmenus. Any ideas? Hope this is ok to ask as Pmw is a layer on top of Tkinter. Thank you! Albert-Jan # -*- coding: utf-8 -*- import Tkinter import Pmw class Demo: def __init__(self, parent): # Create and pack the OptionMenu megawidgets. # The first one has a textvariable. self.var = Tkinter.StringVar() self.var.set('steamed') self.method_menu = Pmw.OptionMenu(parent, labelpos = 'w', label_text = 'Choose method:', menubutton_textvariable = self.var, items = ['baked', 'steamed', 'stir fried', 'boiled', 'raw'], menubutton_width = 10, ) #self.method_menu.pack(anchor = 'w', padx = 10, pady = 10) self.method_menu.grid(row=0, column=0, sticky = 'w', padx = 10, pady = 10) self.vege_menu = Pmw.OptionMenu (parent, labelpos = 'w', label_text = 'Choose vegetable:', items = ('broccoli-broccoli-broccoli-broccoli', 'peas', 'carrots', 'pumpkin'), menubutton_width = 10, command = self._printOrder, ) #self.vege_menu.pack(anchor = 'w', padx = 10, pady = 10) self.vege_menu.grid(row=1, column=0, sticky = 'w', padx = 10, pady = 10) self.direction_menu = Pmw.OptionMenu (parent, labelpos = 'w', label_text = 'Menu direction:', items = ('flush', 'above', 'below', 'left', 'right'), menubutton_width = 10, command = self._changeDirection, ) #self.direction_menu.pack(anchor = 'w', padx = 10, pady = 10) self.direction_menu.grid(row=2, column=0, sticky = 'w', padx = 10, pady = 10) menus = (self.method_menu, self.vege_menu, self.direction_menu) Pmw.alignlabels(menus) def _printOrder(self, vege): # Can use 'self.var.get()' instead of 'getcurselection()'. print 'You have chosen %s %s.' % \ (self.method_menu.getcurselection(), vege) def _changeDirection(self, direction): for menu in (self.method_menu, self.vege_menu, self.direction_menu): menu.configure(menubutton_direction = direction) if __name__ == "__main__" : root = Pmw.initialise() root.title("Demo") widget = Demo(root) root.mainloop() From cs at zip.com.au Sat Mar 12 03:15:35 2016 From: cs at zip.com.au (Cameron Simpson) Date: Sat, 12 Mar 2016 19:15:35 +1100 Subject: [Tutor] Changing the interpreter prompt symbol from ">>>" to ??? In-Reply-To: References: Message-ID: <20160312081535.GA21567@cskk.homeip.net> On 12Mar2016 00:53, boB Stepp wrote: >On Fri, Mar 11, 2016 at 10:08 PM, wolfrage8765 at gmail.com > wrote: >> On a web based terminal via codeanywhere.com setting sys.ps1 = >> chr(16) results in no character being displayed. It is literally just >> a new line. So something to think about. I set it back to sys.ps1 = >> '>>>' > >Thanks for the feedback. I tried out your link, codeanywhere.com . I >have to confess my experience was not a good one. Firstly, the >environment supplied would not accept my space bar characters! So I >could not type any import statements. However, I did try: > >print('\u25ba'), which did not require any spaces and received an >error stating that it would not accept values greater than hex ff. So >it is pretty clear that following Cameron's suggestion is not (At >least on the surface.) doable in the codeanywhere environment. Might >I suggest pythonanywhere? All of this works fine with utf-8 there. Sounds like codeanywhere is an 8-bit environment. Maybe ISO8859-1 (untested assumption). Cheers, Cameron Simpson From diliupg at gmail.com Sat Mar 12 00:15:38 2016 From: diliupg at gmail.com (DiliupG) Date: Sat, 12 Mar 2016 10:45:38 +0530 Subject: [Tutor] Program Arcade Games Help In-Reply-To: References: Message-ID: All the help and guidance you need are in the pages here. http://programarcadegames.com/ if you follow the book slowly from the start you shouldn't have a problem. If you do, stackoverflow is a good place to ask. When ever you ask a question try to give as much details as possible so that who ever answers do not have to go searching over the web to figure out what you are asking. Lab 9 deals with questions on functions. If you are unable to do these it most probably means that you have not grasped the concepts of what functions are. Again stackoverflow and Daniweb are good places of reference to learn more. On Fri, Mar 11, 2016 at 8:41 PM, Ethan Batterman wrote: > I am really struggling with Lab 9: Functions pt 3 and 4 of program arcade > games. Any help or guidance would be greatly appreciated. I am completely > lost. Thank you in advance! > > > Ethan > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Diliup Gabadamudalige http://www.diliupg.com http://soft.diliupg.com/ ********************************************************************************************** This e-mail is confidential. It may also be legally privileged. If you are not the intended recipient or have received it in error, please delete it and all copies from your system and notify the sender immediately by return e-mail. Any unauthorized reading, reproducing, printing or further dissemination of this e-mail or its contents is strictly prohibited and may be unlawful. Internet communications cannot be guaranteed to be timely, secure, error or virus-free. The sender does not accept liability for any errors or omissions. ********************************************************************************************** From justinhayes1982 at icloud.com Fri Mar 11 20:03:02 2016 From: justinhayes1982 at icloud.com (Justin Hayes) Date: Sat, 12 Mar 2016 01:03:02 +0000 (GMT) Subject: [Tutor] How do I access and manipulate files? Message-ID: From cs at zip.com.au Sat Mar 12 03:14:10 2016 From: cs at zip.com.au (Cameron Simpson) Date: Sat, 12 Mar 2016 19:14:10 +1100 Subject: [Tutor] Changing the interpreter prompt symbol from ">>>" to ??? In-Reply-To: References: Message-ID: <20160312081410.GA6640@cskk.homeip.net> On 12Mar2016 00:46, boB Stepp wrote: >On Fri, Mar 11, 2016 at 11:02 PM, Cameron Simpson wrote: >> 0x25ba BLACK RIGHT-POINTING POINTER >> >> So it seems that your environment has chosen to transcribe your chr(26) and >> chr(16) into some glyphs for display, and matched those glyphs with suitable >> Unicode codepoints. (Well, "suitable" if you also see a right-arrow and a >> right pointing triangle; do you?) > >I did with the non-printing control character, but not with '\u25ba' ! > So I had to go through some contortions after some research to get my >Win7 cmd.exe and PowerShell to display the desired prompt using >'\u25ba' as the character with utf-8 encoding. My new >pythonstartup.py file (Which PYTHONSTARTUP now points to) follows: > >#!/usr/bin/env python3 > >import os >import sys > >os.system('chcp 65001') # cmd.exe and PowerShell require the code >page to be changed. >sys.ps1 = '\u25ba ' # I remembered to add the additional space. Looks good to me. (I'm not a Windows person; the _logic_ looks good to me!) >Additionally, one must set the font for cmd.exe and PowerShell to >"Lucida Console" or the above will not work. You may find some other fonts also work if you don't like that one. >> So: I would not rely on your stuff being presented nicely if you use 16 and >> 26 because they are not printable to start with, and you just got lucky. If, >> OTOH, you figure out some nice glyphs and their Unicode points, then many >> environments will render them sensibly. Though, of course, not a pure ACII >> terminal - those are rare these days though. > >So let's see if this copies and pastes into a plain text Gmail and is >visible to "many environments": > >Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:54:25) [MSC v.1900 >64 bit (AMD64)] on win32 >Type "help", "copyright", "credits" or "license" for more information. >Active code page: 65001 >? print("Can everyone read the prompt?") >Can everyone read the prompt? >? > >It looks good to me in Gmail. Any issues? Angry users of pure ASCII >terminals? ~(:>) I see a right pointing triangle. In green:-) But my terminals are green-on-black. Cheers, Cameron Simpson From wolfrage8765 at gmail.com Sat Mar 12 03:50:17 2016 From: wolfrage8765 at gmail.com (wolfrage8765 at gmail.com) Date: Sat, 12 Mar 2016 03:50:17 -0500 Subject: [Tutor] Changing the interpreter prompt symbol from ">>>" to ??? In-Reply-To: References: Message-ID: On Sat, Mar 12, 2016 at 1:53 AM, boB Stepp wrote: > > Thanks for the feedback. I tried out your link, codeanywhere.com . I > have to confess my experience was not a good one. Firstly, the > environment supplied would not accept my space bar characters! So I > could not type any import statements. However, I did try: Yes I do not endorse codeanywhere.com; but it is the only editor I have access to while at work; so as the only it meets my needs barely. > > print('\u25ba'), which did not require any spaces and received an > error stating that it would not accept values greater than hex ff. So > it is pretty clear that following Cameron's suggestion is not (At > least on the surface.) doable in the codeanywhere environment. Might > I suggest pythonanywhere? All of this works fine with utf-8 there. I used to use Pythonanywhere.com but it is blocked; so it is no longer an option. > > boB > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From wolfrage8765 at gmail.com Sat Mar 12 03:55:38 2016 From: wolfrage8765 at gmail.com (wolfrage8765 at gmail.com) Date: Sat, 12 Mar 2016 03:55:38 -0500 Subject: [Tutor] How do I access and manipulate files? In-Reply-To: References: Message-ID: On Fri, Mar 11, 2016 at 8:03 PM, Justin Hayes wrote: > Access: https://docs.python.org/2/library/functions.html#open Basic Manipulation: http://stackoverflow.com/posts/9283052/revisions Please try some code and ask some more specific questions. The Python documentation is pretty good and there is a wealth of information online. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Sat Mar 12 04:18:57 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 12 Mar 2016 09:18:57 +0000 Subject: [Tutor] Pmw/Tkinter question In-Reply-To: References: Message-ID: On 12/03/16 08:17, Albert-Jan Roskam wrote: > Hello, > > Below is a slightly modified example about Pmw/Tkinter from http://pmw.sourceforge.net/doc/howtouse.html. > I changed the geometry manager from 'pack' to 'grid', because I use that in all other parts of my program. > The problem is, 'broccoli' won't display nicely under vege_menu. I want it to left-align, not center (I don't case that it's truncated). In plain Tkinter I could do "self.vege_menu.configure(anchor=Tkinter.W)" but this raises a KeyError in Pmw. > > The real reason for switching from Tkinter to Pmw is that Pmw is more compact, and it has an 'index' method that I could use to link two optionmenus. > > Any ideas? Hope this is ok to ask as Pmw is a layer on top of Tkinter. You can always ask :-) But this is a pretty specific question and I'd expect a better response from the tkinter mailing list. It is pretty active and very helpful. The gmane link is gmane.comp.python.tkinter on news://news.gmane.org:119/gmane.comp.python.tkinter Although my Grayson book on Tkinter covers PMW I've never used it so can't help directly. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Sat Mar 12 04:23:54 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 12 Mar 2016 09:23:54 +0000 Subject: [Tutor] Program Arcade Games Help In-Reply-To: References: Message-ID: On 12/03/16 05:15, DiliupG wrote: > All the help and guidance you need are in the pages here. > > http://programarcadegames.com/ > > if you follow the book slowly from the start you shouldn't have a problem. > If you do, stackoverflow is a good place to ask. As is the tutor list of course. :-) > When ever you ask a question try to give as much details as possible so > that who ever answers do not have to go searching over the web to figure > out what you are asking. > > Lab 9 deals with questions on functions. If you are unable to do these it > most probably means that you have not grasped the concepts of what > functions are. ... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From __peter__ at web.de Sat Mar 12 04:28:36 2016 From: __peter__ at web.de (Peter Otten) Date: Sat, 12 Mar 2016 10:28:36 +0100 Subject: [Tutor] Pmw/Tkinter question References: Message-ID: Albert-Jan Roskam wrote: > Hello, > > Below is a slightly modified example about Pmw/Tkinter from > http://pmw.sourceforge.net/doc/howtouse.html. I changed the geometry > manager from 'pack' to 'grid', because I use that in all other parts of my > program. The problem is, 'broccoli' won't display nicely under vege_menu. > I want it to left-align, not center (I don't case that it's truncated). In > plain Tkinter I could do "self.vege_menu.configure(anchor=Tkinter.W)" but > this raises a KeyError in Pmw. I don't see an official way to to change the alignment, but looking into the source there's class OptionMenu(Pmw.MegaWidget): def __init__(self, parent = None, **kw): [...] self._menubutton = self.createcomponent('menubutton', (), None, Tkinter.Menubutton, (interior,), borderwidth = 2, indicatoron = 1, relief = 'raised', anchor = 'c', highlightthickness = 2, direction = 'flush', takefocus = 1, ) so if you don't mind touching _private attributes > self.vege_menu = Pmw.OptionMenu (parent, > labelpos = 'w', > label_text = 'Choose vegetable:', > items = ('broccoli-broccoli-broccoli-broccoli', 'peas', > 'carrots', 'pumpkin'), menubutton_width = 10, > command = self._printOrder, > ) self.vege_menu._menubutton.config(anchor=Tkinter.W) > #self.vege_menu.pack(anchor = 'w', padx = 10, pady = 10) > self.vege_menu.grid(row=1, column=0, sticky = 'w', padx = 10, pady > = 10) should work. From sjeik_appie at hotmail.com Sat Mar 12 05:05:45 2016 From: sjeik_appie at hotmail.com (Albert-Jan Roskam) Date: Sat, 12 Mar 2016 10:05:45 +0000 Subject: [Tutor] Pmw/Tkinter question In-Reply-To: References: , Message-ID: > To: tutor at python.org > From: __peter__ at web.de > Date: Sat, 12 Mar 2016 10:28:36 +0100 > Subject: Re: [Tutor] Pmw/Tkinter question > > Albert-Jan Roskam wrote: > > > Hello, > > > > Below is a slightly modified example about Pmw/Tkinter from > > http://pmw.sourceforge.net/doc/howtouse.html. I changed the geometry > > manager from 'pack' to 'grid', because I use that in all other parts of my > > program. The problem is, 'broccoli' won't display nicely under vege_menu. > > I want it to left-align, not center (I don't case that it's truncated). In > > plain Tkinter I could do "self.vege_menu.configure(anchor=Tkinter.W)" but > > this raises a KeyError in Pmw. > > I don't see an official way to to change the alignment, but looking into the > source there's > > class OptionMenu(Pmw.MegaWidget): > > def __init__(self, parent = None, **kw): > > [...] > self._menubutton = self.createcomponent('menubutton', > (), None, > Tkinter.Menubutton, (interior,), > borderwidth = 2, > indicatoron = 1, > relief = 'raised', > anchor = 'c', > highlightthickness = 2, > direction = 'flush', > takefocus = 1, > ) > > so if you don't mind touching _private attributes > > > self.vege_menu = Pmw.OptionMenu (parent, > > labelpos = 'w', > > label_text = 'Choose vegetable:', > > items = ('broccoli-broccoli-broccoli-broccoli', 'peas', > > 'carrots', 'pumpkin'), menubutton_width = 10, > > command = self._printOrder, > > ) > self.vege_menu._menubutton.config(anchor=Tkinter.W) > > > #self.vege_menu.pack(anchor = 'w', padx = 10, pady = 10) > > self.vege_menu.grid(row=1, column=0, sticky = 'w', padx = 10, pady > > = 10) > > should work. Ahh, yes, that works! Thank you!! I should indeed have looked at the source myself. The Tk website is often informative, but not everything is exposed by Tkinter/Pmw. This is also the first time I tried Pmw. A lot less verbose than Tkinter, but it takes some time to learn the names/meaning of various parameters. They differ from the equivalent params in Tkinter and are often more descriptive, but pre-existing knowledge of Tkinter creates some "noise". Best wishes, Albert-Jan From breamoreboy at yahoo.co.uk Sat Mar 12 03:51:16 2016 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 12 Mar 2016 08:51:16 +0000 Subject: [Tutor] How do I access and manipulate files? In-Reply-To: References: Message-ID: On 12/03/2016 01:03, Justin Hayes wrote: Would you please read this http://www.catb.org/esr/faqs/smart-questions.html and then try again, thanks. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From alan.gauld at btinternet.com Sat Mar 12 09:03:01 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 12 Mar 2016 14:03:01 +0000 Subject: [Tutor] How do I access and manipulate files? In-Reply-To: References: Message-ID: On 12/03/16 08:51, Mark Lawrence wrote: > On 12/03/2016 01:03, Justin Hayes wrote: > > Would you please read this > http://www.catb.org/esr/faqs/smart-questions.html and then try again, To be fair to Justin his original post did include a paragraph of text providing some context. But somewhere between the moderation queue and appearing on the list it got stripped. I've asked him to repost in plain text. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From david at graniteweb.com Sat Mar 12 10:28:37 2016 From: david at graniteweb.com (David Rock) Date: Sat, 12 Mar 2016 09:28:37 -0600 Subject: [Tutor] Changing the interpreter prompt symbol from ">>>" to ??? In-Reply-To: References: <20160312050221.GA88471@cskk.homeip.net> Message-ID: <20160312152837.GE15669@raspberrypi> * boB Stepp [2016-03-12 00:46]: > > So let's see if this copies and pastes into a plain text Gmail and is > visible to "many environments": > > Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:54:25) [MSC v.1900 > 64 bit (AMD64)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > Active code page: 65001 > ? print("Can everyone read the prompt?") > Can everyone read the prompt? > ? > > It looks good to me in Gmail. Any issues? Angry users of pure ASCII > terminals? ~(:>) I'm using mutt in a screen session on raspbian. Looks fine to me. I have put a lot of effort into "properly" displaying "weird" things, though. -- David Rock david at graniteweb.com From robertvstepp at gmail.com Sat Mar 12 12:21:15 2016 From: robertvstepp at gmail.com (boB Stepp) Date: Sat, 12 Mar 2016 11:21:15 -0600 Subject: [Tutor] Changing the interpreter prompt symbol from ">>>" to ??? In-Reply-To: <20160312081410.GA6640@cskk.homeip.net> References: <20160312081410.GA6640@cskk.homeip.net> Message-ID: On Sat, Mar 12, 2016 at 2:14 AM, Cameron Simpson wrote: > On 12Mar2016 00:46, boB Stepp wrote: >> Additionally, one must set the font for cmd.exe and PowerShell to >> "Lucida Console" or the above will not work. > > > You may find some other fonts also work if you don't like that one. On my Win7 64-bit OS, the only font options available for both PowerShell and cmd.exe are 1) Consolas; 2) Lucida Console; and 3) Raster Fonts. The online research I did stated that only Lucida Console would provide full access to all the characters available in utf-8 with the code page set to 65001. For my particular choice of a single character, 1) Consolas will work as well, though it looks raggedy compared to 2) Lucida Console. However, usually where there is a will there is a way, so I would not be surprised if research would reveal that other workable fonts could be installed in PowerShell and cmd.exe. But (For the moment!) I am quite satisfied with the results of Lucida Console. boB From robertvstepp at gmail.com Sat Mar 12 13:10:57 2016 From: robertvstepp at gmail.com (boB Stepp) Date: Sat, 12 Mar 2016 12:10:57 -0600 Subject: [Tutor] OT: (Continuous) integration testing: Can a solo developer with very limited resources truly do this? Message-ID: >From "Practices of an Agile Developer" by Venkat Subramaniam and Andy Hunt, c. 2006, page 90: You're already writing unit tests to exercise your code. Whenever you modify or refactor your code, you exercise your test cases before you check in the code. All you have to do now is exercise your test cases on each supported platform or environment. If your application is expected to run on different operating systems (MacOS, Linux, Windows, etc.), *** you need to test on all of them *** [My emphasis.]. If you expect your application to work on different versions of the Java Virtual Machine (VM) or .NET common language runtime (CLR), *** you need to test that as well *** [My emphasis.]. I firmly agree that this -- in principle -- must be done. But how on earth can a solo developer, perhaps hoping to make a buck or two, with very limited resources, accomplish manual (much less continuous, automated) integration testing on all reasonable environment possibilities? Just the possibilities for Windows with their constant, unending (albeit, necessary) string of security updates boggles my imagination! One of the many beauties of Python is its portability across many platforms, but it is not perfect. And surprises can occur, even if it is not Python's fault. I *thought* I was finally finished with supporting Python 2.4 at work, and could start using features available in Python 2.6. While testing some new code where I had starting using "with ..." to take care of closing files, I started receiving erratic crashes. Sure enough the traceback pointed to the sections of code using the "with ..." blocks. Huh?!? After investigation, I found that when my IS and commercial vendor friends installed the second computational server for the planning software we use, they did *not* install the *exact* same environment. The OS version was the same, but not all of the other ancillary software was the same. In this instance, they went backwards with Python and installed Python 2.4 on the new server. Since which server gets used is out of the user's control, sometimes my tests ran on one server, sometimes on the other. And since I am stuck doing manual testing, these kinds of things are especially hard to catch! The only way I will ever be able to automate testing at work will be to write my own custom testing framework that can bridge the "automation gap" between the software we use with its proprietary scripting language which does not support automated testing of any sort and the Python that I find myself using more and more, where I have the potential to automate. But the bottom line is -- at work -- the core data I need is in the proprietary environment and after the needed processing with Python it has to be translated back into the proprietary environment's scripting language and run there. The above was just a single practical example (Rant? Sorry!). But even for stuff I do at home, even with using some complex combination of virtual environments to test all relevant OS's (Assuming I could even afford copies WinXP, WinVista, Win7, Win10, etc., with all their many permutations.), how can automated, continuous integration testing be accomplished *in practice* for the severely resource-constrained solo developer? -- boB From alan.gauld at btinternet.com Sat Mar 12 15:02:45 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 12 Mar 2016 20:02:45 +0000 Subject: [Tutor] OT: (Continuous) integration testing: Can a solo developer with very limited resources truly do this? In-Reply-To: References: Message-ID: On 12/03/16 18:10, boB Stepp wrote: > > You're already writing unit tests to exercise your code. Whenever you > modify or refactor your code, you exercise your test cases before you > check in the code. All you have to do now is exercise your test cases > on each supported platform or environment. That's not what I'd call integration testing. Integration testing tests the interfaces between your classes/modules/processes. And that's a completely different set of tests from your unit tests. That nit-pick aside... > If your application is expected to run on different operating systems > (MacOS, Linux, Windows, etc.), *** you need to test on all of them *** > I firmly agree that this -- in principle -- must be done. But how on > earth can a solo developer, perhaps hoping to make a buck or two, with > very limited resources, accomplish manual (much less continuous, > automated) integration testing on all reasonable environment > possibilities? Virtual machines, eg VirtualBox. You can install all of the required OS on a single physical machine (assuming the same hardware of course). For example, on my Linux Mint box I have 2 versions of Windows(XP and Win 8.1) plus Ubuntu and Mandriva Linux virtual machines ready to run. It only takes a few seconds to start/stop each one. It might be possible to run an intel based MacOS in a virtual machine too but I've not tried that and limit my Apple testing to my ancient G3 based iBook... > the same. In this instance, they went backwards with Python and > installed Python 2.4 on the new server. Since which server gets used > is out of the user's control, sometimes my tests ran on one server, > sometimes on the other. Eeek, that's bad. Mirrored servers should be mirrors. Somebody deserves a serious kicking! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From wolfrage8765 at gmail.com Sat Mar 12 19:51:10 2016 From: wolfrage8765 at gmail.com (wolfrage8765 at gmail.com) Date: Sat, 12 Mar 2016 19:51:10 -0500 Subject: [Tutor] OT: (Continuous) integration testing: Can a solo developer with very limited resources truly do this? In-Reply-To: References: Message-ID: > You're already writing unit tests to exercise your code. Whenever you > modify or refactor your code, you exercise your test cases before you > check in the code. All you have to do now is exercise your test cases > on each supported platform or environment. > > If your application is expected to run on different operating systems > (MacOS, Linux, Windows, etc.), *** you need to test on all of them *** > [My emphasis.]. If you expect your application to work on different > versions of the Java Virtual Machine (VM) or .NET common language > runtime (CLR), *** you need to test that as well *** [My emphasis.]. > > > I firmly agree that this -- in principle -- must be done. But how on > earth can a solo developer, perhaps hoping to make a buck or two, with I as a solo developer have been unable to achieve this task too; but once my software is closer to complete that is when I look to do integration testing. > very limited resources, accomplish manual (much less continuous, > automated) integration testing on all reasonable environment > possibilities? Just the possibilities for Windows with their > constant, unending (albeit, necessary) string of security updates > boggles my imagination! You can always download the free test versions of windows; that is what I do and then I throw them on a virtual machine so as to not have to suck up that cost. But dealing with what security updates break is a different story all together. > > One of the many beauties of Python is its portability across many > platforms, but it is not perfect. And surprises can occur, even if it > is not Python's fault. I *thought* I was finally finished with > supporting Python 2.4 at work, and could start using features > available in Python 2.6. While testing some new code where I had > starting using "with ..." to take care of closing files, I started > receiving erratic crashes. Sure enough the traceback pointed to the > sections of code using the "with ..." blocks. Huh?!? After > investigation, I found that when my IS and commercial vendor friends > installed the second computational server for the planning software we > use, they did *not* install the *exact* same environment. The OS > version was the same, but not all of the other ancillary software was > the same. In this instance, they went backwards with Python and > installed Python 2.4 on the new server. Since which server gets used > is out of the user's control, sometimes my tests ran on one server, > sometimes on the other. And since I am stuck doing manual testing, > these kinds of things are especially hard to catch! The only way I > will ever be able to automate testing at work will be to write my own > custom testing framework that can bridge the "automation gap" between > the software we use with its proprietary scripting language which does > not support automated testing of any sort and the Python that I find > myself using more and more, where I have the potential to automate. > But the bottom line is -- at work -- the core data I need is in the > proprietary environment and after the needed processing with Python it > has to be translated back into the proprietary environment's scripting > language and run there. Yes in my virtual environments I have over time been diligently writing a testing automation tool; that starts when the OS boots; then looks to a specific server for a specific directory to download the code to be tested. But it is very rough; the key is to start small and write code that can be re-used. But I am still missing an android and IOS client so I have to test those manually. > > The above was just a single practical example (Rant? Sorry!). But > even for stuff I do at home, even with using some complex combination > of virtual environments to test all relevant OS's (Assuming I could > even afford copies WinXP, WinVista, Win7, Win10, etc., with all their > many permutations.), how can automated, continuous integration testing > be accomplished *in practice* for the severely resource-constrained > solo developer? Good Luck! From robertvstepp at gmail.com Sat Mar 12 21:21:24 2016 From: robertvstepp at gmail.com (boB Stepp) Date: Sat, 12 Mar 2016 20:21:24 -0600 Subject: [Tutor] OT: (Continuous) integration testing: Can a solo developer with very limited resources truly do this? In-Reply-To: References: Message-ID: On Sat, Mar 12, 2016 at 2:02 PM, Alan Gauld wrote: > On 12/03/16 18:10, boB Stepp wrote: > Virtual machines, eg VirtualBox. > You can install all of the required OS on a single physical machine > (assuming the same hardware of course). For example, on my > Linux Mint box I have 2 versions of Windows(XP and Win 8.1) > plus Ubuntu and Mandriva Linux virtual machines ready to run. > It only takes a few seconds to start/stop each one. > > It might be possible to run an intel based MacOS in a virtual > machine too but I've not tried that and limit my Apple testing > to my ancient G3 based iBook... Does one need to already have installation media for each OS to be used, or are they pre-loaded? If the first, for Windows that could potentially be a chunk of money! boB From dyoo at hashcollision.org Sat Mar 12 21:34:02 2016 From: dyoo at hashcollision.org (Danny Yoo) Date: Sat, 12 Mar 2016 18:34:02 -0800 Subject: [Tutor] OT: (Continuous) integration testing: Can a solo developer with very limited resources truly do this? In-Reply-To: References: Message-ID: On Sat, Mar 12, 2016 at 10:10 AM, boB Stepp wrote: > From "Practices of an Agile Developer" by Venkat Subramaniam and Andy > Hunt, c. 2006, page 90: > > > You're already writing unit tests to exercise your code. Whenever you > modify or refactor your code, you exercise your test cases before you > check in the code. All you have to do now is exercise your test cases > on each supported platform or environment. Hi Bob, There are some common infrastructure that folks can use. For example, Travis CL is one such continuous integration system that's getting traction: https://travis-ci.org/ I think there's another CI system called Jenkins CI that's also used quite a bit. Hope this helps! From robertvstepp at gmail.com Sat Mar 12 22:27:31 2016 From: robertvstepp at gmail.com (boB Stepp) Date: Sat, 12 Mar 2016 21:27:31 -0600 Subject: [Tutor] Pmw/Tkinter question In-Reply-To: References: Message-ID: On Sat, Mar 12, 2016 at 2:17 AM, Albert-Jan Roskam wrote: > Below is a slightly modified example about Pmw/Tkinter from http://pmw.sourceforge.net/doc/howtouse.html. > I changed the geometry manager from 'pack' to 'grid', because I use that in all other parts of my program. > The problem is, 'broccoli' won't display nicely under vege_menu. I want it to left-align, not center... I cracked my copy of Grayson and went to his example for OptionMenu widget. His example from page 64-65 is: var = StringVar() var.set('Quantity Surveyor') opt_menu = Pmw.OptionMenu(root, labelpos=W, label_text='Choose profession:', menubutton_textvariable=var, items=('Stockbroker', 'Quantity Surveyor', 'Church Warden', 'BRM'), menubutton_width=16) opt_menu.pack(anchor=W, padx=20, pady=30) In your case you use a lowercase 'w', where Grayson uses uppercase for labelpos. I have not tried this out, but is it possible correct case matters here? On page 584 for the labelpos option he gives: Option: labelpos; Units: anchor; Default: None Specifies where to place the label component. If not None, it should be a concatenation of one or two of the letters N, S, E and W. The first letter specifies on which side of the megawidget to place the label. If a second letter is specified, it indicates where on that side to place the label. For example, if labelpos is W, the label is placed in the center of the left-hand side; if it is WN, the label is placed at the top of the left-hand side; if it is WS, the label is placed at the bottom of the left-hand side. I presume the second letter possibilities are referring to vertical spacing. Hope this helps! boB From robertvstepp at gmail.com Sun Mar 13 00:08:20 2016 From: robertvstepp at gmail.com (boB Stepp) Date: Sat, 12 Mar 2016 23:08:20 -0600 Subject: [Tutor] Pmw/Tkinter question In-Reply-To: References: Message-ID: On Sat, Mar 12, 2016 at 2:17 AM, Albert-Jan Roskam wrote: > Hello, > > Below is a slightly modified example about Pmw/Tkinter from http://pmw.sourceforge.net/doc/howtouse.html. > I changed the geometry manager from 'pack' to 'grid', because I use that in all other parts of my program. > The problem is, 'broccoli' won't display nicely under vege_menu. I want it to left-align, not center (I don't case that it's truncated)... Not having run your code (I did not have Pmw installed.), I think I misunderstood your question(s). I went ahead and installed Pmw and ran your code. I don't have Py 2 installed, so I had to do the usual conversions to make it Py 3 compatible. Once I did that I got all of your labels showing up on the right side of the menu buttons. I presume you want them on the left side of each button? To do that you with the grid manager, you do not want the buttons to attach to the left side of the overall megawidget. Instead, allow the menu buttons to center in each row by omitting the sticky option from grid() and then your labels have room to attach on the left side. Assuming that I am now trying to solve the correct problem, my Py *3* code is: # -*- coding: utf-8 -*- import tkinter import Pmw class Demo: def __init__(self, parent): # Create and pack the OptionMenu megawidgets. # The first one has a textvariable. self.var = tkinter.StringVar() self.var.set('steamed') self.method_menu = Pmw.OptionMenu(parent, labelpos = 'w', label_text = 'Choose method:', menubutton_textvariable = self.var, items = ['baked', 'steamed', 'stir fried', 'boiled', 'raw'], menubutton_width = 10, ) self.method_menu.grid(row=0, column=0, padx = 10, pady = 10) self.vege_menu = Pmw.OptionMenu (parent, labelpos = 'w', label_text = 'Choose vegetable:', items = ('broccoli', 'peas','carrots', 'pumpkin'), menubutton_width = 10, command = self._printOrder, ) self.vege_menu.grid(row=1, column=0, padx = 10, pady = 10) self.direction_menu = Pmw.OptionMenu (parent, labelpos = 'w', label_text = 'Menu direction:', items = ('flush', 'above', 'below', 'left', 'right'), menubutton_width = 10, command = self._changeDirection, ) self.direction_menu.grid(row=2, column=0, padx = 10, pady = 10) menus = (self.method_menu, self.vege_menu, self.direction_menu) Pmw.alignlabels(menus) def _printOrder(self, vege): # Can use 'self.var.get()' instead of 'getcurselection()'. print('You have chosen %s %s.' % \ (self.method_menu.getcurselection(), vege)) def _changeDirection(self, direction): for menu in (self.method_menu, self.vege_menu, self.direction_menu): menu.configure(menubutton_direction = direction) if __name__ == "__main__" : root = Pmw.initialise() root.title("Demo") widget = Demo(root) root.mainloop() I omitted the extra "broccoli" words, to clarify the alignment issues. I hope I am going in the direction you wanted! Nonetheless, having never used the Python megawidgets before, I found this educational. In passing, I was surprised that it does not matter about the case of the sticky positions. I know I have gotten errors at work by not having the proper case for these, but then, I wasn't doing classes. boB From wolfrage8765 at gmail.com Sun Mar 13 00:53:29 2016 From: wolfrage8765 at gmail.com (wolfrage8765 at gmail.com) Date: Sun, 13 Mar 2016 00:53:29 -0500 Subject: [Tutor] OT: (Continuous) integration testing: Can a solo developer with very limited resources truly do this? In-Reply-To: References: Message-ID: >> >>> Does one need to already have installation media for each OS to be >>> used, or are they pre-loaded? If the first, for Windows that could >>> potentially be a chunk of money! >> >> See Here Free Virtual Machines for Windows: >> https://dev.windows.com/en-us/microsoft-edge/tools/vms/windows/ > > I saw these but my superficial impression was that these were for > Explorer and Edge browser testing. Are they in fact usable for any OS > functions I might have my programs using? Yes at least the last time I downloaded one from the site it was a full up and functional version of Windows only stipulation is the trial period but using Virtual Box Snapshot functionality I am always able to easily revert the VM back to day 0 of the trial period. > > If yes, perhaps we should post to the entire Tutor list, too? Sorry I mean to post to the entire tutor list; thanks for pointing that out. > > -- > boB From eryksun at gmail.com Sun Mar 13 03:39:11 2016 From: eryksun at gmail.com (eryk sun) Date: Sun, 13 Mar 2016 01:39:11 -0600 Subject: [Tutor] Changing the interpreter prompt symbol from ">>>" to ??? In-Reply-To: References: <20160312050221.GA88471@cskk.homeip.net> Message-ID: On Sat, Mar 12, 2016 at 12:46 AM, boB Stepp wrote: > I did with the non-printing control character, but not with '\u25ba' ! > So I had to go through some contortions after some research to get my > Win7 cmd.exe and PowerShell to display the desired prompt using The console is hosted by another process named conhost.exe. When Python is running in the foreground, the cmd shell is just waiting in the background until Python exits. > '\u25ba' as the character with utf-8 encoding. My new > pythonstartup.py file (Which PYTHONSTARTUP now points to) follows: > > #!/usr/bin/env python3 > > import os > import sys > > os.system('chcp 65001') # cmd.exe and PowerShell require the code > page to be changed. > sys.ps1 = '\u25ba ' # I remembered to add the additional space. chcp.com calls SetConsoleCP (to change the input codepage) and SetConsoleOutputCP. You can call these functions via ctypes if you need to separately modify the input or output codepages. For example: >>> kernel32 = ctypes.WinDLL('kernel32', use_last_error=True) >>> sys.ps1 = '\u25ba ' ??? kernel32.SetConsoleOutputCP(65001) 1 ? UTF-8 in the console is generally buggy, but this example works since the sys.ps1 prompt is written without buffering (discussed below). However, Python still thinks the console is using the initial codepage. To print non-ASCII characters, you'll either have to change the codepage before starting Python or rebind sys.stdout and sys.stderr. ? print(''.join(chr(x) for x in range(240, 256))) ???????????????? Let's try to fix this: ? fd = os.dup(1) ? sys.stdout = open(fd, 'w', encoding='utf-8') ? print(''.join(chr(x) for x in range(240, 256))) ???????????????? ??????? ??? ? The above buggy output is in Windows 7. Codepage 65001 was only ever meant for encoding text to and from files and sockets, via WinAPI WideCharToMultiByte and MultiByteToWideChar. Using it in the console is buggy because the console's ANSI API hard codes a lot of assumptions that fall apart with UTF-8. For example, if you try to paste non-ASCII characters into the console using 65001 as the input codepage, Python will quit as if you had entered Ctrl+Z. Also, in Windows 7 when you print non-ASCII characters you'll get a trail of garbage written to the end of the print in proportion to the number of non-ASCII characters, especially with character codes that take more than 2 UTF-8 bytes. Also, with Python 2, the CRT's FILE buffering can split a UTF-8 sequence across two writes. The split UTF-8 sequence gets printed as 2 to 4 replacement characters. I've discussed these problems in more detail in the following issue: http://bugs.python.org/issue26345 Windows 10 fixes the problem with printing extra characters, but it still has the problem with reading non-ASCII input as UTF-8 and still can't handle a buffered writer that splits a UTF-8 sequence across two writes. Maybe Windows 20 will finally get this right. For the time being, programs that use Unicode in the console should use the wide-character (UTF-16) API. Python doesn't support this out of the box, since it's not designed to handle UTF-16 in the raw I/O layer. The win-unicode-console package add this support. https://pypi.python.org/pypi/win_unicode_console From sjeik_appie at hotmail.com Sun Mar 13 04:07:50 2016 From: sjeik_appie at hotmail.com (Albert-Jan Roskam) Date: Sun, 13 Mar 2016 08:07:50 +0000 Subject: [Tutor] OT: (Continuous) integration testing: Can a solo developer with very limited resources truly do this? In-Reply-To: References: , Message-ID: > From: dyoo at hashcollision.org > Date: Sat, 12 Mar 2016 18:34:02 -0800 > To: robertvstepp at gmail.com > Subject: Re: [Tutor] OT: (Continuous) integration testing: Can a solo developer with very limited resources truly do this? > CC: tutor at python.org > > On Sat, Mar 12, 2016 at 10:10 AM, boB Stepp wrote: > > From "Practices of an Agile Developer" by Venkat Subramaniam and Andy > > Hunt, c. 2006, page 90: > > > > > > You're already writing unit tests to exercise your code. Whenever you > > modify or refactor your code, you exercise your test cases before you > > check in the code. All you have to do now is exercise your test cases > > on each supported platform or environment. > > > Hi Bob, > > > There are some common infrastructure that folks can use. For example, > Travis CL is one such continuous integration system that's getting > traction: > > https://travis-ci.org/ > > I think there's another CI system called Jenkins CI that's also used > quite a bit. I have used Jenkins CI. It was designed for/with Java, but works very well with Python. I used a multi-configuration project, where you run all unittests in a matrix of N python versions * M operating systems. There are many, many plugins for Jenkins CI and I believe I used the VirtualBox and the Git plugins. You can set things up in such a way that, with each commit, Jenkins tells Virtualbox to fire up the various OSes, then tell Git to make a shallow clone of your repo, then run the tests for each python version (I think this works with tox and virtualenv). It takes a while before everything is up and running, but you can start by setting up Jenkins so it just runs the tests on your host OS. Then you gradually add one OS after another. Hackintosh (unofficial MacOS) was the hardest to get working. Later it got annoying that all these VMs were fired up after each commit. So I manually fired them up whenever I believed it was a good moment. At one point, my tests failed after I updated Jenkins itself, which was very, very annoying. Jenkins, VirtualBox and Git are free software. Appveyor is a similar service to Travis CI, but for windows. It is free for open source projects. You can set it up such that all unittests (and possibly build steps) are run after each "git push". Docker is a way to efficiently run multiple Linux instances. I have no experience with this (because I don't want to limit things to Linux). Vagrant is a disgustingly easy way to fire up VMs (http://www.vagrantbox.es/). You can create your own vagrant boxes with Veewee. I now see that there is a vagrant plugin for virtualbox (https://wiki.jenkins-ci.org/display/JENKINS/Vagrant-plugin) Hercules is a program to emulate mainframes (http://www.hercules-390.org/). It felt to geeky to try and combine this with Jenkins :-). One very different point: I once read somewhere that requirements.txt should "pin the versions": http://nvie.com/posts/pin-your-packages/. That seems a very good idea to me. From sjeik_appie at hotmail.com Sun Mar 13 04:14:54 2016 From: sjeik_appie at hotmail.com (Albert-Jan Roskam) Date: Sun, 13 Mar 2016 08:14:54 +0000 Subject: [Tutor] Changing the interpreter prompt symbol from ">>>" to ??? In-Reply-To: References: , <20160312050221.GA88471@cskk.homeip.net>, , Message-ID: > From: eryksun at gmail.com > Date: Sun, 13 Mar 2016 01:39:11 -0600 > To: tutor at python.org > Subject: Re: [Tutor] Changing the interpreter prompt symbol from ">>>" to ??? > > On Sat, Mar 12, 2016 at 12:46 AM, boB Stepp wrote: > > I did with the non-printing control character, but not with '\u25ba' ! > > So I had to go through some contortions after some research to get my > > Win7 cmd.exe and PowerShell to display the desired prompt using > > The console is hosted by another process named conhost.exe. When > Python is running in the foreground, the cmd shell is just waiting in > the background until Python exits. > > > '\u25ba' as the character with utf-8 encoding. My new > > pythonstartup.py file (Which PYTHONSTARTUP now points to) follows: > > > > #!/usr/bin/env python3 > > > > import os > > import sys > > > > os.system('chcp 65001') # cmd.exe and PowerShell require the code > > page to be changed. > > sys.ps1 = '\u25ba ' # I remembered to add the additional space. > > chcp.com calls SetConsoleCP (to change the input codepage) and > SetConsoleOutputCP. You can call these functions via ctypes if you > need to separately modify the input or output codepages. For example: I thought that utf-8 (cp65001) is by definition (or by design?) impossible for console output in windows? Aren't there "w" (wide) versions of functions that do accept utf-8? Best wishes, Albert-Jan From alan.gauld at btinternet.com Sun Mar 13 05:01:26 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 13 Mar 2016 09:01:26 +0000 Subject: [Tutor] OT: (Continuous) integration testing: Can a solo developer with very limited resources truly do this? In-Reply-To: References: Message-ID: On 13/03/16 02:21, boB Stepp wrote: > On Sat, Mar 12, 2016 at 2:02 PM, Alan Gauld wrote: >> On 12/03/16 18:10, boB Stepp wrote: > Does one need to already have installation media for each OS to be > used, or are they pre-loaded? If the first, for Windows that could > potentially be a chunk of money! Yes, but I buy them when I do the upgrade to my Windows box and I keep the older versions for use in VirtualBox too. So I currently have Windows 98, XP, 7, 8, 8.1 and 10 available. In practice I only really use XP, and 8.1 in Vbox (and I have 10 running on a separate physical box). So long as you only run one instance at a time I think it's still legal (but I am not a lawyer!). All the Linux stuff is free of course... Old versions of Windows can be found cheaply on EBay too although you need to be careful you are getting a legitimate copy including a key with them.... Cave emptor. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From sjeik_appie at hotmail.com Sun Mar 13 12:01:00 2016 From: sjeik_appie at hotmail.com (Albert-Jan Roskam) Date: Sun, 13 Mar 2016 16:01:00 +0000 Subject: [Tutor] Pmw/Tkinter question In-Reply-To: References: , Message-ID: ---------------------------------------- > Date: Sat, 12 Mar 2016 23:08:20 -0600 > Subject: Re: [Tutor] Pmw/Tkinter question > From: robertvstepp at gmail.com > To: sjeik_appie at hotmail.com > CC: tutor at python.org > > On Sat, Mar 12, 2016 at 2:17 AM, Albert-Jan Roskam > wrote: >> Hello, >> >> Below is a slightly modified example about Pmw/Tkinter from http://pmw.sourceforge.net/doc/howtouse.html. >> I changed the geometry manager from 'pack' to 'grid', because I use that in all other parts of my program. >> The problem is, 'broccoli' won't display nicely under vege_menu. I want it to left-align, not center (I don't case that it's truncated)... > > Not having run your code (I did not have Pmw installed.), I think I > misunderstood your question(s). I went ahead and installed Pmw and > ran your code. I don't have Py 2 installed, so I had to do the usual > conversions to make it Py 3 compatible. Once I did that I got all of > your labels showing up on the right side of the menu buttons. I > presume you want them on the left side of each button? To do that you > with the grid manager, you do not want the buttons to attach to the > left side of the overall megawidget. Instead, allow the menu buttons > to center in each row by omitting the sticky option from grid() and > then your labels have room to attach on the left side. Assuming that > I am now trying to solve the correct problem, my Py *3* code is: > > # -*- coding: utf-8 -*- > > import tkinter > import Pmw > > class Demo: > def __init__(self, parent): > # Create and pack the OptionMenu megawidgets. > # The first one has a textvariable. > self.var = tkinter.StringVar() > self.var.set('steamed') > self.method_menu = Pmw.OptionMenu(parent, > labelpos = 'w', > label_text = 'Choose method:', > menubutton_textvariable = self.var, > items = ['baked', 'steamed', 'stir fried', 'boiled', 'raw'], > menubutton_width = 10, > ) > self.method_menu.grid(row=0, column=0, padx = 10, pady = 10) > > self.vege_menu = Pmw.OptionMenu (parent, > labelpos = 'w', > label_text = 'Choose vegetable:', > items = ('broccoli', 'peas','carrots', 'pumpkin'), > menubutton_width = 10, > command = self._printOrder, > ) > self.vege_menu.grid(row=1, column=0, padx = 10, pady = 10) > > self.direction_menu = Pmw.OptionMenu (parent, > labelpos = 'w', > label_text = 'Menu direction:', > items = ('flush', 'above', 'below', 'left', 'right'), > menubutton_width = 10, > command = self._changeDirection, > ) > self.direction_menu.grid(row=2, column=0, padx = 10, pady = 10) > > menus = (self.method_menu, self.vege_menu, self.direction_menu) > Pmw.alignlabels(menus) > > def _printOrder(self, vege): > # Can use 'self.var.get()' instead of 'getcurselection()'. > print('You have chosen %s %s.' % \ > (self.method_menu.getcurselection(), vege)) > > def _changeDirection(self, direction): > for menu in (self.method_menu, self.vege_menu, self.direction_menu): > menu.configure(menubutton_direction = direction) > > if __name__ == "__main__" : > root = Pmw.initialise() > root.title("Demo") > widget = Demo(root) > root.mainloop() > > I omitted the extra "broccoli" words, to clarify the alignment issues. > I hope I am going in the direction you wanted! Nonetheless, having > never used the Python megawidgets before, I found this educational. > In passing, I was surprised that it does not matter about the case of > the sticky positions. I know I have gotten errors at work by not > having the proper case for these, but then, I wasn't doing classes. Hi Bob, Thanks! However, if you replace 'broccoli' with a much longer option, you will see what I meant with the alignment problem. One can no longer read the first letters of the option once it's selected. That's kinda ugly IMHO. Peter's suggestion solves it (but it uses a private/undocumented method). Pmw seems to be quite handy, compared to Tkinter. Not sure how it compares to tix. I suppose both offer a lot of shortcuts for many common tasks. I've only wprked with it very briefly, so I havent discovered much of it. One thing liked is the ability to easily use validators in text entry widgets, with red colors for invalid values etc. Still, tkinter and friends will never win a beauty contest. PyQt is much more visually attractive. I was surprised motivating this could be. Qt Designer makes the process easier, but tkinter is more straightforward. Best wishes, Albert-Jan From eryksun at gmail.com Sun Mar 13 14:58:46 2016 From: eryksun at gmail.com (eryk sun) Date: Sun, 13 Mar 2016 13:58:46 -0500 Subject: [Tutor] Changing the interpreter prompt symbol from ">>>" to ??? In-Reply-To: References: <20160312050221.GA88471@cskk.homeip.net> Message-ID: On Sun, Mar 13, 2016 at 3:14 AM, Albert-Jan Roskam wrote: > I thought that utf-8 (cp65001) is by definition (or by design?) impossible > for console output in windows? Aren't there "w" (wide) versions of functions > that do accept utf-8? The wide-character API works with the native Windows character encoding, UTF-16. Except the console is a bit 'special'. A surrogate pair (e.g. a non-BMP emoji) appears as 2 box characters, but you can copy it from the console to a rich text application, and it renders normally. The console also doesn't support variable-width fonts for mixing narrow and wide (East Asian) glyphs on the same screen. If that matters, there's a program called ConEmu that hides the console and proxies its screen and input buffers to drive an improved interface that has flexible font support, ANSI/VT100 terminal emulation, and tabs. If you pair that with win_unicode_console, it's almost as good as a Linux terminal, but the number of hoops you have to go through to make it all work is too complicated. Some people try to use UTF-8 (codepage 65001) in the ANSI API -- ReadConsoleA/ReadFile and WriteConsoleA/WriteFile. But the console's UTF-8 support is dysfunctional. It's not designed to handle it. In Windows 7, WriteFile calls WriteConsoleA, which decodes the buffer to UTF-16 using the current codepage and returns the number of UTF-16 'characters' written instead of the number of bytes. This confuses buffered writers. Say it writes a 20-byte UTF-8 string with 2 bytes per character. WriteFile returns that it successfully wrote 10 characters, so the buffered writer tries to write the last 10 bytes again. This leads to a trail of garbage text written after every write. When a program reads from the console using ReadFile or ReadConsoleA, the console's input buffer has to be encoded to the target codepage. It assumes that an ANSI character is 1 byte, so if you try to read N bytes, it tries to encode N characters. This fails for non-ASCII UTF-8, which has 2 to 4 bytes per character. However, it won't decrease the number of characters to fit in the N byte buffer. In the API the argument is named "nNumberOfCharsToRead", and they're sticking to that literally. The result is that 0 bytes are read, which is interpreted as EOF. So the REPL will quit, and input() will raise EOFError. From robertvstepp at gmail.com Sun Mar 13 19:06:46 2016 From: robertvstepp at gmail.com (boB Stepp) Date: Sun, 13 Mar 2016 18:06:46 -0500 Subject: [Tutor] Pmw/Tkinter question In-Reply-To: References: Message-ID: On Sun, Mar 13, 2016 at 11:01 AM, Albert-Jan Roskam wrote: > ---------------------------------------- > Thanks! However, if you replace 'broccoli' with a much longer option, you will see what I meant with the alignment problem. One can no longer read the first letters of the option once it's selected. > That's kinda ugly IMHO. Peter's suggestion solves it (but it uses a private/undocumented method). Did you actually run the amended code I posted? On my PC and environment (Win7-64bit, Py 3) everything looks aligned even when I add back in your long "broccoli-..." option. I will send you a png image of what I am seeing on my PC privately. -- boB From robertvstepp at gmail.com Sun Mar 13 19:24:34 2016 From: robertvstepp at gmail.com (boB Stepp) Date: Sun, 13 Mar 2016 18:24:34 -0500 Subject: [Tutor] Pmw/Tkinter question In-Reply-To: References: Message-ID: On Sun, Mar 13, 2016 at 6:06 PM, boB Stepp wrote: > On Sun, Mar 13, 2016 at 11:01 AM, Albert-Jan Roskam > wrote: >> ---------------------------------------- > >> Thanks! However, if you replace 'broccoli' with a much longer option, you will see what I meant with the alignment problem. One can no longer read the first letters of the option once it's selected. >> That's kinda ugly IMHO. Peter's suggestion solves it (but it uses a private/undocumented method). > > Did you actually run the amended code I posted? On my PC and > environment (Win7-64bit, Py 3) everything looks aligned even when I > add back in your long "broccoli-..." option. I will send you a png > image of what I am seeing on my PC privately. CURSES!!! I deeply apologize. I have been out of the house all day. I had stayed up late last night and forgot I had played around with Peter's suggestion. The screen capture I just sent you privately reflects Peter's suggestion. When I removed his line, you are right, with the longer string sequence it is *not* left justified as it should be. Ah, well. I tried to be helpful. This seems like buggy behavior, though, to me. Perhaps there is something about these widgets we are not understanding? boB From oscar.j.benjamin at gmail.com Sun Mar 13 20:03:57 2016 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Mon, 14 Mar 2016 00:03:57 +0000 Subject: [Tutor] Pmw/Tkinter question In-Reply-To: References: Message-ID: On 13 Mar 2016 23:25, "boB Stepp" wrote: > > On Sun, Mar 13, 2016 at 6:06 PM, boB Stepp wrote: > > On Sun, Mar 13, 2016 at 11:01 AM, Albert-Jan Roskam > > wrote: > >> ---------------------------------------- > > > >> Thanks! However, if you replace 'broccoli' with a much longer option, you will see what I meant with the alignment problem. One can no longer read the first letters of the option once it's selected. > >> That's kinda ugly IMHO. Peter's suggestion solves it (but it uses a private/undocumented method). > > > > Did you actually run the amended code I posted? On my PC and > > environment (Win7-64bit, Py 3) everything looks aligned even when I > > add back in your long "broccoli-..." option. I will send you a png > > image of what I am seeing on my PC privately. > > CURSES!!! I deeply apologize. I have been out of the house all day. > I had stayed up late last night and forgot I had played around with > Peter's suggestion. The screen capture I just sent you privately > reflects Peter's suggestion. When I removed his line, you are right, > with the longer string sequence it is *not* left justified as it > should be. > > Ah, well. I tried to be helpful. I often get confused when trying to work with bits to of code from mailing list discussions. It's really okay and it's great to let people know if you realise that you previously misunderstood something. Otherwise your original confusion lingers in the minds of everyone on the list! -- Oscar From robertvstepp at gmail.com Sun Mar 13 20:19:55 2016 From: robertvstepp at gmail.com (boB Stepp) Date: Sun, 13 Mar 2016 19:19:55 -0500 Subject: [Tutor] Pmw/Tkinter question In-Reply-To: References: Message-ID: I just cannot leave this problem alone; however, I *do* believe I have found the correct way to do what Albert-Jan desires within the publicly accessible features of Pmw and Tkinter. I looked at the Pmw documentation online at http://pmw.sourceforge.net/doc/OptionMenu.html and it said: menubutton The menu button displaying the currently selected value. By default, this component is a Tkinter.Menubutton. So I looked up Tkinter.Menubutton next in one of my books and it has the desired anchor option. So if we add menubutton_anchor = 'w' in the appropriate place, then I get the desired alignment. BTW, this fits in with Peter's suggestion. It just needs to be using the normal Pmw/Tkinter machinery: On Sat, Mar 12, 2016 at 2:17 AM, Albert-Jan Roskam wrote: > # -*- coding: utf-8 -*- > > import Tkinter > import Pmw > > class Demo: > def __init__(self, parent): > # Create and pack the OptionMenu megawidgets. > # The first one has a textvariable. > self.var = Tkinter.StringVar() > self.var.set('steamed') > self.method_menu = Pmw.OptionMenu(parent, > labelpos = 'w', > label_text = 'Choose method:', > menubutton_textvariable = self.var, > items = ['baked', 'steamed', 'stir fried', 'boiled', 'raw'], > menubutton_width = 10, > ) > #self.method_menu.pack(anchor = 'w', padx = 10, pady = 10) > self.method_menu.grid(row=0, column=0, sticky = 'w', padx = 10, pady = 10) > > self.vege_menu = Pmw.OptionMenu (parent, > labelpos = 'w', > label_text = 'Choose vegetable:', > items = ('broccoli-broccoli-broccoli-broccoli', 'peas', 'carrots', 'pumpkin'), > menubutton_width = 10, menubutton_anchor = 'w', > command = self._printOrder, > ) > #self.vege_menu.pack(anchor = 'w', padx = 10, pady = 10) > self.vege_menu.grid(row=1, column=0, sticky = 'w', padx = 10, pady = 10) [...] Probably "menubutton_anchor = 'w'" should be added to the other two menu buttons' code as they in the future might have overly long item names. And thanks, Oscar! That makes me feel quite a bit better as I wash the egg off my face from my earlier erroneous efforts. I think I have it right now. boB From David.Aldrich at EMEA.NEC.COM Mon Mar 14 13:19:05 2016 From: David.Aldrich at EMEA.NEC.COM (David Aldrich) Date: Mon, 14 Mar 2016 17:19:05 +0000 Subject: [Tutor] Concerning relative import paths Message-ID: <41302A7145AC054FA7A96CFD03835A0A0BAAE2FF@EX10MBX02.EU.NEC.COM> Hi My Python project's directory structure looks like this: myproj ----- gui | |-- python The 'gui' folder contains my main.py. The 'python' folder contains various modules that we have written. My gui/main.py contains this sort of import code: import os, sys sys.path.append('../python') import MyClass This works fine at runtime. The thing is that I am using Microsoft's Visual Studio Code editor with an extension that implements Intellisense for Python. The Intellisense is working fine for the os and sys modules, but it doesn't respond to MyClass. This seems reasonable because I guess it ignores the sys.path.append line. My question is: is there a better way that I can specify the import statements so that a tool such as Intellisense will have an absolute path to find the modules? I hope this isn't too tool specific, I'm just wondering whether there's a more pythonic way of implementing this import code? Best regards David From alan.gauld at btinternet.com Tue Mar 15 05:46:38 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 15 Mar 2016 09:46:38 +0000 Subject: [Tutor] Concerning relative import paths In-Reply-To: <41302A7145AC054FA7A96CFD03835A0A0BAAE2FF@EX10MBX02.EU.NEC.COM> References: <41302A7145AC054FA7A96CFD03835A0A0BAAE2FF@EX10MBX02.EU.NEC.COM> Message-ID: On 14/03/16 17:19, David Aldrich wrote: > myproj ----- gui > > | > > |-- python > > My gui/main.py contains this sort of import code: > > import os, sys > sys.path.append('../python') > import MyClass > > > The thing is that I am using Microsoft's Visual Studio... > My question is: is there a better way that I can specify > the import statements so that a tool such as Intellisense > will have an absolute path to find the modules? I know nothing about VS but have you tried setting the PYTHONPATH environment variable to myproj/python? Then just use import MyClass If VS sees anything its probably the environment vars. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From eh387 at exeter.ac.uk Tue Mar 15 07:45:56 2016 From: eh387 at exeter.ac.uk (Holderness, Ellie) Date: Tue, 15 Mar 2016 11:45:56 +0000 Subject: [Tutor] Citing Python Message-ID: Hi, How do I cite Python for my dissertation bibliography? I used version 3.5.1. Thanks Ellie From alan.gauld at btinternet.com Tue Mar 15 14:43:44 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 15 Mar 2016 18:43:44 +0000 Subject: [Tutor] Citing Python In-Reply-To: References: Message-ID: On 15/03/16 11:45, Holderness, Ellie wrote: > How do I cite Python for my dissertation bibliography? > I used version 3.5.1. I'm not sure a citation is strictly necessary for a programming language, but if you want to you could cite the Python web site. Would you cite JavaScript, CSS or HTML if you built a website? Or SQL if you built a database? If you used a particular tutorial to learn the language you could cite that (either as a book or web site). HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From sjeik_appie at hotmail.com Tue Mar 15 15:30:23 2016 From: sjeik_appie at hotmail.com (Albert-Jan Roskam) Date: Tue, 15 Mar 2016 19:30:23 +0000 Subject: [Tutor] Pmw/Tkinter question In-Reply-To: References: , Message-ID: > Date: Sun, 13 Mar 2016 19:19:55 -0500 > From: robertvstepp at gmail.com > To: tutor at python.org > Subject: Re: [Tutor] Pmw/Tkinter question > > I just cannot leave this problem alone; however, I *do* believe I have > found the correct way to do what Albert-Jan desires within the > publicly accessible features of Pmw and Tkinter. I looked at the Pmw > documentation online at > > http://pmw.sourceforge.net/doc/OptionMenu.html > > and it said: > > > menubutton > > The menu button displaying the currently selected value. By default, > this component is a Tkinter.Menubutton. > > > So I looked up Tkinter.Menubutton next in one of my books and it has > the desired anchor option. So if we add > > menubutton_anchor = 'w' > > in the appropriate place, then I get the desired alignment. BTW, this > fits in with Peter's suggestion. It just needs to be using the normal > Pmw/Tkinter machinery: Thanks, you're right! After the line: self.vege_menu.grid(row=1, column=0, sticky = 'w', padx = 10, pady = 10) either one of the following lines does the trick: self.vege_menu.configure(menubutton_anchor=Tkinter.W) #self.vege_menu.configure(menubutton_anchor=' w') #self.vege_menu._menubutton.config(anchor=Tkinter.W) This does not work, however: self.vege_menu.grid(row=1, column=0, sticky = 'w', padx = 10, pady = 10, menubutton_anchor=Tkinter.W) I tested this on debian linux jessie, with Python 2.7 (it turned out that I incorrectly compiled 3.5, no _tkinter) Best wishes, Albert-Jan From sjeik_appie at hotmail.com Tue Mar 15 15:51:57 2016 From: sjeik_appie at hotmail.com (Albert-Jan Roskam) Date: Tue, 15 Mar 2016 19:51:57 +0000 Subject: [Tutor] Changing the interpreter prompt symbol from ">>>" to ??? In-Reply-To: References: , <20160312050221.GA88471@cskk.homeip.net> , , Message-ID: > From: eryksun at gmail.com > Date: Sun, 13 Mar 2016 13:58:46 -0500 > Subject: Re: [Tutor] Changing the interpreter prompt symbol from ">>>" to ??? > To: tutor at python.org > CC: sjeik_appie at hotmail.com > > On Sun, Mar 13, 2016 at 3:14 AM, Albert-Jan Roskam > wrote: > > I thought that utf-8 (cp65001) is by definition (or by design?) impossible > > for console output in windows? Aren't there "w" (wide) versions of functions > > that do accept utf-8? > > The wide-character API works with the native Windows character > encoding, UTF-16. Except the console is a bit 'special'. A surrogate > pair (e.g. a non-BMP emoji) appears as 2 box characters, but you can > copy it from the console to a rich text application, and it renders > normally. That is very useful to know. > The console also doesn't support variable-width fonts for > mixing narrow and wide (East Asian) glyphs on the same screen. If that > matters, there's a program called ConEmu that hides the console and > proxies its screen and input buffers to drive an improved interface > that has flexible font support, ANSI/VT100 terminal emulation, and > tabs. If you pair that with win_unicode_console, it's almost as good > as a Linux terminal, but the number of hoops you have to go through to > make it all work is too complicated. So windows uses the following (Western locales): console: cp437 (OEM codepage) "bytes": cp1252 (ANSI codepage) unicode: utf-16-le (is 'mbcs' equivalent to utf-16-*?) Sheesh, so much room for errors. Why not everything utf-8, like in linux? Is cmd.exe that impopular that Microsoft does not replace it with something better? I understand that this silly OEM codepage is a historical anomaly, but am I correct in saying that the use of codepages (with stupid differences such as latin-1 vs cp1252 as a bonus) are designed to hamper cross-platform compatibility (and force people to stick with windows)? > Some people try to use UTF-8 (codepage 65001) in the ANSI API -- > ReadConsoleA/ReadFile and WriteConsoleA/WriteFile. But the console's > UTF-8 support is dysfunctional. It's not designed to handle it. > > In Windows 7, WriteFile calls WriteConsoleA, which decodes the buffer > to UTF-16 using the current codepage and returns the number of UTF-16 > 'characters' written instead of the number of bytes. This confuses > buffered writers. Say it writes a 20-byte UTF-8 string with 2 bytes > per character. WriteFile returns that it successfully wrote 10 > characters, so the buffered writer tries to write the last 10 bytes > again. This leads to a trail of garbage text written after every > write. Strange. I would have thought it writes the first 10 bytes (5 characters) and that the remaining 10 bytes end up in oblivion. > When a program reads from the console using ReadFile or ReadConsoleA, > the console's input buffer has to be encoded to the target codepage. > It assumes that an ANSI character is 1 byte, so if you try to read N > bytes, it tries to encode N characters. This fails for non-ASCII > UTF-8, which has 2 to 4 bytes per character. However, it won't > decrease the number of characters to fit in the N byte buffer. In the > API the argument is named "nNumberOfCharsToRead", and they're sticking > to that literally. The result is that 0 bytes are read, which is > interpreted as EOF. So the REPL will quit, and input() will raise > EOFError. From beachkidken at gmail.com Tue Mar 15 17:31:55 2016 From: beachkidken at gmail.com (Ken G.) Date: Tue, 15 Mar 2016 17:31:55 -0400 Subject: [Tutor] Best way to install Python 3 onto Windows 10 Message-ID: <56E87F4B.1010000@gmail.com> Having acquired a new laptop yesterday with Windows 10 installed and up-to-date, what would be the best way to install the latest version of Python 3? The laptop is an Dell Latitude E5500 and I am still learning the bells and whistles of it. I last used Windows XP 3-4 years back so this usage is all new to me. Currently, I am using Python 2.7.6 on a desktop Linux system, Ubuntu 14.04.4 and using Geany as a go to using Python. TIA, Ken From alan.gauld at btinternet.com Tue Mar 15 17:40:56 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 15 Mar 2016 21:40:56 +0000 Subject: [Tutor] Changing the interpreter prompt symbol from ">>>" to ??? In-Reply-To: References: <20160312050221.GA88471@cskk.homeip.net> Message-ID: On 15/03/16 19:51, Albert-Jan Roskam wrote: > So windows uses the following (Western locales): > console: cp437 (OEM codepage) > "bytes": cp1252 (ANSI codepage) > unicode: utf-16-le (is 'mbcs' equivalent to utf-16-*?) > > > Sheesh, so much room for errors. Why not everything utf-8, like in linux? > Is cmd.exe that impopular that Microsoft does not replace it with something better? It's replaced by Powershell. It's just that not many people use Powershell. Familiarity beats superiority. Whether Powershell actually handles display of text any better is another question. I don;t know the answer to that and am too lazy to fire up my Windows box to find out! :-( > in saying that the use of codepages (with stupid differences such as latin-1 vs cp1252 as a bonus) > are designed to hamper cross-platform compatibility (and force people to stick with windows)? I think that's probably being unfair on Microsoft. It is mainly just historical I think. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Tue Mar 15 17:45:09 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 15 Mar 2016 21:45:09 +0000 Subject: [Tutor] Best way to install Python 3 onto Windows 10 In-Reply-To: <56E87F4B.1010000@gmail.com> References: <56E87F4B.1010000@gmail.com> Message-ID: On 15/03/16 21:31, Ken G. wrote: > Having acquired a new laptop yesterday with > Windows 10 installed and up-to-date, what > would be the best way to install the latest > version of Python 3? Personally I always install ActiveState Python on Windows so that I can set up the Pythonwin IDE and use the ActiveState Windows help viewer for the Python docs. The installer should do everything you need for you. (You may have to locate the pyhonwin exe and set up a shortcut - I seem to recall that was not done by the installer for Win 10... Caveat: ActiveState are sometimes a few months behind with their python versions so might not have the very latest build out yet. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From beachkidken at gmail.com Tue Mar 15 19:26:31 2016 From: beachkidken at gmail.com (Ken G.) Date: Tue, 15 Mar 2016 19:26:31 -0400 Subject: [Tutor] Best way to install Python 3 onto Windows 10 [RESOLVED] In-Reply-To: References: <56E87F4B.1010000@gmail.com> Message-ID: <56E89A27.9030805@gmail.com> On 03/15/2016 05:45 PM, Alan Gauld wrote: > On 15/03/16 21:31, Ken G. wrote: >> Having acquired a new laptop yesterday with >> Windows 10 installed and up-to-date, what >> would be the best way to install the latest >> version of Python 3? > Personally I always install ActiveState Python on > Windows so that I can set up the Pythonwin IDE and > use the ActiveState Windows help viewer for the > Python docs. > > The installer should do everything you need for > you. (You may have to locate the pyhonwin exe and > set up a shortcut - I seem to recall that was not > done by the installer for Win 10... > > Caveat: ActiveState are sometimes a few months > behind with their python versions so might not > have the very latest build out yet. > Thank you Alan. I just could not remember the name of that helpful installer for the Windows system. Ken From eryksun at gmail.com Tue Mar 15 20:15:03 2016 From: eryksun at gmail.com (eryk sun) Date: Tue, 15 Mar 2016 19:15:03 -0500 Subject: [Tutor] Changing the interpreter prompt symbol from ">>>" to ??? In-Reply-To: References: <20160312050221.GA88471@cskk.homeip.net> Message-ID: On Tue, Mar 15, 2016 at 2:51 PM, Albert-Jan Roskam wrote: > > So windows uses the following (Western locales): > console: cp437 (OEM codepage) > "bytes": cp1252 (ANSI codepage) The console defaults to the OEM codepage, but you can separately switch the input and output to different codepages. This is an exception to the rule, as otherwise the system codepage used in the [A]NSI API is fixed when the system boots. Changing it requires modifying the system locale and rebooting. > unicode: utf-16-le (is 'mbcs' equivalent to utf-16-*?) The native Unicode encoding of Windows is UTF-16LE. This is what gets used in the kernel, device drivers, and filesystems. UTF-16 was created to accommodate the early adopters of 16-bit Unicode, such as Windows. When you call an ANSI API, such as CreateFileA, the bytes argument(s) get decoded to UTF-16, and then it calls the corresponding wide-character function, such as CreateFileW (or maybe a common internal function, but that's an implementation detail). ANSI is a legacy API, and it's moving towards deprecation and obsolescence. New WinAPI functions are often created with only wide-character support. MBCS (multibyte character set) refers to encoding that can be used in the system locale for the [A]NSI API. While technically UTF-8 and UTF-16 are multibyte encodings, they're not allowed in the legacy ANSI API. That said, because the console is just plain weird, it allows setting its input and output codepages to UTF-8, even though the result is often buggy. > Sheesh, so much room for errors. Why not everything utf-8, like in linux? NT was developed before UTF-8 was released, so you're asking the NT team to invent a time machine. Plus there's nothing really that horrible about UTF-16. On the plus side, it uses only 2 bytes per character for all characters in the BMP, whereas UTF-8 uses 3 bytes per character for 61440 out of 63488 characters in the BMP (not including the surrogate-pair block, U+D800-U+DFFF). On the plus side for UTF-8, it encodes ASCII (i.e. ordinals less than 128) in a single byte per character. > Is cmd.exe that impopular that Microsoft does not replace it with something > better? cmd.exe is a shell, like powershell.exe or bash.exe, and a console client application just like python.exe. cmd.exe doesn't host the console, nor does it have anything to do with the console subsystem other than being a client of it. When you run python.exe from cmd.exe, all cmd does is wait for python to exit. When you run a program that's flagged as a console application, the system either attaches an inherited console if one exists, or opens and attaches a new console. This window is hosted by an instance of conhost.exe. It also implements the application's command-line editing, input history buffer (e.g. F7), and input aliases, separately for each attached executable. This part of the console API is accessible from the command line via doskey.exe. cmd.exe is a Unicode application, so codepages aren't generally of much concern to it, except it defaults to encoding to the console codepage when its built-in commands such as "dir" and "set" are piped to another program. You can force it to use UTF-16 in this case by running cmd /U. This is just for cmd's internal commands. What external commands write to a pipe is up to them. For example, Python 3 defaults to using the ANSI codepage when stdio is a pipe. You can override this via the environment variable PYTHONIOENCODING. As to replacing the console, I doubt that will happen. Microsoft has little incentive to invest in improving/replacing the console and command-line applications. Windows administration has shifted to PowerShell scripting and cmdlets. > am I correct in saying that the use of codepages (with stupid differences > such as latin-1 vs cp1252 as a bonus) are designed to hamper cross- > platform compatibility (and force people to stick with windows)? The difference between codepage 1252 and Latin-1 is historical. Windows development circa 1990 was following a draft ANSI standard for character encodings, which later became the ISO 8859-x encodings. Windows codepages ended up deviating from the ISO standard. Plus the 'ANSI' API also supports MBCS codepages for East-Asian languages. I can't speak to any nefarious business plans to hamper cross-platform compatibility. But it seems to me that this is a matter of rushing to get a product to market without having time to wait for a standards committee, plus a good measure of arrogance that comes from having market dominance. > Strange. I would have thought it writes the first 10 bytes (5 characters) > and that the remaining 10 bytes end up in oblivion. Maybe a few more details will help to clarify the matter. In Windows 7, WriteFile basically calls WriteConsoleA, which makes a local procedure call (LPC) to SrvWriteConsole in conhost.exe. This call is flagged as to whether the buffer is ANSI or Unicode (UTF-16). If it's ANSI, the console first decodes the buffer using MultiByteToWideChar according to the output screen's codepage. Then it copies the decoded buffer to the output screen buffer and returns to the caller how many UTF-16 *code points* it wrote. Maybe that's fine for WriteConsoleA, but returning that number to a WriteFile caller (a bytes API) is nonsense. If I write a 20-byte buffer, I need to know that all 20 bytes were written, not that 10 UTF-16 codes were written. This causes problems with buffered writers such as Python 3's BufferedWriter class. From robertvstepp at gmail.com Tue Mar 15 20:35:20 2016 From: robertvstepp at gmail.com (boB Stepp) Date: Tue, 15 Mar 2016 19:35:20 -0500 Subject: [Tutor] Changing the interpreter prompt symbol from ">>>" to ??? In-Reply-To: References: <20160312050221.GA88471@cskk.homeip.net> Message-ID: Is the following result in PowerShell related to what Eryk has been discussing? Windows PowerShell Copyright (C) 2009 Microsoft Corporation. All rights reserved. PS C:\Windows\system32> py Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:54:25) [MSC v.1900 64 bit (AMD64)] on w in32 Type "help", "copyright", "credits" or "license" for more information. Active code page: 65001 ? help(print) Not enough memory. If it matters, the same thing happens whether I run PowerShell with administrator rights or not. The same thing happens in cmd.exe. It does not happen in the IDLE Python shell. This is bizarre. What's up? boB From robertvstepp at gmail.com Tue Mar 15 20:45:25 2016 From: robertvstepp at gmail.com (boB Stepp) Date: Tue, 15 Mar 2016 19:45:25 -0500 Subject: [Tutor] Changing the interpreter prompt symbol from ">>>" to ??? In-Reply-To: References: <20160312050221.GA88471@cskk.homeip.net> Message-ID: On Tue, Mar 15, 2016 at 7:35 PM, boB Stepp wrote: > Is the following result in PowerShell related to what Eryk has been discussing? > > Windows PowerShell > Copyright (C) 2009 Microsoft Corporation. All rights reserved. > > PS C:\Windows\system32> py > Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:54:25) [MSC v.1900 > 64 bit (AMD64)] on w > in32 > Type "help", "copyright", "credits" or "license" for more information. > Active code page: 65001 > ? help(print) > Not enough memory. > Apparently this is another consequence of setting the code page to 65001. See https://bugs.python.org/issue19914 I am now wondering which is better: Adopt the solution suggested earlier by Eryk, applying that Python monkey patch and using utf-16 or doing something more drastic, like installing Cygwin. What are the cons in doing the latter? Will I achieve Unicode harmony under Windows by using Cygwin? -- boB From eryksun at gmail.com Tue Mar 15 21:01:02 2016 From: eryksun at gmail.com (eryk sun) Date: Tue, 15 Mar 2016 20:01:02 -0500 Subject: [Tutor] Changing the interpreter prompt symbol from ">>>" to ??? In-Reply-To: References: <20160312050221.GA88471@cskk.homeip.net> Message-ID: On Tue, Mar 15, 2016 at 4:40 PM, Alan Gauld wrote: > On 15/03/16 19:51, Albert-Jan Roskam wrote: > >> Sheesh, so much room for errors. Why not everything utf-8, like in linux? >> Is cmd.exe that impopular that Microsoft does not replace it with something better? > > It's replaced by Powershell. > It's just that not many people use Powershell. > Familiarity beats superiority. > > Whether Powershell actually handles display of text any better is > another question. I don;t know the answer to that and am too lazy > to fire up my Windows box to find out! :-( powershell.exe is a standard console application. It works the same as cmd.exe and python.exe. OTOH, maybe you're referring to PowerShell Integrate Scripting Environment (ISE), which is more like an IDE. It hides the console window and sets stdout and stderr to pipes. Bizarrely, if you run python.exe in this environment, stdin still uses the hidden console (I made the console visible and could type into it and see the result in ISE). It's pretty much useless for regular interactive console applications. It's more focused on designing, testing and running PowerShell scripts and cmdlets. From alan.gauld at btinternet.com Tue Mar 15 21:31:08 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 16 Mar 2016 01:31:08 +0000 Subject: [Tutor] Changing the interpreter prompt symbol from ">>>" to ??? In-Reply-To: References: <20160312050221.GA88471@cskk.homeip.net> Message-ID: On 16/03/16 00:45, boB Stepp wrote: > doing something more drastic, like installing Cygwin. What are the > cons in doing the latter? Will I achieve Unicode harmony under > Windows by using Cygwin? If you now unix then you owe it to yourself to install cygwin. It will give you a Linux box on your windows box. Complete with xterms and bash and all the other Unix tools you know. But it doesn't help at all in developing Python code for Windows users of whom 99% will still be using the standard cmd shell. Cygwin is more useful if you need to work in Windows but also want to target *nix users. That way round it works pretty well. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From steve at pearwood.info Tue Mar 15 21:50:23 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 16 Mar 2016 12:50:23 +1100 Subject: [Tutor] Citing Python In-Reply-To: References: Message-ID: <20160316015022.GA8022@ando.pearwood.info> On Tue, Mar 15, 2016 at 11:45:56AM +0000, Holderness, Ellie wrote: > Hi, > > How do I cite Python for my dissertation bibliography? I used version 3.5.1. What a fantastic question! I have no idea! I googled for "how to cite programming language" and found these: http://stackoverflow.com/questions/15688758/r-stats-citation-for-a-scientific-paper http://blog.apastyle.org/apastyle/2015/01/how-to-cite-software-in-apa-style.html I ran "citation()" in my copy of R and got this: > citation() To cite R in publications use: R Core Team (2014). R: A language and environment for statistical computing. R Foundation for Statistical Computing, Vienna, Austria. URL http://www.R-project.org/. A BibTeX entry for LaTeX users is @Manual{, title = {R: A Language and Environment for Statistical Computing}, author = {{R Core Team}}, organization = {R Foundation for Statistical Computing}, address = {Vienna, Austria}, year = {2014}, url = {http://www.R-project.org/}, } We have invested a lot of time and effort in creating R, please cite it when using it for data analysis. See also ?citation("pkgname")? for citing R packages. So using this as a template, I would use: Python Core Team (2015). Python: A dynamic, open source programming language. Python Software Foundation. URL https://www.python.org/. -- Steve From alan.gauld at btinternet.com Tue Mar 15 22:10:38 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 16 Mar 2016 02:10:38 +0000 Subject: [Tutor] Changing the interpreter prompt symbol from ">>>" to ??? In-Reply-To: References: <20160312050221.GA88471@cskk.homeip.net> Message-ID: On 16/03/16 01:31, Alan Gauld wrote: > If you now unix then you owe it to yourself to install cygwin. now -> know sorry. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From matt.williams45.mw at gmail.com Tue Mar 15 15:53:56 2016 From: matt.williams45.mw at gmail.com (Matt Williams) Date: Tue, 15 Mar 2016 19:53:56 +0000 Subject: [Tutor] Citing Python In-Reply-To: References: Message-ID: <56E86854.6060107@gmail.com> No, but in his defence, I can imagine someone reading the dissertation and asking for a citation.. (Apologies for TP). M On 15/03/2016 18:43, Alan Gauld wrote: > On 15/03/16 11:45, Holderness, Ellie wrote: > >> How do I cite Python for my dissertation bibliography? >> I used version 3.5.1. > I'm not sure a citation is strictly necessary for a programming > language, but if you want to you could cite the Python web site. > Would you cite JavaScript, CSS or HTML if you built a website? > Or SQL if you built a database? > > If you used a particular tutorial to learn the language > you could cite that (either as a book or web site). > > HTH From steve at pearwood.info Tue Mar 15 23:02:26 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 16 Mar 2016 14:02:26 +1100 Subject: [Tutor] Citing Python In-Reply-To: References: Message-ID: <20160316030225.GB8022@ando.pearwood.info> On Tue, Mar 15, 2016 at 06:43:44PM +0000, Alan Gauld wrote: > On 15/03/16 11:45, Holderness, Ellie wrote: > > > How do I cite Python for my dissertation bibliography? > > I used version 3.5.1. > > I'm not sure a citation is strictly necessary for a programming > language, but if you want to you could cite the Python web site. > Would you cite JavaScript, CSS or HTML if you built a website? > Or SQL if you built a database? If the dissertation was *about* the database, or website, certainly you would. It is normal to cite the software used to generate results, so that others can replicate your work. If Ellie's dissertation depends on Python for her results, or if the dissertation is specifically about Python, then she will probably need to cite the specific version used. One approach is to cite the reference manual for the specific version: http://academia.stackexchange.com/questions/5482/how-do-i-reference-the-python-programming-language-in-a-thesis-or-a-paper See also Brett Cannon's thesis: https://www.researchgate.net/publication/213879590_Localized_Type_Inference_of_Atomic_Types_in_Python (Brett is one of the core developers of Python, particularly well known for his work on the new import system.) It's also common to reference Mathematica: http://support.wolfram.com/kb/472 This paper: "Julia: A Fast Dynamic Language for Technical Computing" http://arxiv.org/abs/1209.5145 references PyPy, Octave and R, but strangely not Julia! > If you used a particular tutorial to learn the language > you could cite that (either as a book or web site). I don't think that is appropriate unless you are specifically referring to the tutorial in the dissertation. -- Steve From eryksun at gmail.com Wed Mar 16 00:36:14 2016 From: eryksun at gmail.com (eryk sun) Date: Tue, 15 Mar 2016 23:36:14 -0500 Subject: [Tutor] Changing the interpreter prompt symbol from ">>>" to ??? In-Reply-To: References: <20160312050221.GA88471@cskk.homeip.net> Message-ID: On Tue, Mar 15, 2016 at 7:45 PM, boB Stepp wrote: > On Tue, Mar 15, 2016 at 7:35 PM, boB Stepp wrote: >> Is the following result in PowerShell related to what Eryk has been discussing? >> >> Windows PowerShell >> Copyright (C) 2009 Microsoft Corporation. All rights reserved. >> >> PS C:\Windows\system32> py >> Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:54:25) [MSC v.1900 >> 64 bit (AMD64)] on w >> in32 >> Type "help", "copyright", "credits" or "license" for more information. >> Active code page: 65001 >> ? help(print) >> Not enough memory. > > Apparently this is another consequence of setting the code page to 65001. See > > https://bugs.python.org/issue19914 I added an analysis of this bug to issue 19914. It's not directly related to a bug in the console, but occurs if the console is set to certain codepages, including 65001. It's a bug in a library that's used by Windows command-line utilities such as more.com and find.exe. The bug doesn't exist in Windows 10. > I am now wondering which is better: Adopt the solution suggested > earlier by Eryk, applying that Python monkey patch and using utf-16 or > doing something more drastic, like installing Cygwin. What are the > cons in doing the latter? Will I achieve Unicode harmony under > Windows by using Cygwin? If you don't need to support Windows, then you could develop in a Linux VM. Unicode works very well in a UTF-8 terminal, which Python's POSIX-oriented I/O system is designed for. From matt.williams45.mw at gmail.com Wed Mar 16 04:36:59 2016 From: matt.williams45.mw at gmail.com (Matt Williams) Date: Wed, 16 Mar 2016 08:36:59 +0000 Subject: [Tutor] Advice on multi-dimensional data storage Message-ID: Dear Tutors, I am looking for some advice. I have some data that has three dimensions to it. I would like to store it such that one could manipulate (query/ update/ etc.) by dimension - so it would be feasible to ask for all of the data that shares a value in d1, or iterate over all of the values via d2. I found some answers on StackOverflow which I need to have a longer look at, but I would be grateful for any thoughts. Thanks, Matt From dvnsarma at gmail.com Wed Mar 16 06:11:58 2016 From: dvnsarma at gmail.com (=?UTF-8?B?RC5WLk4uU2FybWEg4LCh4LC/LuCwteCwvy7gsI7gsKjgsY0u4LC24LCw4LGN4LCu?=) Date: Wed, 16 Mar 2016 15:41:58 +0530 Subject: [Tutor] Fwd: Citing Python In-Reply-To: References: <20160316030225.GB8022@ando.pearwood.info> Message-ID: ---------- Forwarded message ---------- From: D.V.N.Sarma ??.??.???.???? Date: Wed, Mar 16, 2016 at 3:39 PM Subject: Re: [Tutor] Citing Python To: Steven D'Aprano "Python 2.7.11 |Anaconda 2.5.0 (64-bit)| (default, Jan 29 2016, 14:26:21) [MSC v.1500 64 bit (AMD64)] on win32 Type "copyright", "credits" or "license()" for more information." Is not this we get on IDLE a citation? regards, Sarma. On Wed, Mar 16, 2016 at 8:32 AM, Steven D'Aprano wrote: > On Tue, Mar 15, 2016 at 06:43:44PM +0000, Alan Gauld wrote: >> On 15/03/16 11:45, Holderness, Ellie wrote: >> >> > How do I cite Python for my dissertation bibliography? >> > I used version 3.5.1. >> >> I'm not sure a citation is strictly necessary for a programming >> language, but if you want to you could cite the Python web site. >> Would you cite JavaScript, CSS or HTML if you built a website? >> Or SQL if you built a database? > > If the dissertation was *about* the database, or website, certainly you > would. > > It is normal to cite the software used to generate results, so that > others can replicate your work. If Ellie's dissertation depends on > Python for her results, or if the dissertation is specifically about > Python, then she will probably need to cite the specific version used. > > One approach is to cite the reference manual for the specific version: > > http://academia.stackexchange.com/questions/5482/how-do-i-reference-the-python-programming-language-in-a-thesis-or-a-paper > > See also Brett Cannon's thesis: > > https://www.researchgate.net/publication/213879590_Localized_Type_Inference_of_Atomic_Types_in_Python > > (Brett is one of the core developers of Python, particularly well known > for his work on the new import system.) > > It's also common to reference Mathematica: > > http://support.wolfram.com/kb/472 > > This paper: > > "Julia: A Fast Dynamic Language for Technical Computing" > http://arxiv.org/abs/1209.5145 > > references PyPy, Octave and R, but strangely not Julia! > > >> If you used a particular tutorial to learn the language >> you could cite that (either as a book or web site). > > I don't think that is appropriate unless you are specifically referring > to the tutorial in the dissertation. > > > > -- > Steve > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Wed Mar 16 06:21:09 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 16 Mar 2016 10:21:09 +0000 Subject: [Tutor] Citing Python In-Reply-To: <20160316030225.GB8022@ando.pearwood.info> References: <20160316030225.GB8022@ando.pearwood.info> Message-ID: On 16/03/16 03:02, Steven D'Aprano wrote: >> I'm not sure a citation is strictly necessary for a programming >> language, but if you want to you could cite the Python web site. >> Would you cite JavaScript, CSS or HTML if you built a website? >> Or SQL if you built a database? > > If the dissertation was *about* the database, or website, certainly you > would. Ah, yes, that's true. Being an electrical engineer by profession/training I tend to forget that some people do actually write theses *about* computer programs rather than just write programs to support their work. If it were the latter I probably would mention the language (and compiler if relevant) in the text, maybe even provide URLs) but not provide full formal citations. But if I was actually describing the program itself then full citations make sense. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Wed Mar 16 06:30:17 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 16 Mar 2016 10:30:17 +0000 Subject: [Tutor] Advice on multi-dimensional data storage In-Reply-To: References: Message-ID: On 16/03/16 08:36, Matt Williams wrote: > Dear Tutors, > > I am looking for some advice. I have some data that has three dimensions to > it. I would like to store it such that one could manipulate (query/ update/ > etc.) by dimension - so it would be feasible to ask for all of the data > that shares a value in d1, or iterate over all of the values via d2. My personal approach to that tends to be to use a database. If performance is an issue maybe an in-memory SQLIte database. There may be things in NumPy that would help too. Pandas is another possibility. And I suspect R (via Rpy2) can do such tricks too if you know R (otherwise go with Pandas). HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From bgailer at gmail.com Wed Mar 16 07:36:09 2016 From: bgailer at gmail.com (Bob Gailer) Date: Wed, 16 Mar 2016 07:36:09 -0400 Subject: [Tutor] Advice on multi-dimensional data storage In-Reply-To: References: Message-ID: On Mar 16, 2016 5:59 AM, "Matt Williams" wrote: > > Dear Tutors, > > I am looking for some advice. I have some data that has three dimensions to > it. I would like to store it such that one could manipulate (query/ update/ > etc.) by dimension - so it would be feasible to ask for all of the data > that shares a value in d1, or iterate over all of the values via d2. I don't understand. Please give a couple of examples. From steve at pearwood.info Wed Mar 16 09:21:33 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 17 Mar 2016 00:21:33 +1100 Subject: [Tutor] Advice on multi-dimensional data storage In-Reply-To: References: Message-ID: <20160316132132.GC8022@ando.pearwood.info> On Wed, Mar 16, 2016 at 08:36:59AM +0000, Matt Williams wrote: > Dear Tutors, > > I am looking for some advice. I have some data that has three dimensions to > it. I would like to store it such that one could manipulate (query/ update/ > etc.) by dimension - so it would be feasible to ask for all of the data > that shares a value in d1, or iterate over all of the values via d2. As a beginner, you should start with the simplest thing that works: nested lists. If that's not suitable, perhaps too slow, then start to look into more complex solutions, like numpy arrays, or a database. Here's a two dimensional array using nested lists: arr = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12] ] Three rows x 4 columns. Easy, right? Now let's make it three dimensional. It looks a bit uglier, but that's because we're trying to write a three dimensional array in two dimensional text: arr3D = [ # Block 0, 3 rows by 4 columns. [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12] ], # Block 1. [ [0, 0, 0, 0], [1, 2, 4, 8], [2, 4, 6, 8] ], # Block 2. [ [0, 1, 2, 3], [1, 2, 4, 8], [2, 6, 10, 14] ] ] Remember that Python counts positions starting from zero, not one, so it is row 0, 1, 2 not row 1, 2, 3. To access an individual item, give each index in square brackets: py> arr3D[0][2][3] # block 0, row 2, column 3 12 Return an entire block: py> arr3D[1] # block 1 is 3 rows x 4 columns [[0, 0, 0, 0], [1, 2, 4, 8], [2, 4, 6, 8]] Return an entire row: py> arr3D[1][2] # row 2 of block 1 [2, 4, 6, 8] There's no easy way to return a column, but we can use a "list comprehension" to extract one out of a block: py> [row[3] for row in arr3D[1]] # extract column 3 of block 1 [0, 8, 8] Hope this helps! -- Steve From alan.gauld at btinternet.com Wed Mar 16 13:56:47 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 16 Mar 2016 17:56:47 +0000 Subject: [Tutor] (SIP installation problem) Best way to install Python 3 onto Windows 10 In-Reply-To: <56E9559B.9000801@gmail.com> References: <56E87F4B.1010000@gmail.com> <56E9559B.9000801@gmail.com> Message-ID: <56E99E5F.90505@btinternet.com> On 16/03/16 12:46, CMG Thrissur wrote: > > Personally I always install ActiveState Python on > > Windows > I tried to install activestate on win 10 but due to my ignorance or > lack of knowlege i could n't get to install pyqt or sip. i tried it > through pip. Active state only installs standard Python. PyQt (and SIP) are comparatively exotic additions and you will need separate installers for those. I have no experience of either so can't help you, but I've CCd the list to widen the exposure. But you should probably try asking on the PyQt and side forums too, there is more likelihood of somebody there knowing the answer. > Even on basic installation i am getting it hard to find installation of sip. I confess i'm not sure which SIP you mean? Google suggests a C/C++ bindings generator which might make sense if that's what PyQt uses, although I'd expect all the bindings to be done for you. Are you sure you really need it to use PyQt? > But Winpython portable version works like a charm on windows. Again I'm not familiar with Winpython. Google tells me its a "scientific" distro for windows, so I assume similar to Anaconda. If it works, why not just use it? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From eryksun at gmail.com Wed Mar 16 15:10:34 2016 From: eryksun at gmail.com (eryk sun) Date: Wed, 16 Mar 2016 14:10:34 -0500 Subject: [Tutor] (SIP installation problem) Best way to install Python 3 onto Windows 10 In-Reply-To: <56E99E5F.90505@btinternet.com> References: <56E87F4B.1010000@gmail.com> <56E9559B.9000801@gmail.com> <56E99E5F.90505@btinternet.com> Message-ID: On Wed, Mar 16, 2016 at 12:56 PM, Alan Gauld wrote: > On 16/03/16 12:46, CMG Thrissur wrote: > >> I tried to install activestate on win 10 but due to my ignorance or >> lack of knowlege i could n't get to install pyqt or sip. i tried it >> through pip. PyQt can't be easily installed from source using pip on Windows, and the project doesn't distribute pre-built wheel packages. You probably want an installer: https://www.riverbankcomputing.com/software/pyqt/download https://www.riverbankcomputing.com/software/pyqt/download5 Riverbank doesn't have a Python 3.5 build yet, but there's an unofficial wheel available here: http://www.lfd.uci.edu/~gohlke/pythonlibs/#pyqt4 Instructions to install wheels: https://pip.pypa.io/en/latest/user_guide/#installing-from-wheels >> Even on basic installation i am getting it hard to find installation > of sip. > > I confess i'm not sure which SIP you mean? Google suggests a C/C++ > bindings generator which might make sense if that's what PyQt uses, > although I'd expect all the bindings to be done for you. > Are you sure you really need it to use PyQt? The Qt bindings require the sip extension module at runtime, but that's included. If you need SIP for your own C++ project, you can learn more about it and download the source from Riverbank: https://riverbankcomputing.com/software/sip/intro From cmgcomsol at gmail.com Wed Mar 16 08:47:48 2016 From: cmgcomsol at gmail.com (CMG Thrissur) Date: Wed, 16 Mar 2016 18:17:48 +0530 Subject: [Tutor] (SIP installation problem) Best way to install Python 3 onto Windows 10 In-Reply-To: <56E9559B.9000801@gmail.com> References: <56E9559B.9000801@gmail.com> Message-ID: <56E955F4.1060902@gmail.com> On Wednesday 16 March 2016 03:15 AM, Alan Gauld wrote: > On 15/03/16 21:31, Ken G. wrote: >> Having acquired a new laptop yesterday with >> Windows 10 installed and up-to-date, what >> would be the best way to install the latest >> version of Python 3? > Personally I always install ActiveState Python on > Windows so that I can set up the Pythonwin IDE and > use the ActiveState Windows help viewer for the > Python docs. > > The installer should do everything you need for > you. (You may have to locate the pyhonwin exe and > set up a shortcut - I seem to recall that was not > done by the installer for Win 10... > > Caveat: ActiveState are sometimes a few months > behind with their python versions so might not > have the very latest build out yet. > I tried to install activestate on win 10 but due to my ignorance or lack of knowlege i could n't get to install pyqt or sip. i tried it through pip. Even on basic installation i am getting it hard to find installation of sip. How the hell do i get it installed, because i want to work on pyqt and it doesn't install without sip. But Winpython portable version works like a charm on windows. George From paul.hermeneutic at gmail.com Wed Mar 16 23:06:59 2016 From: paul.hermeneutic at gmail.com (paul.hermeneutic at gmail.com) Date: Wed, 16 Mar 2016 21:06:59 -0600 Subject: [Tutor] Best way to install Python 3 onto Windows 10 In-Reply-To: <56E87F4B.1010000@gmail.com> References: <56E87F4B.1010000@gmail.com> Message-ID: I would visit http://www.python.org/ and hover over the "Downloads" text, then choose the desired package. If you want a 64-bit kit, go to https://www.python.org/downloads/release/python-351/ and choose "Windows x86-64 executable installer". On Tue, Mar 15, 2016 at 3:31 PM, Ken G. wrote: > Having acquired a new laptop yesterday with > Windows 10 installed and up-to-date, what > would be the best way to install the latest > version of Python 3? The laptop is an Dell > Latitude E5500 and I am still learning the > bells and whistles of it. I last used Windows > XP 3-4 years back so this usage is all new > to me. > > Currently, I am using Python 2.7.6 on a > desktop Linux system, Ubuntu 14.04.4 and > using Geany as a go to using Python. > > TIA, > > Ken > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From yeh at whoosh.cn Thu Mar 17 03:15:58 2016 From: yeh at whoosh.cn (Yeh) Date: Thu, 17 Mar 2016 15:15:58 +0800 Subject: [Tutor] how to transform the data as below? Message-ID: Hi, I got messages from a MCU by using codes below: import socket import time port = 8888 s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) s.bind(("",port)) print('waiting on port:', port) while True: ??? data, addr = s.recvfrom(1024) ??? print("DATA:", data, addr) ??? time.sleep(100) The messages should be a head "YY" and 5 integers, (each integer is transferred by 2 bytes.) but I got data below. So, how to transform the data? and how to arrange the data to a array? DATA: b'\t\x01x\x01\xfd\x02\x01\x02[YY\x01\t\x01x\x01\xfd\x02\x02\x02ZYY\x01\n\x01x\x01\xfe\x02\x01\x02ZYY\x01\t\x01x\x01\xfe\x02\x02\x02ZYY\x01\t\x01x\x01\xfe\x02\x01\x02[YY\x01\t\x01x\x01\xfe\x02\x02\x02[YY\x01\t\x01x\x01\xfe\x02\x01\x02ZYY\x01\t\x01x\x01\xfd\x02\x02\x02ZYY\x01\t\x01x\x01\xfd\x02\x02\x02ZYY\x01\x08\x01w\x01\xfd\x02\x02\x02ZYY\x01\t\x01w\x01\xfd\x02\x01\x02YYY\x01\t\x01x\x01\xfe\x02\x02\x02ZYY\x01\x08\x01x\x01\xfe\x02\x02\x02ZYY\x01\t\x01x\x01\xfe\x02\x02\x02ZYY\x01\t\x01x\x01\xfe\x02\x01\x02ZYY\x01\t\x01x\x01\xfe\x02\x01\x02ZYY\x01\t\x01x\x01\xfd\x02\x01\x02ZYY\x01\t\x01x\x01\xfd\x02\x02\x02ZYY\x01\t\x01x\x01\xfe\x02\x02\x02ZYY\x01\t\x01x\x01\xfe\x02\x02\x02ZYY\x01\t\x01x\x01\xfe\x02\x01\x02ZYY\x01\t\x01y\x01\xfe\x02\x02\x02ZYY\x01\t\x01x\x01\xfe\x02\x01\x02ZYY\x01\t\x01x\x01\xfe\x02\x01\x02ZYY\x01\t\x01x\x01\xfe\x02\x01\x02ZYY\x01\t\x01x\x01\xfd\x02\x02\x02ZYY\x01\n\x01x\x01\xfe\x02\x01\x02ZYY\x01\t\x01x\x01\xfd\x02\x01\x02ZYY\x01\t\x01x\x01\xfe\x02\x01\x02ZYY\x01\t\x01x\x01\xfe\x02\x01\x02ZYY\x01\n\x01x\x01\xfe\x02\x01\x02ZYY\x01\x08\x01x\x01\xfe\x02\x02\x02ZYY\x01\t\x01x\x01\xfe\x02\x01\x02ZYY\x01\t\x01x\x01\xfd\x02\x02\x02ZYY\x01\x08\x01w\x01\xfd\x02\x01\x02YYY\x01\t\x01x\x01\xfd\x02\x01\x02ZYY\x01\t\x01x\x01\xfd\x02\x01\x02ZYY\x01\t\x01x\x01\xfe\x02\x02\x02ZYY\x01\t\x01x\x01\xfd\x02\x01\x02ZYY\x01\t\x01x\x01\xfd\x02\x02\x02ZYY\x01\t\x01x\x01\xfe\x02\x01\x02ZYY\x01\t\x01y\x01\xfe\x02\x02\x02ZYY\x01\x08\x01x\x01\xfd\x02\x01\x02ZYY\x01\t\x01x\x01\xfe\x02\x02\x02ZYY\x01\t\x01x\x01\xfd\x02\x01\x02ZYY\x01\x08\x01w\x01\xfe\x02\x02\x02ZYY\x01\t\x01x\x01\xfe\x02\x01\x02ZYY\x01\t\x01x\x01\xfe\x02\x02\x02ZYY\x01\t\x01w\x01\xfe\x02\x01\x02ZYY\x01\t\x01x\x01\xfd\x02\x02\x02ZYY\x01\t\x01x\x01\xfd\x02\x01\x02ZYY\x01\x08\x01x\x01\xfe\x02\x02\x02ZYY\x01\t\x01x\x01\xfd\x02\x01\x02ZYY\x01\x08\x01x\x01\xfe\x02\x02\x02ZYY\x01\t\x01x\x01\xfe\x02\x01\x02YYY\x01\t\x01x\x01\xfe\x02\x02\x02ZYY\x01\x08\x01x\x01\xfe\x02\x01\x02ZYY\x01\t\x01x\x01\xfe\x02\x02\x02ZYY\x01\t\x01x\x01\xfd\x02\x01\x02YYY\x01\t\x01x\x01\xfd\x02\x02\x02ZYY\x01\t\x01x\x01\xfe\x02\x02\x02ZYY\x01\t\x01x\x01\xfe\x02\x02\x02ZYY\x01\n\x01x\x01\xfe\x02\x01\x02ZYY\x01\n\x01y\x01\xfe\x02\x01\x02ZYY\x01\t\x01x\x01\xfe\x02\x01\x02ZYY\x01\t\x01x\x01\xfe\x02\x01\x02ZYY\x01\t\x01y\x01\xfe\x02\x01\x02ZYY\x01\t\x01x\x01\xfe\x02\x01\x02ZYY\x01\t\x01x\x01\xfd\x02\x01\x02ZYY\x01\t\x01x\x01\xfd\x02\x01\x02ZYY\x01\t\x01x\x01\xfd\x02\x01\x02ZYY\x01\x08\x01w\x01\xfd\x02\x02\x02ZYY\x01\t\x01x\x01\xfe\x02\x01\x02ZYY\x01\t\x01x\x01\xfd\x02\x02\x02ZYY\x01\t\x01x\x01\xfd\x02\x01\x02ZYY\x01\x08\x01x\x01\xfe\x02\x02\x02ZYY\x01\t\x01w\x01\xfd\x02\x01\x02ZYY\x01\t\x01x\x01\xfd\x02\x02\x02ZYY\x01\x08\x01w\x01\xfe\x02\x01\x02ZYY\x01\t\x01w\x01\xfe\x02\x02\x02ZYY\x01\t\x01w\x01\xfe\x02\x01\x02ZYY\x01\x08\x01x\x01\xfd\x02\x02\x02ZYY\x01\t\x01x\x01\xfd\x02\x02\x02ZYY\x01\x08\x01x\x01' ('192.168.1.101', 35000) Thanks! Yeh From __peter__ at web.de Thu Mar 17 05:47:47 2016 From: __peter__ at web.de (Peter Otten) Date: Thu, 17 Mar 2016 10:47:47 +0100 Subject: [Tutor] how to transform the data as below? References: Message-ID: Yeh wrote: > Hi, > > I got messages from a MCU by using codes below: > > import socket > import time > > port = 8888 > s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) > s.bind(("",port)) > print('waiting on port:', port) > while True: > data, addr = s.recvfrom(1024) > print("DATA:", data, addr) > time.sleep(100) > > The messages should be a head "YY" and 5 integers, (each integer is > transferred by 2 bytes.) but I got data below. So, how to transform the > data? and how to arrange the data to a array? > > DATA: > b'\t\x01x\x01\xfd\x02\x01\x02[YY\x01\t\x01x\x01... > ('192.168.1.101', 35000) What you read are the raw bytes. The array module offers one way to convert bytes to integers. Unfortunately the separator byte sequence b"YY" (or b"XY" followed by b"YZ") is also that for the integer 22873: >>> array.array("H", b"YY") array('H', [22873]) Therefore you cannot be 100% sure when you start the bytes-to-int conversion at the first occurence of b"YY". Here's an example that uses a simple heuristics (which may fail!) to cope with the problem import array, re def find_start(data): for m in re.compile(b"YY").finditer(data): if all( data[i:i+2] == b"YY" for i in range(m.start(), len(data), 12)): return m.start() raise ValueError data = b'\t\x01x\x01\xfd\x02\x01\x02[YY\x01\t... if __name__ == "__main__": start = find_start(data) for i in range(start, len(data)-11, 12): chunk = data[i:i+12] print(chunk, "-->", list(array.array("H", chunk[2:]))) From oscar.j.benjamin at gmail.com Thu Mar 17 11:27:37 2016 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Thu, 17 Mar 2016 15:27:37 +0000 Subject: [Tutor] Advice on multi-dimensional data storage In-Reply-To: <20160316132132.GC8022@ando.pearwood.info> References: <20160316132132.GC8022@ando.pearwood.info> Message-ID: On 16 March 2016 at 13:21, Steven D'Aprano wrote: > On Wed, Mar 16, 2016 at 08:36:59AM +0000, Matt Williams wrote: >> Dear Tutors, >> >> I am looking for some advice. I have some data that has three dimensions to >> it. I would like to store it such that one could manipulate (query/ update/ >> etc.) by dimension - so it would be feasible to ask for all of the data >> that shares a value in d1, or iterate over all of the values via d2. Can you give a bit more information about this? Do you want persistent (i.e. on the hard-disk) storage like Alan's database idea? Or do you want an in memory data structure like Steve's lists of lists idea? What do you want to store in this data structure (numbers, strings, other Python objects, ...)? I'll assume as Steve did that you want to store numbers in an in-memory data structure. Steve proposed this list of lists construct: > arr3D = [ > # Block 0, 3 rows by 4 columns. > [ [1, 2, 3, 4], > [5, 6, 7, 8], > [9, 10, 11, 12] ], > # Block 1. > [ [0, 0, 0, 0], > [1, 2, 4, 8], > [2, 4, 6, 8] ], > # Block 2. > [ [0, 1, 2, 3], > [1, 2, 4, 8], > [2, 6, 10, 14] ] > ] With numpy we can go one better and turn this into a true 3D array: >>> import numpy as np >>> nparr3D = np.array(arr3D) >>> nparr3D array([[[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12]], [[ 0, 0, 0, 0], [ 1, 2, 4, 8], [ 2, 4, 6, 8]], [[ 0, 1, 2, 3], [ 1, 2, 4, 8], [ 2, 6, 10, 14]]]) Now that we have this we can do all sorts of things with it. Think of your 3D array as pages where each page has rows and columns. We can select a page: >>> nparr3D[0] array([[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12]]) Or we can select an element: >>> nparr3D[0,2,3] 12 We can select the first row of each page making a 2D array: >>> nparr3D[:,0,:] array([[1, 2, 3, 4], [0, 0, 0, 0], [0, 1, 2, 3]]) We can select the last column: >>> nparr3D[:,:,3] array([[ 4, 8, 12], [ 0, 8, 8], [ 3, 8, 14]]) >>> nparr3D[:,:,3].transpose() array([[ 4, 0, 3], [ 8, 8, 8], [12, 8, 14]]) We can also modify the array. Let's add 100 to the first page: >>> nparr3D[0, :, :] += 100 >>> nparr3D array([[[101, 102, 103, 104], [105, 106, 107, 108], [109, 110, 111, 112]], [[ 0, 0, 0, 0], [ 1, 2, 4, 8], [ 2, 4, 6, 8]], [[ 0, 1, 2, 3], [ 1, 2, 4, 8], [ 2, 6, 10, 14]]]) There are many more things that you can do here if you learn to use numpy. -- Oscar From cmgcomsol at gmail.com Thu Mar 17 07:32:39 2016 From: cmgcomsol at gmail.com (CMG Thrissur) Date: Thu, 17 Mar 2016 17:02:39 +0530 Subject: [Tutor] (SIP installation problem) Best way to install Python 3 onto Windows 10 In-Reply-To: <56E99E5F.90505@btinternet.com> References: <56E87F4B.1010000@gmail.com> <56E9559B.9000801@gmail.com> <56E99E5F.90505@btinternet.com> Message-ID: <56EA95D7.6030003@gmail.com> On Wednesday 16 March 2016 11:26 PM, Alan Gauld wrote: > On 16/03/16 12:46, CMG Thrissur wrote: >>> Personally I always install ActiveState Python on >>> Windows >> I tried to install activestate on win 10 but due to my ignorance or >> lack of knowlege i could n't get to install pyqt or sip. i tried it >> through pip. > Active state only installs standard Python. PyQt (and SIP) are > comparatively > exotic additions and you will need separate installers for those. > I have no experience of either so can't help you, but I've CCd the list > to widen the exposure. But you should probably try asking on the PyQt > and side forums too, there is more likelihood of somebody there knowing > the answer. > >> Even on basic installation i am getting it hard to find installation > of sip. > > I confess i'm not sure which SIP you mean? Google suggests a C/C++ > bindings generator which might make sense if that's what PyQt uses, > although I'd expect all the bindings to be done for you. > Are you sure you really need it to use PyQt? > >> But Winpython portable version works like a charm on windows. > Again I'm not familiar with Winpython. Google tells me its a "scientific" > distro for windows, so I assume similar to Anaconda. If it works, why > not just use it? > I think linux is much better and i will stick to it, but at work i have to work on win 10 and that to i sometimes have to make python utilities for others to work on which requires a gui, like a simple example i have to combine many excel files and extract specific items from them and then make a new xls file. Now i can do it on cui but for other people to use the software who are not so digital oriented like me will find it hard to use cui, beside that if i don't present them a dialog to point to the directory where they have the file, they would find it very difficult. some staff members just use the computers on hit or miss strategy.(You can understand that if tell you they call me computer geek with my level of knowledge ;).) Now i have a little good understanding of c++ and through it Qt so qt is very easy for me to work on rather than working on tkinter or gtk, and other wx thing is not working on py3, so you can understand that if cant install PYQT for developing apps. I tried it first time form the standard python edition and then from activestate version, hoping that pyqt will be installed easily as it gets installed on linux but to my surprise it doesn't. So here i am trying each and everything. To add to my frustration the SiP distribution pointed by pyqt contains a readme which asks me to use a file to install it (something i am not remembering right now) and the said file cannot be found anywhere in the distribution of SIP. Winpython is a portable distribtuion which just gets the work done, but if i have to replace or update something then i think i am out of luck on windows. Thanks for enduring my rant and frustration on the topic. I will now try the same with pyqt group maybe they have some idea about the product. Although i will trouble you with my other problems on python. George From cmgcomsol at gmail.com Thu Mar 17 07:36:02 2016 From: cmgcomsol at gmail.com (CMG Thrissur) Date: Thu, 17 Mar 2016 17:06:02 +0530 Subject: [Tutor] (SIP installation problem) Best way to install Python 3 onto Windows 10 In-Reply-To: References: <56E87F4B.1010000@gmail.com> <56E9559B.9000801@gmail.com> <56E99E5F.90505@btinternet.com> Message-ID: <56EA96A2.3060807@gmail.com> On Thursday 17 March 2016 12:40 AM, eryk sun wrote: > On Wed, Mar 16, 2016 at 12:56 PM, Alan Gauld wrote: >> On 16/03/16 12:46, CMG Thrissur wrote: >> >>> I tried to install activestate on win 10 but due to my ignorance or >>> lack of knowlege i could n't get to install pyqt or sip. i tried it >>> through pip. > PyQt can't be easily installed from source using pip on Windows, and > the project doesn't distribute pre-built wheel packages. You probably > want an installer: > > https://www.riverbankcomputing.com/software/pyqt/download > https://www.riverbankcomputing.com/software/pyqt/download5 > > Riverbank doesn't have a Python 3.5 build yet, but there's an > unofficial wheel available here: > > http://www.lfd.uci.edu/~gohlke/pythonlibs/#pyqt4 > > Instructions to install wheels: > > https://pip.pypa.io/en/latest/user_guide/#installing-from-wheels > >>> Even on basic installation i am getting it hard to find installation >> of sip. >> >> I confess i'm not sure which SIP you mean? Google suggests a C/C++ >> bindings generator which might make sense if that's what PyQt uses, >> although I'd expect all the bindings to be done for you. >> Are you sure you really need it to use PyQt? > The Qt bindings require the sip extension module at runtime, but > that's included. If you need SIP for your own C++ project, you can > learn more about it and download the source from Riverbank: > > https://riverbankcomputing.com/software/sip/intro Thank you for the link but on that page i see mention of SIP requirement, is that required for binary package also. George From sinasareth at yahoo.com Thu Mar 17 13:48:21 2016 From: sinasareth at yahoo.com (sina sareth) Date: Thu, 17 Mar 2016 17:48:21 +0000 (UTC) Subject: [Tutor] Advice on multi-dimensional data storage In-Reply-To: References: Message-ID: <1529813961.364851.1458236901238.JavaMail.yahoo@mail.yahoo.com> Hi thereI would like to make 2 apps I wonder if somebody has a similar codes. ?They said it is easier to use Django and MySQL.Thanks 1) XML parsing into database.?2) Do the same thing but this time, get ALL the quotes and save them as separate database entries (you will have to do a for loop for this).? On Thursday, March 17, 2016 8:28 AM, Oscar Benjamin wrote: On 16 March 2016 at 13:21, Steven D'Aprano wrote: > On Wed, Mar 16, 2016 at 08:36:59AM +0000, Matt Williams wrote: >> Dear Tutors, >> >> I am looking for some advice. I have some data that has three dimensions to >> it. I would like to store it such that one could manipulate (query/ update/ >> etc.) by dimension - so it would be feasible to ask for all of the data >> that shares a value in d1, or iterate over all of the values via d2. Can you give a bit more information about this? Do you want persistent (i.e. on the hard-disk) storage like Alan's database idea? Or do you want an in memory data structure like Steve's lists of lists idea? What do you want to store in this data structure (numbers, strings, other Python objects, ...)? I'll assume as Steve did that you want to store numbers in an in-memory data structure. Steve proposed this list of lists construct: > arr3D = [ >? ? ? ? ? # Block 0, 3 rows by 4 columns. >? ? ? ? ? [ [1, 2, 3, 4], >? ? ? ? ? ? [5, 6, 7, 8], >? ? ? ? ? ? [9, 10, 11, 12] ], >? ? ? ? ? # Block 1. >? ? ? ? ? [ [0, 0, 0, 0], >? ? ? ? ? ? [1, 2, 4, 8], >? ? ? ? ? ? [2, 4, 6, 8] ], >? ? ? ? ? # Block 2. >? ? ? ? ? [ [0, 1, 2, 3], >? ? ? ? ? ? [1, 2, 4, 8], >? ? ? ? ? ? [2, 6, 10, 14] ] >? ? ? ? ? ] With numpy we can go one better and turn this into a true 3D array: >>> import numpy as np >>> nparr3D = np.array(arr3D) >>> nparr3D array([[[ 1,? 2,? 3,? 4], ? ? ? ? [ 5,? 6,? 7,? 8], ? ? ? ? [ 9, 10, 11, 12]], ? ? ? [[ 0,? 0,? 0,? 0], ? ? ? ? [ 1,? 2,? 4,? 8], ? ? ? ? [ 2,? 4,? 6,? 8]], ? ? ? [[ 0,? 1,? 2,? 3], ? ? ? ? [ 1,? 2,? 4,? 8], ? ? ? ? [ 2,? 6, 10, 14]]]) Now that we have this we can do all sorts of things with it. Think of your 3D array as pages where each page has rows and columns. We can select a page: >>> nparr3D[0] array([[ 1,? 2,? 3,? 4], ? ? ? [ 5,? 6,? 7,? 8], ? ? ? [ 9, 10, 11, 12]]) Or we can select an element: >>> nparr3D[0,2,3] 12 We can select the first row of each page making a 2D array: >>> nparr3D[:,0,:] array([[1, 2, 3, 4], ? ? ? [0, 0, 0, 0], ? ? ? [0, 1, 2, 3]]) We can select the last column: >>> nparr3D[:,:,3] array([[ 4,? 8, 12], ? ? ? [ 0,? 8,? 8], ? ? ? [ 3,? 8, 14]]) >>> nparr3D[:,:,3].transpose() array([[ 4,? 0,? 3], ? ? ? [ 8,? 8,? 8], ? ? ? [12,? 8, 14]]) We can also modify the array. Let's add 100 to the first page: >>> nparr3D[0, :, :] += 100 >>> nparr3D array([[[101, 102, 103, 104], ? ? ? ? [105, 106, 107, 108], ? ? ? ? [109, 110, 111, 112]], ? ? ? [[? 0,? 0,? 0,? 0], ? ? ? ? [? 1,? 2,? 4,? 8], ? ? ? ? [? 2,? 4,? 6,? 8]], ? ? ? [[? 0,? 1,? 2,? 3], ? ? ? ? [? 1,? 2,? 4,? 8], ? ? ? ? [? 2,? 6,? 10,? 14]]]) There are many more things that you can do here if you learn to use numpy. -- Oscar _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor From ton.nakano at outlook.com Thu Mar 17 10:11:06 2016 From: ton.nakano at outlook.com (Yeh Z) Date: Thu, 17 Mar 2016 22:11:06 +0800 Subject: [Tutor] how to transform the data as below? Message-ID: Thanks for your help, It's my bad, I should put them to a list, not a array? such as: YY, 100, 140, 200, 110, 160? Firstly, I'm confused about how to convert them to string and integers? the raw bytes? Is it different to the bytes packing by "pack"? I want to read them by a human way. Besides, the MUC is made by my friend, we want to make an installation, which can send data via UDP from a sensor. Maybe, we can change some things in MUC? I don't know MUC totally. :( I just trying to learn Python. Thanks Yeh -------- Original Message -------- Subject: Re: [Tutor] how to transform the data as below? From: Peter Otten <__peter__ at web.de> To: tutor at python.org CC: Yeh wrote: > Hi, > > I got messages from a MCU by using codes below: > > import socket > import time > > port = 8888 > s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) > s.bind(("",port)) > print('waiting on port:', port) > while True: > data, addr = s.recvfrom(1024) > print("DATA:", data, addr) > time.sleep(100) > > The messages should be a head "YY" and 5 integers, (each integer is > transferred by 2 bytes.) but I got data below. So, how to transform the > data? and how to arrange the data to a array? > > DATA: > b'\t\x01x\x01\xfd\x02\x01\x02[YY\x01\t\x01x\x01... > ('192.168.1.101', 35000) What you read are the raw bytes. The array module offers one way to convert bytes to integers. Unfortunately the separator byte sequence b"YY" (or b"XY" followed by b"YZ") is also that for the integer 22873: >>> array.array("H", b"YY") array('H', [22873]) Therefore you cannot be 100% sure when you start the bytes-to-int conversion at the first occurence of b"YY". Here's an example that uses a simple heuristics (which may fail!) to cope with the problem import array, re def find_start(data): ??? for m in re.compile(b"YY").finditer(data): ??????? if all( ??????????????? data[i:i+2] == b"YY" ??????????????? for i in range(m.start(), len(data), 12)): ??????????? ??????????? return m.start() ??? raise ValueError data = b'\t\x01x\x01\xfd\x02\x01\x02[YY\x01\t... if __name__ == "__main__": ??? start = find_start(data) ??? for i in range(start, len(data)-11, 12): ??????? chunk = data[i:i+12] ??????? print(chunk, "-->", list(array.array("H", chunk[2:]))) _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: [1]https://mail.python.org/mailman/listinfo/tutor References Visible links 1. https://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Thu Mar 17 19:44:30 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 17 Mar 2016 23:44:30 +0000 Subject: [Tutor] (SIP installation problem) Best way to install Python 3 onto Windows 10 In-Reply-To: <56EA95D7.6030003@gmail.com> References: <56E87F4B.1010000@gmail.com> <56E9559B.9000801@gmail.com> <56E99E5F.90505@btinternet.com> <56EA95D7.6030003@gmail.com> Message-ID: On 17/03/16 11:32, CMG Thrissur wrote: >>> But Winpython portable version works like a charm on windows. >> > I think linux is much better and i will stick to it, but at work i have > to work on win 10 and that to i sometimes have to make python utilities > for others to work on which requires a gui, Sure I understand that. I use Linux 90% of the time but other people use Windows so I have Windows boxes too. > Now i have a little good understanding of c++ and through it Qt Ok, if you know Qt stick with it. > pyqt will be installed easily as it gets installed on linux but to my > surprise it doesn't. I think it is if you use a binary installer. I did load it up once on windows a long time ago, decided I didn't like it much and went back to Tkinter. But it wasn't very hard to get it working - I'd have given up sooner if it was! > Thanks for enduring my rant and frustration on the topic. It's fine and explains your choices. Sometimes it's good to just let go ;-) > the same with pyqt group maybe they have some idea There are a lot more of them using Qt than on this list that's for sure. I hope you get something working soon. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Thu Mar 17 19:56:20 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 17 Mar 2016 23:56:20 +0000 Subject: [Tutor] Two web apps (was Re: Advice on multi-dimensional data storage) In-Reply-To: <1529813961.364851.1458236901238.JavaMail.yahoo@mail.yahoo.com> References: <1529813961.364851.1458236901238.JavaMail.yahoo@mail.yahoo.com> Message-ID: On 17/03/16 17:48, sina sareth via Tutor wrote: Please start a new thread for a new subject and please change the subject line it makes searching the archives much easier. > Hi thereI would like to make 2 apps I wonder if somebody has a similar codes. We would need a bit more background information. > They said it is easier to use Django and MySQL. Who are "they"? Easier than what? Django is a fine framework but there are many others and several are easier to start with than Django. (Although probably more limiting later) As for MySQL do you know SQL? If not that is just another learning curve to climb. And given the comment below, about suggesting you use a for loop, I'd guess you aren't very far up the Python learning curve yet? > 1) XML parsing into database. This doesn't need to be a web app at all from the description, it could just be a command line tool. But what are you supposed to parse out of the XML? The description is far too vague to mean anything. > 2) Do the same thing but this time, get ALL the quotes and save > them as separate database entries > (you will have to do a for loop for this). Again there is no mention of web here so you don't need Django. But what does it mean by "quotes"? I assume they are a feature of your XML file but we have no idea what it looks like. Based on what you have shown us I'd use standard Python and the xml.etree package in the standard library. Are you using Python v2 or v3? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From eryksun at gmail.com Thu Mar 17 21:06:12 2016 From: eryksun at gmail.com (eryk sun) Date: Thu, 17 Mar 2016 20:06:12 -0500 Subject: [Tutor] (SIP installation problem) Best way to install Python 3 onto Windows 10 In-Reply-To: <56EA96A2.3060807@gmail.com> References: <56E87F4B.1010000@gmail.com> <56E9559B.9000801@gmail.com> <56E99E5F.90505@btinternet.com> <56EA96A2.3060807@gmail.com> Message-ID: On Thu, Mar 17, 2016 at 6:36 AM, CMG Thrissur wrote: > Thank you for the link but on that page i see mention of SIP requirement, is > that required for binary package also. The .exe and .whl packages for PyQt are self-contained. You don't need anything else, and you don't have to build anything from source. From __peter__ at web.de Fri Mar 18 05:32:12 2016 From: __peter__ at web.de (Peter Otten) Date: Fri, 18 Mar 2016 10:32:12 +0100 Subject: [Tutor] how to transform the data as below? References: Message-ID: Yeh Z wrote: [Please don't top-post. Thank you] > Thanks for your help, > > It's my bad, I should put them to a list, not a array? > such as: > YY, 100, 140, 200, 110, 160? I supposed that you are trying to read binary data. > Firstly, I'm confused about how to convert them to string and integers? > the raw bytes? Is it different to the bytes packing by "pack"? I want > to read them by a human way. If you can control what data is generated then using text would indeed simplify things. > Besides, the MUC is made by my friend, we want to make an installation, > which can send data via UDP from a sensor. Maybe, we can change some > things in MUC? I don't know MUC totally. :( I just trying to learn > Python. By the way, what is a MUC? From yeh at whoosh.cn Fri Mar 18 07:41:21 2016 From: yeh at whoosh.cn (Yeh) Date: Fri, 18 Mar 2016 19:41:21 +0800 Subject: [Tutor] how to transform the data as below? In-Reply-To: References: , Message-ID: Thanks for your help, Sorry for top-post and MUC. It is MCU - Micro Controller Unit. > I supposed that you are trying to read binary data. my friend said to me that the data should be the hexadecimal, and I need convert them to string "YY" and decimal integers first. but why the data which I received are including "YY"? Is it due to "recvfrom"? > If you can control what data is generated then using text would indeed > simplify things. using text mean strings? If it still doesn't work, we will try to send strings from MCU, but for efficiency, the hexadecimal is better, right? Finaly, we are going to pack the data to OSC messages to some musical softwares. We have already sent OSC messages from Python via UDP. But when we try to change the client to a MCU, we got these problems. So... What can we do next? Thanks Yeh Z From __peter__ at web.de Fri Mar 18 11:31:38 2016 From: __peter__ at web.de (Peter Otten) Date: Fri, 18 Mar 2016 16:31:38 +0100 Subject: [Tutor] how to transform the data as below? References: Message-ID: Yeh wrote: > Thanks for your help, > > Sorry for top-post and MUC. It is MCU - Micro Controller Unit. > >> I supposed that you are trying to read binary data. > > my friend said to me that the data should be the hexadecimal, and I need > convert them to string "YY" and decimal integers first. but why the data > which I received are including "YY"? Is it due to "recvfrom"? I suppose he thinks that hexadecimal and binary is the same. The data you showed is binary. For example the following sequence of bytes 9 1 120 1 253 2 is displayed as the bytestring b'\t\x01x\x01\xfd' in Python. When the bytes are shown as hexadecimal numbers the same data looks like this: 09 01 78 01 fd 02 >> If you can control what data is generated then using text would indeed >> simplify things. > > using text mean strings? If it still doesn't work, we will try to send > strings from MCU, but for efficiency, the hexadecimal is better, right? First make it work, then worry about "efficiency". > Finaly, we are going to pack the data to OSC messages to some musical > softwares. We have already sent OSC messages from Python via UDP. But when > we try to change the client to a MCU, we got these problems. > > So... What can we do next? Look for a library that understands OSC? I assume that means Open Sound Control... From alan.gauld at btinternet.com Fri Mar 18 14:51:24 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 18 Mar 2016 18:51:24 +0000 Subject: [Tutor] how to transform the data as below? In-Reply-To: References: Message-ID: On 18/03/16 15:31, Peter Otten wrote: > I suppose he thinks that hexadecimal and binary is the same. The data you > showed is binary. For example the following sequence of bytes > > 9 1 120 1 253 2 > > is displayed as the bytestring > > b'\t\x01x\x01\xfd' What happened to the 2 at the end? Shouldn't it be: b'\t\x01x\x01\xfd\x02' -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From __peter__ at web.de Fri Mar 18 15:09:29 2016 From: __peter__ at web.de (Peter Otten) Date: Fri, 18 Mar 2016 20:09:29 +0100 Subject: [Tutor] how to transform the data as below? References: Message-ID: Alan Gauld wrote: > On 18/03/16 15:31, Peter Otten wrote: > >> I suppose he thinks that hexadecimal and binary is the same. The data you >> showed is binary. For example the following sequence of bytes >> >> 9 1 120 1 253 2 >> >> is displayed as the bytestring >> >> b'\t\x01x\x01\xfd' > > What happened to the 2 at the end? > Shouldn't it be: > > b'\t\x01x\x01\xfd\x02' Yes, sorry. From robertvstepp at gmail.com Sat Mar 19 00:26:13 2016 From: robertvstepp at gmail.com (boB Stepp) Date: Fri, 18 Mar 2016 23:26:13 -0500 Subject: [Tutor] How to test function using random.randint()? Message-ID: If I had a function to roll a die, such as: import random def roll_die(num_sides): return random.randint(1, num_sides) How would I write unit tests for this? The first thing that suggests itself to me is to do something like assertIn(roll_die(num_sides), range(1, num_sides + 1) And I would think I would want to come up with some sort of "reasonable" number of iterations of such a test. What would be "reasonable" is unclear to me. But in theory I might not hit all possible sides of the die being rolled. I could also check for numbers not in the desired range. And I can check for invalid values for num_sides to see if the appropriate exceptions get raised. And I do not see how I can test for an appropriate "randomness" to the numbers the function generates without to a lot of iterations, figuring out what statistical analysis I need to do, etc. Of course I don't know that I care about testing for this for what will be used in a game for fun. Am I on the right track with this? The actual function will be more complicated in that it will generate a result for multiple dice with potentially a variety of sides, e.g., 3d6 + 1d10, etc. -- boB From ben+python at benfinney.id.au Sat Mar 19 01:05:58 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 19 Mar 2016 16:05:58 +1100 Subject: [Tutor] How to test function using random.randint()? References: Message-ID: <85lh5fhxah.fsf@benfinney.id.au> boB Stepp writes: > If I had a function to roll a die, such as: > > import random > > def roll_die(num_sides): > return random.randint(1, num_sides) > > How would I write unit tests for this? You need to make the system deterministic during the test run. Since the random number generator (RNG) is a dependency that your test cases don't entirely control, that is a dependency that makes the system non-deterministic. One way to do that is to allow the dependency ? the RNG ? to be specified as part of the API of the system under test:: def roll_die(num_sides, rng=None): This is known as the ?dependency injection? pattern. The system makes a deliberate API for its dependencies, and allows the caller to specify the object that represents the dependency. The system does not directly use the external dependency; it uses the dependency supplied, as an abstraction:: import random def roll_die(num_sides, rng=None): """ Return a result from a random die of `num_sides` sides. :param num_sides: The number of sides on the die. :param rng: An instance of `random.Random`, the random number generator to use. Default: the `random.random` instance. :return: The integer result from the die roll. The die is defined to have equal-probability faces, numbered from 1 to `num_sides`. """ if rng is None: rng = random.random result = rng.randint(1, num_sides) return result In this case the dependency has a sensible default, so the caller doesn't *need* to specify the dependency. That's not always true, and dependency injection often entails re-designing the API and callers must adapt to that new API. With that re-design, the test module can create an RNG that behaves as expected. Your test cases can create their own RNG instance and specify its seed, which means the same numbers will be generated every time from that seed. import unittest import random from . import die_roller # The system under test. class roll_die_TestCase(unittest.TestCase): """ Test cases for the `roll_die` function. """ def setUp(self): """ Set up test fixtures. """ # Set the seed value such that the system can't anticipate # it, but such that we can re-use it any time. self.seed = id(self) self.rng = random.Random(self.seed) def test_result_in_expected_range(self): """ The result should be in the range expected for the die. """ test_num_sides = 6 expected_range = range(1, test_num_sides + 1) result = die_roller.roll_die(test_num_sides, rng=self.rng) self.assertIn(result, expected_range) def test_result_is_from_rng(self): """ The result should be produced by the supplied RNG. """ test_num_sides = 6 self.rng.seed(self.seed) expected_result = self.rng.randint(1, test_num_sides) self.rng.seed(self.seed) result = die_roller.roll_die(test_num_sides, rng=self.rng) self.assertEqual(result, expected_result) > And I do not see how I can test for an appropriate "randomness" to the > numbers the function generates without to a lot of iterations, That's the thing about randomness. By definition, you can't determine it :-) But by providing your own RNG that is under control of the test cases, you can know what numbers it will produce by re-setting it to a known seed. Hopefully you can take this as an example of how to better design systems so they don't have tightly-entangled external dependencies. -- \ ?The good thing about science is that it's true whether or not | `\ you believe in it.? ?Neil deGrasse Tyson, 2011-02-04 | _o__) | Ben Finney From alan.gauld at btinternet.com Sat Mar 19 05:04:32 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 19 Mar 2016 09:04:32 +0000 Subject: [Tutor] How to test function using random.randint()? In-Reply-To: References: Message-ID: On 19/03/16 04:26, boB Stepp wrote: > If I had a function to roll a die, such as: > > How would I write unit tests for this? Ben has given the general case answer. > And I do not see how I can test for an appropriate "randomness" to the > numbers the function generates without to a lot of iterations, And you have answered the specific case where it is the randomness itself that you are testing. In that case you need to generate a lot of iterations (several thousand say) and store the results then analyze the spread against the desired distribution pattern. There is no shortcut. And if the nature of the randomness is important, as it often is in simulations etc you have to do it. But in most cases the amount of randomness is not critical and you are using a well known and tested RNG so you only need to check the scaling is producing the right output range. That does mean you need to check the boundary conditions carefully and that may also involve a loop to create enough samples to be sure. One of the most common errors with RNGs is to generate 1 less than the desired range. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From steve at pearwood.info Sat Mar 19 08:29:10 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 19 Mar 2016 23:29:10 +1100 Subject: [Tutor] How to test function using random.randint()? In-Reply-To: References: Message-ID: <20160319122910.GJ8022@ando.pearwood.info> On Fri, Mar 18, 2016 at 11:26:13PM -0500, boB Stepp wrote: > If I had a function to roll a die, such as: > > import random > > def roll_die(num_sides): > return random.randint(1, num_sides) > > How would I write unit tests for this? (1) One way would be to monkey-patch the random module with your own. Something like this: import mymodule # The module containing the roll_die function. class random: @staticmethod def myrandomint(a, b): return 5 save = mymodule.random try: mymodule.random = random assert mymodule.roll_die(100) == 5 finally: mymodule.random = save Better would be to set up myrandomint so that it returns a specific sequence of values, so you can write: assert mymodule.roll_die(100) == 5 assert mymodule.roll_die(100) == 23 assert mymodule.roll_die(100) == 17 assert mymodule.roll_die(100) == 2 (for example). One way to get a known sequence of values is like this: values = [5, 23, 17, 2] it = iter(values) func = functools.partial(next, it, 999) Now func is a function that takes no arguments and returns 5 the first time you call it, 23 the second time, and so on, and then returns 999 forever afterwards. (2) Another way is to use the random seed to get a predictable series of values: import mymodule mymodule.random.seed(95) assert mymodule.roll_die(6) == 3 assert mymodule.roll_die(6) == 2 assert mymodule.roll_die(6) == 6 assert mymodule.roll_die(6) == 6 assert mymodule.roll_die(6) == 5 But beware: Python only guarantees that changing the seed will give the same sequence of values for random.random(), *not* for the other random functions. So they can change according to the version of Python you are using. However, you know that given some specific version, the output of randint(a, b) will be the same when given the same seed. It may be different for another version. (3) A third approach is "dependency injection". Re-write your roll_die function like this: def roll_die(num_sides, randint=None): if randint is None: # Use the default randint from random import randint return randint(1, num_sides) Now, when testing, you can *explicitly* provide a "randint" function that returns whatever you like. Use the monkey-patch technique above, or your own custom random generator: import random myrand = random.Random() # Make an independent PRNG. myrand.seed(1000) # Seed to a known value # Record the values it gives. values = [myrand.randint(1, 6) for i in range(1000)] myrand.seed(1000) # Restore the seed. for expected_value in values: assert mymodule.roll_die(6, myrand.randint) == expected_value -- Steve From steve at pearwood.info Sat Mar 19 09:03:56 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 20 Mar 2016 00:03:56 +1100 Subject: [Tutor] How to test function using random.randint()? In-Reply-To: <85lh5fhxah.fsf@benfinney.id.au> References: <85lh5fhxah.fsf@benfinney.id.au> Message-ID: <20160319130356.GK8022@ando.pearwood.info> On Sat, Mar 19, 2016 at 04:05:58PM +1100, Ben Finney wrote: > import random > > def roll_die(num_sides, rng=None): > """ Return a result from a random die of `num_sides` sides. > > :param num_sides: The number of sides on the die. > :param rng: An instance of `random.Random`, the random > number generator to use. > Default: the `random.random` instance. > :return: The integer result from the die roll. > > The die is defined to have equal-probability faces, numbered > from 1 to `num_sides`. > > """ > if rng is None: > rng = random.random Typo: you want rng = random.randint. > result = rng.randint(1, num_sides) And here you just want result = rng(1, num_sides). Otherwise you're trying to call random.randint.randint. > > And I do not see how I can test for an appropriate "randomness" to the > > numbers the function generates without to a lot of iterations, > > That's the thing about randomness. By definition, you can't determine it > :-) http://dilbert.com/strip/2001-10-25 But all joking aside, Python's pseudo-random number generator is one of the best in the world, the Mersenne Twister. For non-cryptographical purposes, it is as random as anything you are likely to need. https://en.wikipedia.org/wiki/Mersenne_Twister It passes all, or most, of the stringent "Diehard" and other tests for randomness: https://en.wikipedia.org/wiki/Diehard_tests -- Steve From alan.gauld at btinternet.com Sat Mar 19 14:19:57 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 19 Mar 2016 18:19:57 +0000 Subject: [Tutor] How to test function using random.randint()? In-Reply-To: <20160319130356.GK8022@ando.pearwood.info> References: <85lh5fhxah.fsf@benfinney.id.au> <20160319130356.GK8022@ando.pearwood.info> Message-ID: On 19/03/16 13:03, Steven D'Aprano wrote: > But all joking aside, Python's pseudo-random number generator is one of > the best in the world, the Mersenne Twister. For non-cryptographical > purposes, it is as random as anything you are likely to need. > > https://en.wikipedia.org/wiki/Mersenne_Twister But only if you want uniform randomness, for many simulation purposes the distribution needs to be weighted according to some non-linear distribution. For example, when we wrote a lot of network simulators we used Erlang and Poisson distributions. And for pink noise simulations we used Gaussian distributions. You can of course produce those by filtering/weighting the output from a linear distribution but in either case you need to test the relative outputs at sampled slots along the range to ensure the output fits the curve. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From robertvstepp at gmail.com Sun Mar 20 00:12:13 2016 From: robertvstepp at gmail.com (boB Stepp) Date: Sat, 19 Mar 2016 23:12:13 -0500 Subject: [Tutor] How to test function using random.randint()? In-Reply-To: <20160319130356.GK8022@ando.pearwood.info> References: <85lh5fhxah.fsf@benfinney.id.au> <20160319130356.GK8022@ando.pearwood.info> Message-ID: On Sat, Mar 19, 2016 at 8:03 AM, Steven D'Aprano wrote: > On Sat, Mar 19, 2016 at 04:05:58PM +1100, Ben Finney wrote: > >> import random >> >> def roll_die(num_sides, rng=None): >> """ Return a result from a random die of `num_sides` sides. >> >> :param num_sides: The number of sides on the die. >> :param rng: An instance of `random.Random`, the random >> number generator to use. >> Default: the `random.random` instance. >> :return: The integer result from the die roll. >> >> The die is defined to have equal-probability faces, numbered >> from 1 to `num_sides`. >> >> """ >> if rng is None: >> rng = random.random > > Typo: you want rng = random.randint. I am thinking that Ben meant: rng = random.Random(). This would then make sense in light of the test cases he sets up later. > >> result = rng.randint(1, num_sides) > > And here you just want result = rng(1, num_sides). Otherwise you're > trying to call random.randint.randint. And then this statement would be correct as Ben wrote it. Ben, please chime in if I have got it wrong. boB From sjeik_appie at hotmail.com Sun Mar 20 09:15:52 2016 From: sjeik_appie at hotmail.com (Albert-Jan Roskam) Date: Sun, 20 Mar 2016 13:15:52 +0000 Subject: [Tutor] Changing the interpreter prompt symbol from ">>>" to ??? In-Reply-To: References: , <20160312050221.GA88471@cskk.homeip.net> , , , , Message-ID: < snip lots of useful info > Hi all, Thanks a lot for all your replies. I am whole lot wiser now :) Best wishes, Albert-Jan From ben+python at benfinney.id.au Sun Mar 20 09:18:01 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 21 Mar 2016 00:18:01 +1100 Subject: [Tutor] How to test function using random.randint()? References: <85lh5fhxah.fsf@benfinney.id.au> <20160319130356.GK8022@ando.pearwood.info> Message-ID: <858u1di8za.fsf@benfinney.id.au> boB Stepp writes: > On Sat, Mar 19, 2016 at 8:03 AM, Steven D'Aprano wrote: > > On Sat, Mar 19, 2016 at 04:05:58PM +1100, Ben Finney wrote: > >> if rng is None: > >> rng = random.random > > > > Typo: you want rng = random.randint. No, I meant what I wrote. The ?rng? parameter is expected to be bound to a RNG. If the caller has not specified a custom RNG instance, we bind ?rng? to the standard RNG instance found at ?random.random?. > >> result = rng.randint(1, num_sides) > > > > And here you just want result = rng(1, num_sides). Otherwise you're > > trying to call random.randint.randint. > > And then this statement would be correct as Ben wrote it. Unlike some other examples I have posted, I actually bothered to demonstrate this working as expected before posting it :-) > Ben, please chime in if I have got it wrong. You have it right, Bob. -- \ ?If consumers even know there's a DRM, what it is, and how it | `\ works, we've already failed.? ?Peter Lee, Disney corporation, | _o__) 2005 | Ben Finney From sjeik_appie at hotmail.com Sun Mar 20 09:53:04 2016 From: sjeik_appie at hotmail.com (Albert-Jan Roskam) Date: Sun, 20 Mar 2016 13:53:04 +0000 Subject: [Tutor] __str__ vs. sys.displayhook Message-ID: Hi, The other day I was playing with this to make a convenient string version of a named tuple: >>> from collections import namedtuple as nt >>> Record = nt("Record", "x y z") >>> Record.__str__ = lambda self: "| %s |" % " | ".join([item + ": " + str(getattr(self, item)) for item in self._fields]) >>> str(Record(1, 2, 3)) '| x: 1 | y: 2 | z: 3 |' Then, after reading another discussion on the main Python list (https://www.mail-archive.com/python-list at python.org/msg409771.html) I realized I could do the same thing with a displayhook. When would I (re)implement __str__, and when would I redefine sys.displayhook? Does the displayhook also affect the way things are logged (with the ' logging'? module)? It feels like sys.displayhook is more " heavy artillery",. but I might be wrong about that. Thanks in advance for your replies! Best wishes, Albert-Jan From steve at pearwood.info Sun Mar 20 10:58:53 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 21 Mar 2016 01:58:53 +1100 Subject: [Tutor] How to test function using random.randint()? In-Reply-To: <858u1di8za.fsf@benfinney.id.au> References: <85lh5fhxah.fsf@benfinney.id.au> <20160319130356.GK8022@ando.pearwood.info> <858u1di8za.fsf@benfinney.id.au> Message-ID: <20160320145853.GQ8022@ando.pearwood.info> On Mon, Mar 21, 2016 at 12:18:01AM +1100, Ben Finney wrote: > boB Stepp writes: > > > On Sat, Mar 19, 2016 at 8:03 AM, Steven D'Aprano wrote: > > > On Sat, Mar 19, 2016 at 04:05:58PM +1100, Ben Finney wrote: > > >> if rng is None: > > >> rng = random.random > > > > > > Typo: you want rng = random.randint. > > No, I meant what I wrote. The ?rng? parameter is expected to be bound to > a RNG. If the caller has not specified a custom RNG instance, we bind > ?rng? to the standard RNG instance found at ?random.random?. random.random is not a PRNG instance. It is a bound method: py> import random py> random.random > > >> result = rng.randint(1, num_sides) > > > > > > And here you just want result = rng(1, num_sides). Otherwise you're > > > trying to call random.randint.randint. > > > > And then this statement would be correct as Ben wrote it. > > Unlike some other examples I have posted, I actually bothered to > demonstrate this working as expected before posting it :-) Perhaps you might want to check again? py> rng = random.random py> rng.randint(1, 6) Traceback (most recent call last): File "", line 1, in AttributeError: 'builtin_function_or_method' object has no attribute 'randint' -- Steve From steve at pearwood.info Sun Mar 20 11:50:17 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 21 Mar 2016 02:50:17 +1100 Subject: [Tutor] __str__ vs. sys.displayhook In-Reply-To: References: Message-ID: <20160320155017.GR8022@ando.pearwood.info> On Sun, Mar 20, 2016 at 01:53:04PM +0000, Albert-Jan Roskam wrote: > Hi, > > The other day I was playing with this to make a convenient string version of a named tuple: > > >>> from collections import namedtuple as nt > >>> Record = nt("Record", "x y z") > >>> Record.__str__ = lambda self: "| %s |" % " | ".join([item + ": " + str(getattr(self, item)) for item in self._fields]) > >>> str(Record(1, 2, 3)) > '| x: 1 | y: 2 | z: 3 |' > > Then, after reading another discussion on the main Python list (https://www.mail-archive.com/python-list at python.org/msg409771.html) I realized I could do the same thing with a displayhook. > When would I (re)implement __str__, and when would I redefine sys.displayhook? Does the displayhook also affect the way things are logged (with the ' logging'? module)? It feels like sys.displayhook is more " heavy artillery",. but I might be wrong about that. As the documentation says, "sys.displayhook is called on the result of evaluating an expression entered in an interactive Python session." So the answer to your question is, you would redefine sys.displayhook when you want to control how objects are displayed in the interactive Python shell. https://docs.python.org/3/library/sys.html#sys.displayhook When you run a script, sys.displayhook is never called. It is only called when you are in interactive mode, typing at the Python prompt. When you assign a value to a variable: the_string = repr(some_expression) sys.displayhook is never called. sys.displayhook has nothing to do with the repr or str conversion, except in the sense that the display hook will probably *use* the value's repr or str. For instance, here's a rather silly display hook in action: py> def hook(value): ... if value is None: return ... sys.stdout.write("+++REDACTED+++\n") ... py> sys.displayhook = hook py> 23 + 1 +++REDACTED+++ py> 1000*2 +++REDACTED+++ py> "hello".upper() +++REDACTED+++ But even with this display hook in place, the repr and str of values are unchanged. It's just tricky to see them unless you bypass the hook: py> print(23 + 1) # print directly to the screen without calling hook 24 You will re-define __str__ when you want to control how objects are converted to strings using the str() function, and __repr__ for how objects are converted using the repr() function. The intention is that repr() returns the "string representation" of the object ("what does it look like?") while str() "converts this object to a string". They are usually the same, but not always: py> from fractions import Fraction py> x = Fraction(1, 2) py> print(str(x)) 1/2 py> print(repr(x)) Fraction(1, 2) -- Steve From sjeik_appie at hotmail.com Sun Mar 20 15:57:55 2016 From: sjeik_appie at hotmail.com (Albert-Jan Roskam) Date: Sun, 20 Mar 2016 19:57:55 +0000 Subject: [Tutor] __str__ vs. sys.displayhook In-Reply-To: <20160320155017.GR8022@ando.pearwood.info> References: , <20160320155017.GR8022@ando.pearwood.info> Message-ID: ---------------------------------------- > Date: Mon, 21 Mar 2016 02:50:17 +1100 > From: steve at pearwood.info > To: tutor at python.org > Subject: Re: [Tutor] __str__ vs. sys.displayhook > > On Sun, Mar 20, 2016 at 01:53:04PM +0000, Albert-Jan Roskam wrote: >> Hi, >> >> The other day I was playing with this to make a convenient string version of a named tuple: >> >>>>> from collections import namedtuple as nt >>>>> Record = nt("Record", "x y z") >>>>> Record.__str__ = lambda self: "| %s |" % " | ".join([item + ": " + str(getattr(self, item)) for item in self._fields]) >>>>> str(Record(1, 2, 3)) >> '| x: 1 | y: 2 | z: 3 |' >> >> Then, after reading another discussion on the main Python list (https://www.mail-archive.com/python-list at python.org/msg409771.html) I realized I could do the same thing with a displayhook. >> When would I (re)implement __str__, and when would I redefine sys.displayhook? Does the displayhook also affect the way things are logged (with the ' logging' module)? It feels like sys.displayhook is more " heavy artillery",. but I might be wrong about that. > > As the documentation says, "sys.displayhook is called on the result of > evaluating an expression entered in an interactive Python session." So > the answer to your question is, you would redefine sys.displayhook when > you want to control how objects are displayed in the interactive Python > shell. > > https://docs.python.org/3/library/sys.html#sys.displayhook > > When you run a script, sys.displayhook is never called. It is only > called when you are in interactive mode, typing at the Python prompt. It seems that ipython uses a displayhook in conjunction with pprint.pprint. Or at least something to that effect. That is *very* convenient, esp. with unordered objects like dictionaries. > When you assign a value to a variable: > > the_string = repr(some_expression) > > sys.displayhook is never called. > > sys.displayhook has nothing to do with the repr or str conversion, > except in the sense that the display hook will probably *use* the > value's repr or str. For instance, here's a rather silly display hook in > action: aha, so it's an implementation detail of the hook to often use str or repr. But not a requirement. > py> def hook(value): > ... if value is None: return > ... sys.stdout.write("+++REDACTED+++\n") > ... > py> sys.displayhook = hook > py> 23 + 1 > +++REDACTED+++ > py> 1000*2 > +++REDACTED+++ > py> "hello".upper() > +++REDACTED+++ > > But even with this display hook in place, the repr and str of values are > unchanged. It's just tricky to see them unless you bypass the hook: > > py> print(23 + 1) # print directly to the screen without calling hook > 24 > > You will re-define __str__ when you want to control how objects are > converted to strings using the str() function, and __repr__ for how > objects are converted using the repr() function. > > The intention is that repr() returns the "string representation" of the > object ("what does it look like?") while str() "converts this object to > a string". They are usually the same, but not always: > > py> from fractions import Fraction > py> x = Fraction(1, 2) > py> print(str(x)) > 1/2 > py> print(repr(x)) > Fraction(1, 2) That makes sense to me. I read somewhere [1, 2]) that __repr__, when implemented and when possible, should return an eval-able representation of the object (though this is not enforce/checked). Or as somebody put it: __str__ is about readability, and __repr__ is about eval-ability: eval(repr(obj)) == obj, e.g. >>> d = {1: 100000} >>> eval(repr(d)) == d True [1] https://docs.python.org/2/reference/datamodel.html#object.__repr__ [2] http://stackoverflow.com/questions/1436703/difference-between-str-and-repr-in-python From steve at pearwood.info Sun Mar 20 19:53:35 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 21 Mar 2016 10:53:35 +1100 Subject: [Tutor] __str__ vs. sys.displayhook In-Reply-To: References: <20160320155017.GR8022@ando.pearwood.info> Message-ID: <20160320235335.GS8022@ando.pearwood.info> On Sun, Mar 20, 2016 at 07:57:55PM +0000, Albert-Jan Roskam wrote: > > The intention is that repr() returns the "string representation" of the > > object ("what does it look like?") while str() "converts this object to > > a string". They are usually the same, but not always: > > > > py> from fractions import Fraction > > py> x = Fraction(1, 2) > > py> print(str(x)) > > 1/2 > > py> print(repr(x)) > > Fraction(1, 2) > > That makes sense to me. I read somewhere [1, 2]) that __repr__, when > implemented and when possible, should return an eval-able > representation of the object (though this is not enforce/checked). This is considered a "nice to have" feature of repr(), but it shouldn't be considered compulsory. It is mostly true for the more common built-ins such as None, ints, floats, strings, lists etc. It's *not* true for classes and functions, or anything using the default object repr: py> o = object() py> repr(o) '' > Or > as somebody put it: __str__ is about readability, and __repr__ is > about eval-ability: eval(repr(obj)) == obj, e.g. I'd be cautious about putting so much emphasis on the eval part, but it's broadly correct. For many objects, the two will be the same, and for some objects it is impractical or unnecessary to expect the eval(repr(obj)) thing to work. certainly wouldn't put it like that. __str__ is more about "convert to a string", and __repr__ is "what the the magic method that gets called by str(), and __repr__ gets called by repr() -- Steve From ben+python at benfinney.id.au Sun Mar 20 21:19:16 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 21 Mar 2016 12:19:16 +1100 Subject: [Tutor] How to test function using random.randint()? References: <85lh5fhxah.fsf@benfinney.id.au> <20160319130356.GK8022@ando.pearwood.info> <858u1di8za.fsf@benfinney.id.au> <20160320145853.GQ8022@ando.pearwood.info> Message-ID: <85zitshbl7.fsf@benfinney.id.au> Steven D'Aprano writes: > On Mon, Mar 21, 2016 at 12:18:01AM +1100, Ben Finney wrote: > > No, I meant what I wrote. The ?rng? parameter is expected to be > > bound to a RNG. If the caller has not specified a custom RNG > > instance, we bind ?rng? to the standard RNG instance found at > > ?random.random?. Steven is right, that name is a function not an RNG. The code should read:: if rng is None: rng = random._inst which is the default RNG instance in the module. It is also named as an implementation-only attribute, not part of the module's API. So you may want to find a more reliable API to use. -- \ ?Very few things happen at the right time, and the rest do not | `\ happen at all. The conscientious historian will correct these | _o__) defects.? ?Mark Twain, _A Horse's Tale_ | Ben Finney From robertvstepp at gmail.com Sun Mar 20 21:29:38 2016 From: robertvstepp at gmail.com (boB Stepp) Date: Sun, 20 Mar 2016 20:29:38 -0500 Subject: [Tutor] How to test function using random.randint()? In-Reply-To: <85zitshbl7.fsf@benfinney.id.au> References: <85lh5fhxah.fsf@benfinney.id.au> <20160319130356.GK8022@ando.pearwood.info> <858u1di8za.fsf@benfinney.id.au> <20160320145853.GQ8022@ando.pearwood.info> <85zitshbl7.fsf@benfinney.id.au> Message-ID: On Sun, Mar 20, 2016 at 8:19 PM, Ben Finney wrote: > > Steven D'Aprano writes: > > > On Mon, Mar 21, 2016 at 12:18:01AM +1100, Ben Finney wrote: > > > No, I meant what I wrote. The ?rng? parameter is expected to be > > > bound to a RNG. If the caller has not specified a custom RNG > > > instance, we bind ?rng? to the standard RNG instance found at > > > ?random.random?. > > Steven is right, that name is a function not an RNG. > > The code should read:: > > if rng is None: > rng = random._inst > > which is the default RNG instance in the module. Can I not use: if rng is None: rng = random.Random() ? When I tested it int the interpreter to see if I could use randint: py3: rng = random.Random() py3: rng.randint(1, 6) 4 Am I missing something basic here? boB From ben+python at benfinney.id.au Sun Mar 20 21:44:14 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 21 Mar 2016 12:44:14 +1100 Subject: [Tutor] How to test function using random.randint()? References: <85lh5fhxah.fsf@benfinney.id.au> <20160319130356.GK8022@ando.pearwood.info> <858u1di8za.fsf@benfinney.id.au> <20160320145853.GQ8022@ando.pearwood.info> <85zitshbl7.fsf@benfinney.id.au> Message-ID: <85lh5chafl.fsf@benfinney.id.au> boB Stepp writes: > On Sun, Mar 20, 2016 at 8:19 PM, Ben Finney wrote: > > if rng is None: > > rng = random._inst > > > > which is the default RNG instance in the module. > > Can I not use: > > if rng is None: > rng = random.Random() That will work. It unfortunately creates a new random.Random instance every time that line is executed, making the function waste a lot of time. So instead, you many want to create a module-level instance, and refer to that as the default. # die_roller.py """ Functionality for rolling numbers from polyhedral dice. """ import random rng = random.Random() def roll_die(num_sides, rng=rng): # ? -- \ ?Give a man a fish, and you'll feed him for a day; give him a | `\ religion, and he'll starve to death while praying for a fish.? | _o__) ?Anonymous | Ben Finney From robertvstepp at gmail.com Sun Mar 20 22:18:43 2016 From: robertvstepp at gmail.com (boB Stepp) Date: Sun, 20 Mar 2016 21:18:43 -0500 Subject: [Tutor] How to test function using random.randint()? In-Reply-To: <85lh5chafl.fsf@benfinney.id.au> References: <85lh5fhxah.fsf@benfinney.id.au> <20160319130356.GK8022@ando.pearwood.info> <858u1di8za.fsf@benfinney.id.au> <20160320145853.GQ8022@ando.pearwood.info> <85zitshbl7.fsf@benfinney.id.au> <85lh5chafl.fsf@benfinney.id.au> Message-ID: On Sun, Mar 20, 2016 at 8:44 PM, Ben Finney wrote: > boB Stepp writes: >> Can I not use: >> >> if rng is None: >> rng = random.Random() > > That will work. > > It unfortunately creates a new random.Random instance every time that > line is executed, making the function waste a lot of time. Ah, I should have thought of that. Thanks! > So instead, you many want to create a module-level instance, and refer > to that as the default. I actually like this better anyway. At the moment I am focused on randint, but later on I am certain I will be other methods of the random module as this "fun" project develops. boB From anshu.kumar726 at gmail.com Tue Mar 22 01:52:57 2016 From: anshu.kumar726 at gmail.com (Anshu Kumar) Date: Tue, 22 Mar 2016 11:22:57 +0530 Subject: [Tutor] install python without root access Message-ID: Hi, I have a Centos06 based machine and I don't have root access. The default Python (GCC compiler based) is quite old 2.7.5 , so I need to update it. I tried installing in local folder where i have access. I am facing deep troubles installing 1. as i try to run ./configure i face configure: error: no acceptable C compiler found in $PATH. I tried to install gcc but its installation also require some c compiler which is not seem to be present. I can't even do yum install gcc without root access. 2. I tried it on another machine where atleast I had gcc compiler but here after make install i can invoke latest python by running ./python-2.7.11, i am wondering how can i suppress default python without using virtual env. Though this is not so serious as the first problem but still i would like to know the way. Could I please be helped? Thanks and Regards, Anshu From thesupervisar at gmail.com Tue Mar 22 05:12:18 2016 From: thesupervisar at gmail.com (Lucas Cavalcante) Date: Tue, 22 Mar 2016 09:12:18 +0000 Subject: [Tutor] Help with recursion Message-ID: Hello, I'm new to both Python and such a mailling list. I'm not sure how it works (if it does). I would really appreciate if anyone could help me with a small piece of code I'm implementing in order to learn some recursion. Cheers, Beterraba From steve at pearwood.info Tue Mar 22 08:27:29 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 22 Mar 2016 23:27:29 +1100 Subject: [Tutor] Help with recursion In-Reply-To: References: Message-ID: <20160322122728.GE12526@ando.pearwood.info> On Tue, Mar 22, 2016 at 09:12:18AM +0000, Lucas Cavalcante wrote: > Hello, I'm new to both Python and such a mailling list. > I'm not sure how it works (if it does). > I would really appreciate if anyone could help me with a small piece of > code I'm implementing in order to learn some recursion. Sure. Show us your code and ask your question. -- Steve From joel.goldstick at gmail.com Tue Mar 22 08:53:55 2016 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 22 Mar 2016 08:53:55 -0400 Subject: [Tutor] Help with recursion In-Reply-To: <20160322122728.GE12526@ando.pearwood.info> References: <20160322122728.GE12526@ando.pearwood.info> Message-ID: On Tue, Mar 22, 2016 at 8:27 AM, Steven D'Aprano wrote: > On Tue, Mar 22, 2016 at 09:12:18AM +0000, Lucas Cavalcante wrote: > > Hello, I'm new to both Python and such a mailling list. > > I'm not sure how it works (if it does). > > I would really appreciate if anyone could help me with a small piece of > > code I'm implementing in order to learn some recursion. > > Sure. Show us your code and ask your question. > > > > -- > Steve > ..or ... google python recursion -- lots of tutorials. If you get stuck, as Steven posted, show some code, and ask a question > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick http://joelgoldstick.com/ http://cc-baseballstats.info/ From martin at linux-ip.net Tue Mar 22 10:27:48 2016 From: martin at linux-ip.net (Martin A. Brown) Date: Tue, 22 Mar 2016 07:27:48 -0700 Subject: [Tutor] Help with recursion In-Reply-To: References: Message-ID: Greetings and welcome Lucas (Beterraba), >Hello, I'm new to both Python and such a mailling list. >I'm not sure how it works (if it does). First, welcome to Python! We hope you like Python and are happy to help you figure out how to get started. The mailing list etiquette is like most mailing lists (be polite, be clear, do not top post). This is an English language mailing list. In addition on this mailing list, we ask people to: * report operating system and Python version they are using * copy/paste the code under question (and/or any errors) * include a question (like for example "I expected X to happen, but Y happened instead. Why?") >I would really appreciate if anyone could help me with a small piece of >code I'm implementing in order to learn some recursion. Recursion is a wonderful technique. One of the classic computer science examples demonstrating recursion (and the limits of recursion) is a function implementing the Fibonacci sequence. https://technobeans.wordpress.com/2012/04/16/5-ways-of-fibonacci-in-python/ But, if you have a more specific question about recursion, then please send it along. Welcome to the world of Python! -Martin -- Martin A. Brown http://linux-ip.net/ From alan.gauld at btinternet.com Tue Mar 22 19:11:55 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 22 Mar 2016 23:11:55 +0000 Subject: [Tutor] install python without root access In-Reply-To: References: Message-ID: On 22/03/16 05:52, Anshu Kumar wrote: > I have a Centos06 based machine and I don't have root access. The default > Python (GCC compiler based) is quite old 2.7.5 , so I need to update it. My first pint would be that 2.7.5 is not that old. Unless you have a very specific feature that you need in 2.7.11 you probably don't need to bother upgrading it. The "Whats New" file is here and covers everything back to 2.7.5. https://hg.python.org/cpython/raw-file/53d30ab403f1/Misc/NEWS > I am facing deep troubles installing Assuming you do need to install it can you use an rpm package (ISTR CentOS uses rpm format?) There are several listed here: https://www.rpmfind.net/linux/rpm2html/search.php?query=python > 1. as i try to run ./configure i face configure: error: no acceptable C > compiler found in $PATH. I tried to install gcc but its installation also > require some c compiler which is not seem to be present. I can't even do > yum install gcc without root access. That seems odd. I've never used CentOS but I can't think why they wouldn't allow gcc to install for a normal user. Most Linux distros come with gcc already there. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From Joaquin.Alzola at lebara.com Tue Mar 22 07:43:14 2016 From: Joaquin.Alzola at lebara.com (Joaquin Alzola) Date: Tue, 22 Mar 2016 11:43:14 +0000 Subject: [Tutor] install python without root access In-Reply-To: References: Message-ID: The easiest way will be to get in contact with the SysAdmin and tell him why you need python upgrade. He can allocate both version for you. -----Original Message----- From: Tutor [mailto:tutor-bounces+joaquin.alzola=lebara.com at python.org] On Behalf Of Anshu Kumar Sent: 22 March 2016 05:53 To: tutor at python.org Subject: [Tutor] install python without root access Hi, I have a Centos06 based machine and I don't have root access. The default Python (GCC compiler based) is quite old 2.7.5 , so I need to update it. I tried installing in local folder where i have access. I am facing deep troubles installing 1. as i try to run ./configure i face configure: error: no acceptable C compiler found in $PATH. I tried to install gcc but its installation also require some c compiler which is not seem to be present. I can't even do yum install gcc without root access. 2. I tried it on another machine where atleast I had gcc compiler but here after make install i can invoke latest python by running ./python-2.7.11, i am wondering how can i suppress default python without using virtual env. Though this is not so serious as the first problem but still i would like to know the way. Could I please be helped? Thanks and Regards, Anshu _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor This email is confidential and may be subject to privilege. If you are not the intended recipient, please do not copy or disclose its content but contact the sender immediately upon receipt. From akleider at sonic.net Wed Mar 23 20:45:24 2016 From: akleider at sonic.net (Alex Kleider) Date: Wed, 23 Mar 2016 17:45:24 -0700 Subject: [Tutor] Object-Oriented Analysis by Peter Coad & Edward Yourdon Message-ID: <2ce8befcd60e15dbb6f6cddd1718da16@sonic.net> The above cited book was mentioned in a recent thread (by Alan I think.) I acquired the book but it isn't at all what I expected and I've no use for it. If he or anyone else would like it, I'm happy to send it along. Just let me know an address[1] to which to send it. Cheers, Alex [1] I'm happy to pay for postage for US and could also send to GB (a friend is visiting and could carry it back and mail locally.) Else where might be more expensive than it's worth. From alan.gauld at btinternet.com Wed Mar 23 21:36:14 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 24 Mar 2016 01:36:14 +0000 Subject: [Tutor] Object-Oriented Analysis by Peter Coad & Edward Yourdon In-Reply-To: <2ce8befcd60e15dbb6f6cddd1718da16@sonic.net> References: <2ce8befcd60e15dbb6f6cddd1718da16@sonic.net> Message-ID: On 24/03/16 00:45, Alex Kleider wrote: > The above cited book was mentioned in a recent thread (by Alan I think.) > I acquired the book but it isn't at all what I expected and I've no use > for it. Yep, it was me. I'm interested in what you found amiss? I confess I still find it one of the best intros to developing real world OOP based systems. I've used the technique on several projects ranging from 4 man-day to 10 man-year scale in teams ranging from me-alone to 8 programmers. (For anything bigger I'd go to UML/RUP style modelling) But no, I don't need another copy :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From starfas_s at yahoo.com Thu Mar 24 17:03:51 2016 From: starfas_s at yahoo.com (Sam Starfas) Date: Thu, 24 Mar 2016 21:03:51 +0000 (UTC) Subject: [Tutor] Removing Content from Lines.... References: <1171436017.5032840.1458853431034.JavaMail.yahoo.ref@mail.yahoo.com> Message-ID: <1171436017.5032840.1458853431034.JavaMail.yahoo@mail.yahoo.com> Hello,I am hoping you experts can help out a newbie.I have written some python code to gather a bunch of sentences from many files. These sentences contain the content: blah blah blah blah 1-up printingblah blah blah blah blah blah blah blah blah blah Presetblah blah blah blah blah blah blah Preset blah blah blah What I want to do is remove the words before the and after the .?How do I do that in Python?? Thanks for any and all help.Sam From tomjmaher4 at gmail.com Thu Mar 24 14:12:28 2016 From: tomjmaher4 at gmail.com (Tom Maher) Date: Thu, 24 Mar 2016 13:12:28 -0500 Subject: [Tutor] Simple game Message-ID: Here is a simple game I am trying to create: print "pick a number between 0 and 100 and tell me if it my guess is too high (h) too low (l) or correct (c)" guess = 0 print 'my guess is 50' raw_input('your input ') n = 50 while raw_input != 'c' or 'h' or 'l': if raw_input == 'h': guess += 1 n -= (n/2) elif raw_input == "l": guess += 1 n += (n/2) elif raw_input == 'c': print "It took " + str(guess) + "guesses" break if raw_input is not 'c' or 'h' or 'l': print "please input either a c, h, or l" elif print "game over" I think its pretty obvious what I'm trying to do here - make a game that will guess your number between 0 and 100 using a bisection search. I know I made some embarrassingly obvious mistakes in the math up there but I can worry about that later. This is after a couple of attempts and so far my code basically stops after the raw input prompt. No matter what I input it doesn't respond. I originally tried to equate raw_input to x as a marker but thought that maybe that changed the raw_input to be read AS x in the code even after input. So instead I entered raw_input in every section to represent the inputted value. Still stops at the prompt. Not sure if it is something obvious or if it is something I'm oblivious to or what. Any help is appreciated! Thanks a lot, Tom From alan.gauld at btinternet.com Thu Mar 24 21:12:41 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 25 Mar 2016 01:12:41 +0000 Subject: [Tutor] Removing Content from Lines.... In-Reply-To: <1171436017.5032840.1458853431034.JavaMail.yahoo@mail.yahoo.com> References: <1171436017.5032840.1458853431034.JavaMail.yahoo.ref@mail.yahoo.com> <1171436017.5032840.1458853431034.JavaMail.yahoo@mail.yahoo.com> Message-ID: On 24/03/16 21:03, Sam Starfas via Tutor wrote: > I have written some python code to gather a bunch > of sentences from many files. > These sentences contain the content: OK, They are presumably lines and not sentences. Lines end in a newline character and sentences end with a period. So they are fundamentally different and need to be handled differently so you need to be precise. > blah blah blah blah 1-up printingblah blah blah blah blah blah blah blah > blah blah Presetblah blah blah blah Also they look like they might be out of an XML or HTML file? In that case the easiest way is probably to use a parser for the original data type (etree for XML, Beautiful Soup for HTML, for examples) That's much easier than trying to do it by yourself. That may involve going back a step and not extracting the lines out first... If its not a recognised format like XML then you may need to do it manually and in that case if the formatting is as precise as you show(no extra spaces etc) then you can simply use string methods to locate the end of the tags. opentag = '' endtag='' start = my_string.find(openTag) + len(openTag) find() will return the position of the opening <. You can then add the length of the tag to get the start of your wanted text. Similarly end = my_string.find(endtag) locates the start of the end tag. You can then use string slicing to get the bit in betweeen. data = my_string[start:end] If the tags are not as clean then you might need to use regular expressions to do it and that's a whole new level of complexity. Things you need to be clear about: 1) are there any irregularities in how the tags are spelled? (eg. spaces, caps etc) 2) do the tags ever have attributes? 3) can there be multiple tags in a single line/sentence? 4) can tags be nested? 5) can tags cross line/sentence boundaries? Without more detail that's the best I can offer. hth -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Thu Mar 24 21:26:45 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 25 Mar 2016 01:26:45 +0000 Subject: [Tutor] Simple game In-Reply-To: References: Message-ID: On 24/03/16 18:12, Tom Maher wrote: > raw_input('your input ') Raw input returns a value, you need to store it somewhere like: value = raw_input('your input ') > while raw_input != 'c' or 'h' or 'l': Then you need to compare vale not the function name. (Did you learn BASIC at some point maybe?) You need to read/think like the computer not like a human. Python sees that while like while value != ('c' or 'h' or 'l'): In other words it evaluates 'c' or 'h' or 'l' first and that will always be True. It then compares your input value to True and if you entered any kind of value (not an empty string) then value will be True and your while will never run. (I'm pretty sure the != is wrong too, you really want ==) A better way to code this specific kind of test is to use the in operator: while value in ('c','h','l'): > if raw_input == 'h': > guess += 1 > n -= (n/2) Again you need to use value if value == 'h':.... Finally you need to print the new value of the computers guess inside the loop or the user can never tell which way to go. You then need to read a new command inside the loop too. So it should probably look something like: initialise values here while True: print "My guess: , n value = raw_input.... if value not in ('h','c','l'): print "must enter hl or c" continue if value == 'h':... elif value == 'l'... else: print 'success in ' , guess, 'guesses' break All untested so you will need to tweak it a bit. But hopefully it points you in the right direction. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From martin at linux-ip.net Thu Mar 24 21:59:57 2016 From: martin at linux-ip.net (Martin A. Brown) Date: Thu, 24 Mar 2016 18:59:57 -0700 Subject: [Tutor] Removing Content from Lines.... In-Reply-To: <1171436017.5032840.1458853431034.JavaMail.yahoo@mail.yahoo.com> References: <1171436017.5032840.1458853431034.JavaMail.yahoo.ref@mail.yahoo.com> <1171436017.5032840.1458853431034.JavaMail.yahoo@mail.yahoo.com> Message-ID: Greetings Sam, >Hello,I am hoping you experts can help out a newbie.I have written >some python code to gather a bunch of sentences from many files. >These sentences contain the content: > >blah blah blah blah 1-up printingblah blah blah blah blah blah blah blah >blah blah Presetblah blah blah blah >blah blah blah Preset blah blah blah > >What I want to do is remove the words before the and >after the .?How do I do that in Python?? Thanks for any >and all help. That looks like DocBook markup to me. If you actually wish only to mangle the strings, you can do the following: def show_just_uicontrol_elements(fin): for line in fin: s = line.index('') e = line.index('') + len('') print(line[s:e]) (Given your question, I'm assuming you can figure out how to open a file and read line by line in Python.) If it's XML, though, you might consider more carefully Alan's admonitions and his suggestion of lxml, as a bit of a safer choice for handling XML data. def listtags(filename, tag=None): if tag is None: sys.exit("Provide a tag name to this function, e.g. uicontrol") doc = lxml.etree.parse(filename) sought = list(doc.getroot().iter(tag)) for element in sought: print(element.tag, element.text) If you were to call the above with: listtags('/path/to/the/data/file.xml', 'uicontrol') You should see the name 'uicontrol' and the contents of each tag, stripped of all surrounding context. The above snippet is really just an example to show you how easy it is (from a coding perspective) to use lxml. You still have to make the investment to understand how lxml processes XML and what your data processing needs are. Good luck in your explorations, -Martin -- Martin A. Brown http://linux-ip.net/ From __peter__ at web.de Fri Mar 25 04:30:51 2016 From: __peter__ at web.de (Peter Otten) Date: Fri, 25 Mar 2016 09:30:51 +0100 Subject: [Tutor] Removing Content from Lines.... References: <1171436017.5032840.1458853431034.JavaMail.yahoo.ref@mail.yahoo.com> <1171436017.5032840.1458853431034.JavaMail.yahoo@mail.yahoo.com> Message-ID: Martin A. Brown wrote: > > Greetings Sam, > >>Hello,I am hoping you experts can help out a newbie.I have written >>some python code to gather a bunch of sentences from many files. >>These sentences contain the content: >> >>blah blah blah blah 1-up printingblah blah blah >>blah blah blah blah blah blah blah Presetblah blah >>blah blah blah blah blah Preset blah blah blah >> >>What I want to do is remove the words before the and >>after the . How do I do that in Python? Thanks for any >>and all help. > > That looks like DocBook markup to me. > > If you actually wish only to mangle the strings, you can do the > following: > > def show_just_uicontrol_elements(fin): > for line in fin: > s = line.index('') > e = line.index('') + len('') > print(line[s:e]) > > (Given your question, I'm assuming you can figure out how to open a > file and read line by line in Python.) > > If it's XML, though, you might consider more carefully Alan's > admonitions and his suggestion of lxml, as a bit of a safer choice > for handling XML data. > > def listtags(filename, tag=None): > if tag is None: > sys.exit("Provide a tag name to this function, e.g. uicontrol") > doc = lxml.etree.parse(filename) > sought = list(doc.getroot().iter(tag)) > for element in sought: > print(element.tag, element.text) > > If you were to call the above with: > > listtags('/path/to/the/data/file.xml', 'uicontrol') > > You should see the name 'uicontrol' and the contents of each tag, > stripped of all surrounding context. > > The above snippet is really just an example to show you how easy it > is (from a coding perspective) to use lxml. You still have to make > the investment to understand how lxml processes XML and what your > data processing needs are. > > Good luck in your explorations, Another approach that uses XPath, also provided by lxml: $ cat tmp.xml blah blah blah blah 1-up printingblah blah blah blah blah blah blah blah blah blah Presetblah blah blah blah blah blah blah Preset blah blah blah $ python3 [...] >>> from lxml import etree >>> root = etree.parse("tmp.xml") >>> root.xpath("//uicontrol/text()") ['1-up printing', 'Preset', 'Preset'] https://en.wikipedia.org/wiki/XPath From sinasareth at yahoo.com Thu Mar 24 21:24:04 2016 From: sinasareth at yahoo.com (sina sareth) Date: Fri, 25 Mar 2016 01:24:04 +0000 (UTC) Subject: [Tutor] Removing Content from Lines.... In-Reply-To: <1171436017.5032840.1458853431034.JavaMail.yahoo@mail.yahoo.com> References: <1171436017.5032840.1458853431034.JavaMail.yahoo@mail.yahoo.com> Message-ID: <144800901.5069607.1458869044035.JavaMail.yahoo@mail.yahoo.com> I wonder if somebody may give some clues to write this method. Use Django to build a view where you can download all Quotes in CSV form.? Thanks On Thursday, March 24, 2016 5:55 PM, Sam Starfas via Tutor wrote: Hello,I am hoping you experts can help out a newbie.I have written some python code to gather a bunch of sentences from many files. These sentences contain the content: blah blah blah blah 1-up printingblah blah blah blah blah blah blah blah blah blah Presetblah blah blah blah blah blah blah Preset blah blah blah What I want to do is remove the words before the and after the .?How do I do that in Python?? Thanks for any and all help.Sam _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Fri Mar 25 12:10:15 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 25 Mar 2016 16:10:15 +0000 Subject: [Tutor] Removing Content from Lines.... In-Reply-To: <144800901.5069607.1458869044035.JavaMail.yahoo@mail.yahoo.com> References: <1171436017.5032840.1458853431034.JavaMail.yahoo@mail.yahoo.com> <144800901.5069607.1458869044035.JavaMail.yahoo@mail.yahoo.com> Message-ID: On 25/03/16 01:24, sina sareth via Tutor wrote: > I wonder if somebody may give some clues to write this method. > Use Django to build a view where you can download all Quotes in CSV form. Please don;t hijack another thread. Use a new post for a new question. Its not clear what you mean by Quotes. Also, Django is not really part of this group's remit, you will probably get a better answer on the Django support forum. They are quite friendly. But you should think about how to explain your question more clearly. Also mention any restrictions such as OS and Python/Django version you are using. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From nitinchandra1 at gmail.com Fri Mar 25 14:34:48 2016 From: nitinchandra1 at gmail.com (nitin chandra) Date: Sat, 26 Mar 2016 00:04:48 +0530 Subject: [Tutor] python smtplib 'Message denied - From address spoofing attempt detected via SMTP Message-ID: Hi All, I am trying to script a confirmation mail on submission of a form. Till now the form submission and summery page is working. BUT the following 'section' is not working. -- This is a python(CGI) script -- hosted on a shared server on hostgator.in -- This is giving "250 Spoofing error ....", below copy/pasted error log of apache with respect to my website *************** script **************** import smtplib ######### Sending Registration Confirmation Mail ####### fromJSSHS = 'no-reply at jsshs.org' toJSSHS = [(str(email)), ' ******@chandrainformatics.com'] SubjectJssHs = "Registration confirmation with JSSHS" TextJsshs = """ ApplicationID : jssh%s FirstNAME : %s LastNAME : %s Gender : %s DoB : %s Age : %s Category : %s Post : %s Phone M : %s Phone LL : %s Email : %s Submission DT : %s Submission Time : %s Also get your original certificates. """ % (str(applicationIDlst),str(nameDBlst),str(lnameDBlst),str(genderDBlst),str(dob_DBlst),str(ageDBlst),str(categoryDBlst),str(postDBlst),str(phmDBlst),str(phllDBlst),str(emailDBlst),datetime.datetime.strptime(str(submissionDate_DBlst2),'%Y-%m-%d').strftime('%d/%m/%Y'),str(submissionTime_DBlst)) messageJSSHS = """ >From : %s To : %s Subject : %s %s """ % (fromJSSHS,",".join(toJSSHS), SubjectJssHs, TextJsshs) server = smtplib.SMTP('mail.jsshs.org', 25) server.set_debuglevel(1) server.ehlo() server.starttls() server.ehlo() server.login(fromJSSHS, '******') server.sendmail(fromJSSHS, toJSSHS, messageJSSHS) server.quit() ##### ERROR BELOW #### [Wed Mar 23 17:14:48 2016] [error] [client 182.68.165.86] Premature end of script headers: application.cgi, referer: http://jsshs.org/application.html [Wed Mar 23 17:14:48 2016] [error] [client 182.68.165.86] File does not exist: /home/jsshsbtl/public_html/500.shtml, referer: http://jsshs.org/application.html send: 'mail FROM: size=474\r\n' send: "\r\nFrom : no-reply at jsshs.org\r\nTo : ['drashokkr007 at yahoo.com', 'nitin at chandrainformatics.com']\r\nSubject : Registration confirmation with JSSHS\r\n\r\n\r\nApplicationID : jsshs28\r\nFirstNAME : mukesh\r\nLastNAME : kumar\r\nGender : male\r\nDoB : 15/09/1982\r\nAge : 34\r\nCategory : scst\r\nPost : paramedical\r\nPhone M : 9872342266\r\nPhone LL : 01124893479\r\nEmail : drashokkr007 at yahoo.com\r\nSubmission DT : 23/03/2016\r\nSubmission Time : 05:38PM\r\n\r\n.\r\n" reply: '250 Message denied - From address spoofing attempt detected via SMTP ( From address: IP: 111.118.215.222 AuthenticatedID: no-reply at jsshs.org Protocol: esmtpa)\r\n' reply: retcode (250); Msg: Message denied - From address spoofing attempt detected via SMTP ( From address: IP: 111.118.215.222 AuthenticatedID: no-reply at jsshs.org Protocol: esmtpa) data: (250, 'Message denied - >From address spoofing attempt detected via SMTP ( From address: IP: 111.118.215.222 AuthenticatedID: no-reply at jsshs.org Protocol: esmtpa)') Thanks Nitin From joel.goldstick at gmail.com Fri Mar 25 14:54:02 2016 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 25 Mar 2016 14:54:02 -0400 Subject: [Tutor] python smtplib 'Message denied - From address spoofing attempt detected via SMTP In-Reply-To: References: Message-ID: On Fri, Mar 25, 2016 at 2:34 PM, nitin chandra wrote: > Hi All, > > I am trying to script a confirmation mail on submission of a form. > > Till now the form submission and summery page is working. > > BUT the following 'section' is not working. > -- This is a python(CGI) script > -- hosted on a shared server on hostgator.in > > -- This is giving "250 Spoofing error ....", below copy/pasted error > log of apache with respect to my website > > *************** script **************** > import smtplib > > ######### Sending Registration Confirmation Mail ####### > fromJSSHS = 'no-reply at jsshs.org' > toJSSHS = [(str(email)), ' ******@chandrainformatics.com'] > > SubjectJssHs = "Registration confirmation with JSSHS" > > TextJsshs = """ > ApplicationID : jssh%s > FirstNAME : %s > LastNAME : %s > Gender : %s > DoB : %s > Age : %s > Category : %s > Post : %s > Phone M : %s > Phone LL : %s > Email : %s > Submission DT : %s > Submission Time : %s > > Also get your original certificates. > """ % > (str(applicationIDlst),str(nameDBlst),str(lnameDBlst),str(genderDBlst),str(dob_DBlst),str(ageDBlst),str(categoryDBlst),str(postDBlst),str(phmDBlst),str(phllDBlst),str(emailDBlst),datetime.datetime.strptime(str(submissionDate_DBlst2),'%Y-%m-%d').strftime('%d/%m/%Y'),str(submissionTime_DBlst)) > > messageJSSHS = """ > From : %s > To : %s > Subject : %s > > %s > > """ % (fromJSSHS,",".join(toJSSHS), SubjectJssHs, TextJsshs) > > server = smtplib.SMTP('mail.jsshs.org', 25) > server.set_debuglevel(1) > server.ehlo() > server.starttls() > server.ehlo() > server.login(fromJSSHS, '******') > server.sendmail(fromJSSHS, toJSSHS, messageJSSHS) > server.quit() > > > ##### ERROR BELOW #### > > [Wed Mar 23 17:14:48 2016] [error] [client 182.68.165.86] Premature > end of script headers: application.cgi, referer: > http://jsshs.org/application.html [Wed Mar 23 17:14:48 2016] [error] > [client 182.68.165.86] File does not exist: > /home/jsshsbtl/public_html/500.shtml, referer: > http://jsshs.org/application.html send: 'mail > FROM: size=474\r\n' send: "\r\nFrom : > no-reply at jsshs.org\r\nTo : ['drashokkr007 at yahoo.com', > 'nitin at chandrainformatics.com']\r\nSubject : Registration confirmation > with JSSHS\r\n\r\n\r\nApplicationID : jsshs28\r\nFirstNAME : > mukesh\r\nLastNAME : kumar\r\nGender : male\r\nDoB : 15/09/1982\r\nAge > : 34\r\nCategory : scst\r\nPost : paramedical\r\nPhone M : > 9872342266\r\nPhone LL : 01124893479\r\nEmail : > drashokkr007 at yahoo.com\r\nSubmission DT : 23/03/2016\r\nSubmission > Time : 05:38PM\r\n\r\n.\r\n" reply: '250 Message denied - From address > spoofing attempt detected via SMTP ( From address: IP: 111.118.215.222 > AuthenticatedID: no-reply at jsshs.org Protocol: esmtpa)\r\n' reply: > retcode (250); Msg: Message denied - From address spoofing attempt > detected via SMTP ( From address: IP: 111.118.215.222 AuthenticatedID: > no-reply at jsshs.org Protocol: esmtpa) data: (250, 'Message denied - > From address spoofing attempt detected via SMTP ( From address: IP: > 111.118.215.222 AuthenticatedID: no-reply at jsshs.org Protocol: > esmtpa)') > > > Thanks > > Nitin > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > According to this page: http://www.answersthatwork.com/Download_Area/ATW_Library/Networking/Network__3-SMTP_Server_Status_Codes_and_SMTP_Error_Codes.pdf You have succeeded in sending your message. Does the message get sent? -- Joel Goldstick http://joelgoldstick.com/ http://cc-baseballstats.info/ From nitinchandra1 at gmail.com Fri Mar 25 16:42:37 2016 From: nitinchandra1 at gmail.com (nitin chandra) Date: Sat, 26 Mar 2016 02:12:37 +0530 Subject: [Tutor] python smtplib 'Message denied - From address spoofing attempt detected via SMTP In-Reply-To: References: Message-ID: No. I dont get one copy of the information filled in the form, as programmed in the script. reply: '250 Message denied - From address spoofing attempt detected via SMTP ( From address: IP: 111.118.215.222 AuthenticatedID: no-reply at jsshs.org Protocol: esmtpa)\r\n' As suggested by SysAdmin from service provider, From header needs to be looked into. Haven't found any solution, mostly all suggested scripts are similar. On 26 March 2016 at 00:24, Joel Goldstick wrote: > > > On Fri, Mar 25, 2016 at 2:34 PM, nitin chandra > wrote: >> >> Hi All, >> >> I am trying to script a confirmation mail on submission of a form. >> >> Till now the form submission and summery page is working. >> >> BUT the following 'section' is not working. >> -- This is a python(CGI) script >> -- hosted on a shared server on hostgator.in >> >> -- This is giving "250 Spoofing error ....", below copy/pasted error >> log of apache with respect to my website >> >> *************** script **************** >> import smtplib >> >> ######### Sending Registration Confirmation Mail ####### >> fromJSSHS = 'no-reply at jsshs.org' >> toJSSHS = [(str(email)), ' ******@chandrainformatics.com'] >> >> SubjectJssHs = "Registration confirmation with JSSHS" >> >> TextJsshs = """ >> ApplicationID : jssh%s >> FirstNAME : %s >> LastNAME : %s >> Gender : %s >> DoB : %s >> Age : %s >> Category : %s >> Post : %s >> Phone M : %s >> Phone LL : %s >> Email : %s >> Submission DT : %s >> Submission Time : %s >> >> Also get your original certificates. >> """ % >> (str(applicationIDlst),str(nameDBlst),str(lnameDBlst),str(genderDBlst),str(dob_DBlst),str(ageDBlst),str(categoryDBlst),str(postDBlst),str(phmDBlst),str(phllDBlst),str(emailDBlst),datetime.datetime.strptime(str(submissionDate_DBlst2),'%Y-%m-%d').strftime('%d/%m/%Y'),str(submissionTime_DBlst)) >> >> messageJSSHS = """ >> From : %s >> To : %s >> Subject : %s >> >> %s >> >> """ % (fromJSSHS,",".join(toJSSHS), SubjectJssHs, TextJsshs) >> >> server = smtplib.SMTP('mail.jsshs.org', 25) >> server.set_debuglevel(1) >> server.ehlo() >> server.starttls() >> server.ehlo() >> server.login(fromJSSHS, '******') >> server.sendmail(fromJSSHS, toJSSHS, messageJSSHS) >> server.quit() >> >> >> ##### ERROR BELOW #### >> >> [Wed Mar 23 17:14:48 2016] [error] [client 182.68.165.86] Premature >> end of script headers: application.cgi, referer: >> http://jsshs.org/application.html [Wed Mar 23 17:14:48 2016] [error] >> [client 182.68.165.86] File does not exist: >> /home/jsshsbtl/public_html/500.shtml, referer: >> http://jsshs.org/application.html send: 'mail >> FROM: size=474\r\n' send: "\r\nFrom : >> no-reply at jsshs.org\r\nTo : ['drashokkr007 at yahoo.com', >> 'nitin at chandrainformatics.com']\r\nSubject : Registration confirmation >> with JSSHS\r\n\r\n\r\nApplicationID : jsshs28\r\nFirstNAME : >> mukesh\r\nLastNAME : kumar\r\nGender : male\r\nDoB : 15/09/1982\r\nAge >> : 34\r\nCategory : scst\r\nPost : paramedical\r\nPhone M : >> 9872342266\r\nPhone LL : 01124893479\r\nEmail : >> drashokkr007 at yahoo.com\r\nSubmission DT : 23/03/2016\r\nSubmission >> Time : 05:38PM\r\n\r\n.\r\n" reply: '250 Message denied - From address >> spoofing attempt detected via SMTP ( From address: IP: 111.118.215.222 >> AuthenticatedID: no-reply at jsshs.org Protocol: esmtpa)\r\n' reply: >> retcode (250); Msg: Message denied - From address spoofing attempt >> detected via SMTP ( From address: IP: 111.118.215.222 AuthenticatedID: >> no-reply at jsshs.org Protocol: esmtpa) data: (250, 'Message denied - >> From address spoofing attempt detected via SMTP ( From address: IP: >> 111.118.215.222 AuthenticatedID: no-reply at jsshs.org Protocol: >> esmtpa)') >> >> >> Thanks >> >> Nitin >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor > > > According to this page: > http://www.answersthatwork.com/Download_Area/ATW_Library/Networking/Network__3-SMTP_Server_Status_Codes_and_SMTP_Error_Codes.pdf > > You have succeeded in sending your message. Does the message get sent? > > -- > Joel Goldstick > http://joelgoldstick.com/ > http://cc-baseballstats.info/ From bill at celestial.net Fri Mar 25 18:18:57 2016 From: bill at celestial.net (Bill Campbell) Date: Fri, 25 Mar 2016 15:18:57 -0700 Subject: [Tutor] python smtplib 'Message denied - From address spoofing attempt detected via SMTP In-Reply-To: References: Message-ID: <20160325221857.GA25870@ayn.mi.celestial.com> On Sat, Mar 26, 2016, nitin chandra wrote: >Hi All, > >I am trying to script a confirmation mail on submission of a form. > >Till now the form submission and summery page is working. > >BUT the following 'section' is not working. >-- This is a python(CGI) script >-- hosted on a shared server on hostgator.in > >-- This is giving "250 Spoofing error ....", below copy/pasted error >log of apache with respect to my website The problem isn't with the python usage, but basic SMTP checking to prevent spamming and such. It's indicating that it thinks the 'From:' address, is bogus. There's no MX record for jss.hs.org, and no IP address for jss.hs.org either. The From: address should be legitimate and deliverable. It might also accept a legitimate 'Reply-To:' address. Bill -- INTERNET: bill at celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax: (206) 232-9186 Skype: jwccsllc (206) 855-5792 A Democracy cannot exist as a permanent form of government. It can only exist until the voters discover they can vote themselves largesse out of the public treasury. From the moment on the majority always votes for the candidate promising the most benefits from the public treasury with the result that Democracy always collapses over a loose fiscal policy, always to be followed by a Dictatorship. Professor Alexander Fraser Tytler. 1801 From starfas_s at yahoo.com Fri Mar 25 17:50:45 2016 From: starfas_s at yahoo.com (Sam Starfas) Date: Fri, 25 Mar 2016 21:50:45 +0000 (UTC) Subject: [Tutor] Removing Content from Lines.... In-Reply-To: <1171436017.5032840.1458853431034.JavaMail.yahoo@mail.yahoo.com> References: <1171436017.5032840.1458853431034.JavaMail.yahoo@mail.yahoo.com> Message-ID: <65138470.5615458.1458942645370.JavaMail.yahoo@mail.yahoo.com> Thanks to all who responded. I will try the suggestions and see if I can get the rest of my script to work.Thanks again for the tips. Will also read up on "len" and "index". Cool stuff! On Thursday, March 24, 2016 5:57 PM, Sam Starfas via Tutor wrote: Hello,I am hoping you experts can help out a newbie.I have written some python code to gather a bunch of sentences from many files. These sentences contain the content: blah blah blah blah 1-up printingblah blah blah blah blah blah blah blah blah blah Presetblah blah blah blah blah blah blah Preset blah blah blah What I want to do is remove the words before the and after the .?How do I do that in Python?? Thanks for any and all help.Sam _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor From dimitarxivanov at gmail.com Sat Mar 26 06:08:02 2016 From: dimitarxivanov at gmail.com (Dimitar Ivanov) Date: Sat, 26 Mar 2016 12:08:02 +0200 Subject: [Tutor] Removing Content from Lines.... In-Reply-To: <65138470.5615458.1458942645370.JavaMail.yahoo@mail.yahoo.com> References: <1171436017.5032840.1458853431034.JavaMail.yahoo@mail.yahoo.com> <65138470.5615458.1458942645370.JavaMail.yahoo@mail.yahoo.com> Message-ID: Hello everyone, First time using the mailing list to give a suggestion, apologies in advance if it's not appropriate :) Considering you're looking for specific string, I'd recommend maybe looking into the Regular Expressions. You could use something like: #At the top of the file import re #Within your function target = open(filename, 'rU') # This will read the file as a whole string, careful, it loads the file into memory so if it's a big file, it might cause troubles text = target.read() # The regular expression should match every single tag and its content within the file, using '.*?' will match each character without being greedy. match = re.findall(r'.*?', text) Afterwards, you can use something like: for i in match: print i This should print out all the matches to Stdout so you can verify the RegEx behaves as expected. To write the matches in a new file, you could do: new = open('Matches', 'w') ## This will create a new file called 'Matches' for writing for i in match: new.write(i + '\n') ## Each match of the RegEx will be written on a new line in the Matches file. At the end, my function looks like this: def textfind(filename): target = open(filename, 'rU') text = target.read() match = re.findall(r'.*?', text) new = open('Matches', 'w') for i in match: new.write(i + '\n') Regards, Dimitar -- Thanks, Dimitar *Twitter:* @winterchillz *Facebook: */dimitarxivanov From ianwinstanley8 at gmail.com Sat Mar 26 07:35:13 2016 From: ianwinstanley8 at gmail.com (Ian Winstanley) Date: Sat, 26 Mar 2016 11:35:13 +0000 Subject: [Tutor] Creating an object which is an extension of a dictionary Message-ID: I'm attempting to create an object which can have elements which can be referenced like a dictionary but can also have normal methods and attributes like a conventional object but can also be referenced with key items using d[key] The dictionary I have is below: UPPERCASE = "ucase" LOWERCASE = "lcase" DEFAULT_TYPING_SETTINGS = {"allow letters" : True, "default case" : LOWERCASE, "allow uppercase" : True, "allow lowercase" : True, "allow shift case change" : True, "allow caps lock uppercase" : True, "allow numbers" : True, "allow standard numbers" : True, "allow keypad numbers" : True, "allow spaces" : True, "space keys" : K_SPACE, "allow backspace" : True, "backspace keys" : K_BACKSPACE, "allow newline" : False, "newline keys" : K_RETURN, "allow tab" : False, "tab keys" : K_TAB, "tab stop" : 4, "allow punctuation" : True, "allow standard punctuation" : True, "allow shift punctuation" : True, "allow number key punctuation" : True, "allow keypad punctuation" : True, "punctuation allowed" : None, "punctuation disallowed" : None, "show cursor" : False, "allow navigation" : False, "allow horizontal navigation" : False, "allow vertical navigation" : False, "allow arrow key navigation" : False, "allow keypad navigation" : False} I want to set an attribute for an object's typing settings which I can change any of these individually but I also want to be able to reference methods which can be called to perform operations such as allow all letters. Ideally I want a typing settings object where I can get and set attributes using for example: typing_settings["allow uppercase"] = True but I also want to create methods I can all using dot notation so I need something which is a cross between a dictionary and a conventional object. It isn't absolutely necessary but I would also like to validate when setting the dictionary attributes such as converting necessary values to boolean when setting and ensure the default case attribute is either UPPER or LOWER Thanks for any suggestions Ian From alan.gauld at btinternet.com Sat Mar 26 13:43:22 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 26 Mar 2016 17:43:22 +0000 Subject: [Tutor] Removing Content from Lines.... In-Reply-To: References: <1171436017.5032840.1458853431034.JavaMail.yahoo@mail.yahoo.com> <65138470.5615458.1458942645370.JavaMail.yahoo@mail.yahoo.com> Message-ID: On 26/03/16 10:08, Dimitar Ivanov wrote: > First time using the mailing list to give a suggestion, apologies in > advance if it's not appropriate :) Join the gang, any suggestions are appropriate since even when they aren't completely correct they offer learning opportunities. So all contributions are welcome. > Considering you're looking for specific string, I'd recommend maybe looking > into the Regular Expressions. You could use something like: The regex approach is good if the pattern is not a simple string. And it also has the advantage that you can findall() in one operation. The downside is that regex are notoriously hard to get right for anything other than trivial. > target = open(filename, 'rU') You should probably use the 'with' style with open(filename, 'rU') as target: # code here > # The regular expression should match every single tag and its content > within the file, using '.*?' will match each character without being greedy. > match = re.findall(r'.*?', text) You need a slash for the second tag: match = re.findall(r'.*?', text) > def textfind(filename): > target = open(filename, 'rU') > text = target.read() > match = re.findall(r'.*?', text) > new = open('Matches', 'w') > for i in match: > new.write(i + '\n') You should either close() the file after writing or use the 'with' style (which closes automatically). Otherwise if your program terminated suddenly your data might not make it from the buffer to the disk. The 'with' style is preferred. with open('Matches', 'w') as new: for m in matches: new.write(m + '\n') But your overall point that a regex can be used is correct, especially if the pattern were not consistent (for example if the tag sometimes had spaces or different cased letters). -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Sat Mar 26 13:50:06 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 26 Mar 2016 17:50:06 +0000 Subject: [Tutor] Creating an object which is an extension of a dictionary In-Reply-To: References: Message-ID: On 26/03/16 11:35, Ian Winstanley wrote: > I'm attempting to create an object which can have elements which can be > referenced like a dictionary but can also have normal methods and > attributes like a conventional object but can also be referenced with key > items using d[key] I think you are looking for UserDict (in the UserDict module) which is specifically designed with subclassing in mind. > It isn't absolutely necessary but I would also like to validate when > setting the dictionary attributes such as converting necessary values to > boolean when setting and ensure the default case attribute is either UPPER > or LOWER You can do that by overriding one of the dunder methods. I think __setitem__() is the one you need but the docs will clarify. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From nitinchandra1 at gmail.com Sat Mar 26 15:15:53 2016 From: nitinchandra1 at gmail.com (nitin chandra) Date: Sun, 27 Mar 2016 00:45:53 +0530 Subject: [Tutor] python smtplib 'Message denied - From address spoofing attempt detected via SMTP In-Reply-To: <20160325221857.GA25870@ayn.mi.celestial.com> References: <20160325221857.GA25870@ayn.mi.celestial.com> Message-ID: So I requested the error_logs once again, and this is what was given by the services provider. Still no luck. Apache Log : send: 'ehlo cp-in-9.webhostbox.net\r\n' reply: '250-cp-in-9.webhostbox.net Hello cp-in-9.webhostbox.net [111.118.215.222]\r\n' reply: '250-SIZE 52428800\r\n' reply: '250-8BITMIME\r\n' reply: '250-PIPELINING\r\n' reply: '250-AUTH PLAIN LOGIN\r\n' reply: '250-STARTTLS\r\n' reply: '250 HELP\r\n' reply: retcode (250); Msg: cp-in-9.webhostbox.net Hello cp-in-9.webhostbox.net [111.118.215.222] SIZE 52428800 8BITMIME PIPELINING AUTH PLAIN LOGIN STARTTLS HELP send: 'AUTH PLAIN AG5vLXJlcGx5QGpzc2hzLm9yZwByZXBseTEwSnNzaHM=\r\n' reply: '235 Authentication succeeded\r\n' reply: retcode (235); Msg: Authentication succeeded send: 'mail FROM: size=483\r\n' reply: '250 OK\r\n' reply: retcode (250); Msg: OK send: 'rcpt TO:\r\n' reply: '250 Accepted\r\n' reply: retcode (250); Msg: Accepted send: 'rcpt TO:\r\n' reply: '250 Accepted\r\n' reply: retcode (250); Msg: Accepted send: 'data\r\n' reply: '354 Enter message, ending with "." on a line by itself\r\n' reply: retcode (354); Msg: Enter message, ending with "." on a line by itself data: (354, 'Enter message, ending with "." on a line by itself') send: "\r\nFrom : no-reply at jsshs.org\r\nTo : ['mailhostingserver at gmail.com', 'nitin at chandrainformatics.com']\r\nSubject : Registration confirmation with JSSHS\r\n\r\n\r\nApplicationID : jsshs34\r\nFirstNAME : test\r\nLastNAME : email\r\nGender : male\r\nDoB : 10/11/2015\r\nAge : 0\r\nCategory : general\r\nPost : jrResident\r\nPhone M : 1234567890\r\nPhone LL : 01234567890\r\nEmail : mailhostingserver at gmail.com\r\nSubmission DT : 25/03/2016\r\nSubmission Time : 07:58AM\r\n\r\n.\r\n" reply: '250 Message denied - From address spoofing attempt detected via SMTP ( >From address: IP: 111.118.215.222 AuthenticatedID: no-reply at jsshs.org Protocol: esmtpa)\r\n' reply: retcode (250); Msg: Message denied - >From address spoofing attempt detected via SMTP ( From address: IP: 111.118.215.222 AuthenticatedID: no-reply at jsshs.org Protocol: esmtpa) data: (250, 'Message denied - From address spoofing attempt detected via SMTP ( From address: IP: 111.118.215.222 AuthenticatedID: no-reply at jsshs.org Protocol: esmtpa)') send: 'quit\r\n' reply: '221 cp-in-9.webhostbox.net closing connection\r\n' reply: retcode (221); Msg: cp-in-9.webhostbox.net closing connection Exim Log : 2016-03-26 04:22:38 SMTP connection from [111.118.215.222]:51490 (TCP/IP connection count = 5) 2016-03-26 04:22:38 H=cp-in-9.webhostbox.net [111.118.215.222]:51490 Warning: Sender rate 1.0 / 1h 2016-03-26 04:22:38 1ajfkE-000jLZ-Js <= no-reply at jsshs.org H=cp-in-9.webhostbox.net [111.118.215.222]:51490 P=esmtpa A=dovecot_plain:no-reply at jsshs.org S=692 for mailhostingserver at gmail.com nitin at chandrainformatics.com 2016-03-26 04:22:38 1ajfkE-000jLZ-Js => blackhole (DATA ACL discarded recipients): Message denied - From address spoofing attempt detected via SMTP ( From address: IP: 111.118.215.222 AuthenticatedID: no-reply at jsshs.org Protocol: esmtpa) 2016-03-26 04:22:38 1ajfkE-000jLZ-Js Completed 2016-03-26 04:22:38 SMTP connection from cp-in-9.webhostbox.net [111.118.215.222]:51490 closed by QUIT On 26 March 2016 at 03:48, Bill Campbell wrote: > On Sat, Mar 26, 2016, nitin chandra wrote: >>Hi All, >> >>I am trying to script a confirmation mail on submission of a form. >> >>Till now the form submission and summery page is working. >> >>BUT the following 'section' is not working. >>-- This is a python(CGI) script >>-- hosted on a shared server on hostgator.in >> >>-- This is giving "250 Spoofing error ....", below copy/pasted error >>log of apache with respect to my website > > The problem isn't with the python usage, but basic SMTP checking to prevent > spamming and such. > > It's indicating that it thinks the 'From:' address, > is bogus. > > There's no MX record for jss.hs.org, and no IP address for jss.hs.org > either. > > The From: address should be legitimate and deliverable. It might > also accept a legitimate 'Reply-To:' address. > > Bill > -- > INTERNET: bill at celestial.com Bill Campbell; Celestial Software LLC > URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way > Voice: (206) 236-1676 Mercer Island, WA 98040-0820 > Fax: (206) 232-9186 Skype: jwccsllc (206) 855-5792 > > A Democracy cannot exist as a permanent form of government. It can only > exist until the voters discover they can vote themselves largesse out of > the public treasury. From the moment on the majority always votes for the > candidate promising the most benefits from the public treasury with the > result that Democracy always collapses over a loose fiscal policy, always > to be followed by a Dictatorship. > Professor Alexander Fraser Tytler. 1801 > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From abhishekkmr18 at gmail.com Mon Mar 28 15:31:57 2016 From: abhishekkmr18 at gmail.com (Abhishek Kumar) Date: Tue, 29 Mar 2016 01:01:57 +0530 Subject: [Tutor] How python keeps track of data types Message-ID: Hello I am a computer science student,I want to know how python keeps track of data types of variables and is there a way to get data types of variables without actually running the script(with type() function). I think python AST can help, but am unable to figure out.Please help me. I've explored compiler library but could not find anything helpful. Thanks Abhishek Kumar From alan.gauld at btinternet.com Mon Mar 28 17:51:10 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 28 Mar 2016 22:51:10 +0100 Subject: [Tutor] How python keeps track of data types In-Reply-To: References: Message-ID: On 28/03/16 20:31, Abhishek Kumar wrote: > I am a computer science student,I want to know how python keeps track of > data types of variables and is there a way to get data types of variables > without actually running the script(with type() function). First, recall that Python variables are just names so they don't really have a type as such, it's the objects that they reference that have types. Second, I'm not sure what you mean by "get data types of variables without actually running the script"? The variables/objects don't exist until you run the script through the interpreter. Python is not statically typed so you cannot analyse the source code in any meaningful way to get the information. Can you explain what you want to do with a short example. For example if I have a script hello.py like ################## import sys message = sys.version greeting = "Hello there, " print greeting + message message = 42 print "the answer is ", message ################## Now how would you want to examine that to determine the "types" of sys, message and greeting?? Especially since message takes on two types(objects) during the execution of the code. > AST can help, but am unable to figure out.Please help me. I don't see how AST would help in this case. It looks at the syntax and in Python there are no type declarations in the syntax. (The new type hints feature might help but very few people actually use that and it doesn't apply in all scenarios) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From ben+python at benfinney.id.au Mon Mar 28 18:14:35 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 29 Mar 2016 09:14:35 +1100 Subject: [Tutor] How python keeps track of data types References: Message-ID: <8560w6b67o.fsf@benfinney.id.au> Abhishek Kumar writes: > I am a computer science student,I want to know how python keeps track > of data types of variables Python doesn't track the type of a variable, because a variable never has any information about type. What Python calls ?variables? are names, referring to objects. Names have no type. Every object has a type, so Python doesn't ?track? the type in the sense you mean. -- \ ?Any sufficiently advanced bug is indistinguishable from a | `\ feature.? ?Rich Kulawiec | _o__) | Ben Finney From steve at pearwood.info Mon Mar 28 18:32:51 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 29 Mar 2016 09:32:51 +1100 Subject: [Tutor] How python keeps track of data types In-Reply-To: References: Message-ID: <20160328223251.GR12526@ando.pearwood.info> On Tue, Mar 29, 2016 at 01:01:57AM +0530, Abhishek Kumar wrote: > Hello > I am a computer science student,I want to know how python keeps track of > data types of variables and is there a way to get data types of variables > without actually running the script(with type() function). I think python > AST can help, but am unable to figure out.Please help me. > I've explored compiler library but could not find anything helpful. Variables in Python do not have types like in C, Pascal or Haskell. Variables can take values of any type: x = None x = 42 # x is now an int x = "Hello" # now x is a str x = [1, 2, 3] # a list of ints x = [1, None, "Hello", 2.5] # list of mixed types x = lambda arg: arg + 1 # and now a function So Python doesn't track the type of variables at all, since variables do not have types. Only values have types: None # the special "None" singleton has type NoneType 42 # an int "Hello" # a string 2.5 # a float and so forth. How does Python track the type of values? In Python, all values are objects. Even strings, floats, ints and None. Objects are typically implemented as a C struct, with a pointer back to the class. So the interpreter can tell the type of the object by looking at the pointer to the class. But that is not part of the Python language, that is part of the implementation. Different Python interpreters, and different versions, will work differently. For example, Jython uses the Java Virtual Machine, so all objects in Jython are Java objects. Jython lets the JVM track the type of objects, using whatever method the JVM uses. Likewise, IronPython uses the .Net Common Language Runtime, so all objects in IronPython are CLR objects. IronPython lets .Net (or Mono) track the type of objects. The "reference implementation" of Python is the normal version of Python most people use, sometimes called CPython. Remember that other versions of Python may work differently inside the interpeter, but the language features should be the same. Python's data model is explained here: https://docs.python.org/3/reference/datamodel.html The CPython implementation is explained in part here: https://docs.python.org/3/c-api/intro.html but only the parts which are public and part of the C API. To really understand the inner workings, you must read the source code: https://hg.python.org/cpython/ The way to determine the type of an object in Python is to call the type() function. -- Steve From kdavid at imf.org Sun Mar 27 11:07:48 2016 From: kdavid at imf.org (Happy Home) Date: Sun, 27 Mar 2016 08:07:48 -0700 Subject: [Tutor] [Fact About] Message-ID: <3qYnVj63NQzFqLR@mail.python.org> Hello, I am IMF agent attach to the World Bank office . I am very much aware of your ordeal towards actualizing the release of your long delayed payment. Not very long after the World Bank completed the acquisition process of all pending payments, I discovered that my boss connived with some top officials of the World Bank to divert funds already approved to settle inheritances, email lottery winners and international contractors. The World Bank has already given approval for the payment of your fund while they deliberately delay your payment and continue to demand fees from different departments mostly from Africa, the UK , Europe and Asia all in an attempt to enrich their private accounts. I wonder why you haven?t notice all these while. I am Christian and my religion does not permit such. Your fund was authorized to be paid to you through the World Bank accredited affiliate with a Key Tested Reference/Claim Code Number, which was supposed to have been issued to you before now. Upon your response to this message, I shall guide you and provide you with all you needed to contact the World Bank affiliate who will facilitate the release of your payment. Truly Yours, Kelly David IMF/World Bank Agent ======================================================================= This e-mail and any attachments may contain information which is confidential, privileged, proprietary or otherwise protected by law. The information is solely intended for the named addressee (or a person responsible for delivering it to the addressee). If you are not the intended recipient of this message, you are not authorized to read, print, retain, copy or disseminate this message or any part of it. If you have received this e-mail in error, please notify the sender immediately by return e-mail and delete it from your computer. ======================================================================= This email has been checked for viruses by Avast antivirus software. http://www.avast.com From dyoo at hashcollision.org Tue Mar 29 03:23:37 2016 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 29 Mar 2016 00:23:37 -0700 Subject: [Tutor] How python keeps track of data types In-Reply-To: References: Message-ID: Hi Abhishek, On Mon, Mar 28, 2016 at 12:31 PM, Abhishek Kumar wrote: > Hello > I am a computer science student,I want to know how python keeps track of > data types of variables and is there a way to get data types of variables > without actually running the script(with type() function). I think python > AST can help, but am unable to figure out.Please help me. > I've explored compiler library but could not find anything helpful. This is not a beginner-level question. You may not be reaching the audience you want here. You're essentially asking for a static type system for Python. Python was not particularly designed to accommodate a static type system It is dynamically typed: in Python, types are attached to values, not variables. Start reading: https://en.wikipedia.org/wiki/Type_system#Dynamic_type_checking_and_runtime_type_information Your question is an active area of CS research. Therefore, we can't provide clear, direct answers to your question: you have to do your own searching. Here are a few starting points. http://lambda-the-ultimate.org/node/1519 http://lambda-the-ultimate.org/node/2622 https://www.cis.upenn.edu/~bcpierce/tapl/ From abhishekkmr18 at gmail.com Tue Mar 29 02:15:34 2016 From: abhishekkmr18 at gmail.com (Abhishek Kumar) Date: Tue, 29 Mar 2016 11:45:34 +0530 Subject: [Tutor] How python keeps track of data types In-Reply-To: References: Message-ID: Thanks everyone for answers and links.I wasn't aware of fact that python names are just references to Objects. Abhishek On Tue, Mar 29, 2016 at 1:01 AM, Abhishek Kumar wrote: > Hello > I am a computer science student,I want to know how python keeps track of > data types of variables and is there a way to get data types of variables > without actually running the script(with type() function). I think python > AST can help, but am unable to figure out.Please help me. > I've explored compiler library but could not find anything helpful. > > Thanks > Abhishek Kumar > From zemmoura.khalil at gmail.com Tue Mar 29 07:29:19 2016 From: zemmoura.khalil at gmail.com (khalil zakaria Zemmoura) Date: Tue, 29 Mar 2016 12:29:19 +0100 Subject: [Tutor] Fwd: How python keeps track of data types In-Reply-To: References: Message-ID: ---------- Forwarded message ---------- From: Abhishek Kumar Date: 2016-03-29 7:15 GMT+01:00 Subject: Re: [Tutor] How python keeps track of data types To: Tutor at python.org Thanks everyone for answers and links.I wasn't aware of fact that python names are just references to Objects. Abhishek On Tue, Mar 29, 2016 at 1:01 AM, Abhishek Kumar wrote: > Hello > I am a computer science student,I want to know how python keeps track of > data types of variables and is there a way to get data types of variables > without actually running the script(with type() function). I think python > AST can help, but am unable to figure out.Please help me. > I've explored compiler library but could not find anything helpful. > > Thanks > Abhishek Kumar > _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor Hi Abhishek You may also take a look at this video tutorials serie that was done by Doctor Philip Guo if you are iterested at looking to the python internal and how it works under the hood https://www.youtube.com/watch?v=ngkl95AMl5M&list=PLzV58Zm8FuBL6OAv1Yu6AwXZrnsFbbR0S Best regards From lwaters at flinthill.org Tue Mar 29 14:03:12 2016 From: lwaters at flinthill.org (Lisa Hasler Waters) Date: Tue, 29 Mar 2016 14:03:12 -0400 Subject: [Tutor] Best tool for programming interactive games in Python Message-ID: Hello All, I have a few students who are interested in creating interactive games in Python. We have learned how to use tkinter but we are looking for something more robust. I tried using pygame but cannot seem to get it initialized. I continually get this error: Traceback (most recent call last): File "/Users/lwaters/Desktop/pygameTest.py", line 1, in import pygame, sys File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/__init__.py", line 95, in 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 >>> Any thoughts would be appreciated! Thanks so much, Lisa Waters - a novice Python-er -- Lisa Waters, PhD Technology Integration Flint Hill School From bgailer at gmail.com Tue Mar 29 14:18:35 2016 From: bgailer at gmail.com (Bob Gailer) Date: Tue, 29 Mar 2016 14:18:35 -0400 Subject: [Tutor] Best tool for programming interactive games in Python In-Reply-To: References: Message-ID: On Mar 29, 2016 2:03 PM, "Lisa Hasler Waters" wrote: > > I continually get this error: > > > Traceback (most recent call last): > File "/Users/lwaters/Desktop/pygameTest.py", line 1, in > import pygame, sys > File > "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/__init__.py", > line 95, in > 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 I assume you are running python 2.7 . true? What operating system? How did you install pygame? First guess uninstall and reinstall a game. Any other information you can give us may help. From lwaters at flinthill.org Tue Mar 29 14:31:05 2016 From: lwaters at flinthill.org (Lisa Hasler Waters) Date: Tue, 29 Mar 2016 14:31:05 -0400 Subject: [Tutor] Best tool for programming interactive games in Python In-Reply-To: References: Message-ID: Thanks Bob. Using Mac, OS 10.11 El Cap Yes running Python 2.7 Installed the Pygame from: http://www.pygame.org/download.shtml 1.9.1 I could try to uninstall/re -- but I'll wait to see if anyone has other suggestions based on the new info I've provided. Thx On Tue, Mar 29, 2016 at 2:18 PM, Bob Gailer wrote: > > On Mar 29, 2016 2:03 PM, "Lisa Hasler Waters" > wrote: > > > > I continually get this error: > > > > > > Traceback (most recent call last): > > File "/Users/lwaters/Desktop/pygameTest.py", line 1, in > > import pygame, sys > > File > > > "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/__init__.py", > > line 95, in > > 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 > I assume you are running python 2.7 . true? > What operating system? > How did you install pygame? > First guess uninstall and reinstall a game. > Any other information you can give us may help. > -- Lisa Waters, PhD Technology Integration Flint Hill School From oscar.j.benjamin at gmail.com Tue Mar 29 14:35:00 2016 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Tue, 29 Mar 2016 19:35:00 +0100 Subject: [Tutor] Best tool for programming interactive games in Python In-Reply-To: References: Message-ID: On 29 Mar 2016 21:19, "Bob Gailer" wrote: > > On Mar 29, 2016 2:03 PM, "Lisa Hasler Waters" wrote: > > > > I continually get this error: > > > > > > Traceback (most recent call last): > > File "/Users/lwaters/Desktop/pygameTest.py", line 1, in > > import pygame, sys > > File > > > "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/__init__.py", > > line 95, in > > 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 > I assume you are running python 2.7 . true? > What operating system? > How did you install pygame? > First guess uninstall and reinstall a game. > Any other information you can give us may help Just guessing here but the error suggests a mismatch between 32 and 64 bit binaries. Is it possible that you have installed 32 bit Python and 64 bit pygame or vice-versa? (I'm not an OSX user but I think that's what the error can mean.) -- Oscar From alan.gauld at btinternet.com Tue Mar 29 15:19:38 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 29 Mar 2016 20:19:38 +0100 Subject: [Tutor] Best tool for programming interactive games in Python In-Reply-To: References: Message-ID: On 29/03/16 19:03, Lisa Hasler Waters wrote: > I have a few students who are interested in creating interactive games in > Python. We have learned how to use tkinter but we are looking for something > more robust. I'm not sure what you mean by robust. Tkinter is fine for low speed/non-graphics intensive type games but probably a bit clunky for graphics. But it should be robust in the sense of reliable... > I tried using pygame but cannot seem to get it initialized. I > continually get this error: > /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/base.so: > no matching architecture in universal wrapper Sounds like you installed the wrong version of pygame for your Mac. The pygame support forum are probably the best folks to ask for specific issues like this. PyGin and Albow are other games based frameworks you could investigate. And of course there is OpenGL which plays very well with MacOSX. Try this link for more: https://wiki.python.org/moin/PythonGameLibraries HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From lwaters at flinthill.org Tue Mar 29 15:35:53 2016 From: lwaters at flinthill.org (Lisa Hasler Waters) Date: Tue, 29 Mar 2016 15:35:53 -0400 Subject: [Tutor] Best tool for programming interactive games in Python In-Reply-To: References: Message-ID: Wonderful! Thanks Alan and Oscar. I will proceed with the various suggestions and hopefully will be successful. Thanks again so very much for all your support and help! Lisa On Tue, Mar 29, 2016 at 3:19 PM, Alan Gauld wrote: > On 29/03/16 19:03, Lisa Hasler Waters wrote: > > > I have a few students who are interested in creating interactive games in > > Python. We have learned how to use tkinter but we are looking for > something > > more robust. > > I'm not sure what you mean by robust. Tkinter is fine for > low speed/non-graphics intensive type games but probably > a bit clunky for graphics. But it should be robust in > the sense of reliable... > > > > I tried using pygame but cannot seem to get it initialized. I > > continually get this error: > > > > /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/base.so: > > no matching architecture in universal wrapper > > Sounds like you installed the wrong version of pygame for your Mac. > The pygame support forum are probably the best folks to ask for specific > issues like this. > > PyGin and Albow are other games based frameworks you could > investigate. And of course there is OpenGL which plays very > well with MacOSX. > > Try this link for more: > > https://wiki.python.org/moin/PythonGameLibraries > > HTH > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > http://www.flickr.com/photos/alangauldphotos > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Lisa Waters, PhD Technology Integration Flint Hill School From oscar.j.benjamin at gmail.com Tue Mar 29 17:17:01 2016 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Tue, 29 Mar 2016 22:17:01 +0100 Subject: [Tutor] Best tool for programming interactive games in Python In-Reply-To: References: Message-ID: On 29 Mar 2016 22:20, "Alan Gauld" wrote: > > PyGin and Albow are other games based frameworks you could > investigate. And of course there is OpenGL which plays very > well with MacOSX. OpenGL plays nicely with Windows and Linux as well. I think that pygame actually uses pyglet which is an OpenGL wrapper behind the scenes. I'm not sure what kind of class this setup is for but I doubt that using raw OpenGL is appropriate here. Some kind of higher level wrapper (e.g. pygame) is what you'd want. I'm not sure how well maintained pygame is any more though. Does anyone know? -- Oscar From alan.gauld at btinternet.com Tue Mar 29 19:26:25 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 30 Mar 2016 00:26:25 +0100 Subject: [Tutor] Best tool for programming interactive games in Python In-Reply-To: References: Message-ID: <56FB0F21.1010205@btinternet.com> On 29/03/16 22:17, Oscar Benjamin wrote: > > > On 29 Mar 2016 22:20, "Alan Gauld" > wrote: > > > investigate. And of course there is OpenGL which plays very > > well with MacOSX. > > OpenGL plays nicely with Windows and Linux as well. > But not so well as MacOS X because the OS itself (or the GUI part) is written in/for OpenGL. So in addition to raw OpenGL you also get to mix n' match the OSX graphics libraries. You can't do that as easily in X or Windows is an add-on library, not a native part of the OS. But I agree raw OpenGL would be too low level for most games development (unless you really want high performance, but then you probably wouldn't use python...). But if you wanted high performance within the context of a single window then OpenGL might be worth exploring. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From wolfrage8765 at gmail.com Wed Mar 30 07:27:30 2016 From: wolfrage8765 at gmail.com (wolfrage8765 at gmail.com) Date: Wed, 30 Mar 2016 07:27:30 -0400 Subject: [Tutor] Best tool for programming interactive games in Python In-Reply-To: <56FB0F21.1010205@btinternet.com> References: <56FB0F21.1010205@btinternet.com> Message-ID: >I have a few students who are interested in creating interactive games in >Python. We have learned how to use tkinter but we are looking for > something more robust. I tried using pygame I recommend Kivy; because then it is easy to take the app from computer to Phone; which opens the world of touch devices! Though not specifically made for games it works very well for my purposes which are a game. From johnf at jfcomputer.com Wed Mar 30 10:36:48 2016 From: johnf at jfcomputer.com (john) Date: Wed, 30 Mar 2016 07:36:48 -0700 Subject: [Tutor] Best tool for programming interactive games in Python In-Reply-To: References: <56FB0F21.1010205@btinternet.com> Message-ID: <56FBE480.9080905@jfcomputer.com> On 03/30/2016 04:27 AM, wolfrage8765 at gmail.com wrote: >> I have a few students who are interested in creating interactive games in >> Python. We have learned how to use tkinter but we are looking for >> something more robust. I tried using pygame > I recommend Kivy; because then it is easy to take the app from > computer to Phone; which opens the world of touch devices! > Though not specifically made for games it works very well for my > purposes which are a game. > I believe Kivy requires pygame so he would get the same error. Johnf From wolfrage8765 at gmail.com Wed Mar 30 10:52:53 2016 From: wolfrage8765 at gmail.com (wolfrage8765 at gmail.com) Date: Wed, 30 Mar 2016 10:52:53 -0400 Subject: [Tutor] Best tool for programming interactive games in Python In-Reply-To: <56FBE480.9080905@jfcomputer.com> References: <56FB0F21.1010205@btinternet.com> <56FBE480.9080905@jfcomputer.com> Message-ID: On Wed, Mar 30, 2016 at 10:36 AM, john wrote: > On 03/30/2016 04:27 AM, wolfrage8765 at gmail.com wrote: >>> >>> I have a few students who are interested in creating interactive games in >>> Python. We have learned how to use tkinter but we are looking for >>> something more robust. I tried using pygame >> >> I recommend Kivy; because then it is easy to take the app from >> computer to Phone; which opens the world of touch devices! >> Though not specifically made for games it works very well for my >> purposes which are a game. >> > I believe Kivy requires pygame so he would get the same error. Since Kivy 1.9 the requirement for pygame has been dropped and they are now using OpenGL instead. From diasnevina at yahoo.co.uk Wed Mar 30 08:43:47 2016 From: diasnevina at yahoo.co.uk (Nevina Dias) Date: Wed, 30 Mar 2016 13:43:47 +0100 Subject: [Tutor] How to calculate the total cost Message-ID: <513F9845-1B50-49A7-9E9E-A1428B44EFBC@yahoo.co.uk> import random import time print ("Welcome to Pizza Shed!") tablenum = input ("Enter table number from 1-25 \n ") while tablenum>25 or tablenum <=0: tablenum = input ("Enter the correct table number, there are only 25 tables ") #Pizza menu with prices print ("---------------------") print ("Let me help you with your order!") print ("---------------------") print ("Menu") print ( "1 = cheese and tomato: 3.50, " "2 = ham and pineapple: 4.20, " "3 = vegetarian: 5.20, " "4 = meat feast: 5.80, " "5 = seafood: 5.60 " ) pizza_choice = input("Enter the type of pizza that you want to order from 1-5 \n") while pizza_choice>5 or pizza_choice <=1: pizza_choice = input ("Enter the right number ") if pizza_choice == 1: print "You have chosen cheese and tomato. The cost for this is 3.50" elif pizza_choice == 2: print ("You have chosen ham and pineapple. The cost for this is 4.20") elif pizza_choice == 3: print ("You have chosen vegetarian. The cost for this is 5.20") elif pizza_choice == 4: print ("You have chosen meat feast. The cost for this is 5.80") elif pizza_choice == 5: print ("You have chosen sea food. The cost for this is 5.60") print ("------------------") pizza_amount = input ("Enter the amount of Pizzas that you want to order ") while pizza_amount > 10 or pizza_amount <=0: pizza_amount = input ("Maximum amount is 10, Please enter again ") print ("--------------------") #base print ("Base") print ( "1 = thin and crispy," "2 = traditional" ) base = input ("Select a base from 1-2 \n") while base>2 or base<=1: base = input ("There are only 2 types, Please enter again ") if base == 1: print "You have chosen thin and crispy" elif base == 2: print ("You have chosen traditional") print ("-------------------") #extra toppings print ("Extra Toppings") toppings = input ("Enter a number for your choice of extra topping \n Enter 1 for extra cheese \n Enter 2 for extra pepperoni \n Enter 3 for extra pineapple \n Enter 4 for extra peppers \n" ) while toppings >4 or toppings < 0: toppings = input ("There are only 4 types of extra toppings, Please try again " ) if toppings == 1: print ("You have chosen extra cheese. The cost for this is 0.50") elif toppings == 2: print ("You have chosen pepperoni. The cost for this is 0.50") elif toppings == 3: print ("You have chosen pineapple. The cost for this is 0.50") elif toppings == 4: print ("You have chosen peppers. The cost for this is 0.50") print ("-------------------------") #drink print ("Drink") print ( "1 = Cola: 0.90, " "2 = Lemonande: 0.80, " "3 = Fizzy Orange: 0.90 " ) drink = input ("Enter a number for your choice of drinks " ) while drink>3 or drink<0: drink = input ("Choices start from 0 to 3 " ) if drink == 1: print "You have chosen Cola. The cost for this is 0.90" elif drink == 2: print ("You have chosen Lemonande. The cost for this is 0.80") elif drink == 3: print ("You have chosen Fizzy Orange. The cost for this is 0.90") drink_amount = input ("Enter the amount of drinks") while drink_amount >10 or drink_amount<0: drink_amount = input (" You can only have upto 10 drinks, Please try again") print ("--------------------------------") print ("Calculating bill") print ("--------------------------------") print ("--------------------------------") print ("Thank You for ordering at Pizza Shed! ") Hey, this is my code.. I need to calculate the total cost, but I m not sure how to do that. Can someone please help me. From sracha00 at leeu.edu Wed Mar 30 08:18:22 2016 From: sracha00 at leeu.edu (Jay Li) Date: Wed, 30 Mar 2016 12:18:22 +0000 Subject: [Tutor] (no subject) Message-ID: <2a0c27248ed9$14621c66$49fcd2a6$@leeu.edu> http://idealwm.com/miles.php Best regards, Jay Li From joel.goldstick at gmail.com Wed Mar 30 13:04:49 2016 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 30 Mar 2016 13:04:49 -0400 Subject: [Tutor] How to calculate the total cost In-Reply-To: <513F9845-1B50-49A7-9E9E-A1428B44EFBC@yahoo.co.uk> References: <513F9845-1B50-49A7-9E9E-A1428B44EFBC@yahoo.co.uk> Message-ID: On Wed, Mar 30, 2016 at 8:43 AM, Nevina Dias via Tutor wrote: > import random > import time > > print ("Welcome to Pizza Shed!") > > tablenum = input ("Enter table number from 1-25 \n ") > while tablenum>25 or tablenum <=0: > tablenum = input ("Enter the correct table number, there are only 25 > tables ") > > #Pizza menu with prices > > print ("---------------------") > > print ("Let me help you with your order!") > > print ("---------------------") > > print ("Menu") > > print ( > "1 = cheese and tomato: 3.50, " > "2 = ham and pineapple: 4.20, " > "3 = vegetarian: 5.20, " > "4 = meat feast: 5.80, " > "5 = seafood: 5.60 " ) > > pizza_choice = input("Enter the type of pizza that you want to order from > 1-5 \n") > while pizza_choice>5 or pizza_choice <=1: > pizza_choice = input ("Enter the right number ") > > if pizza_choice == 1: > print "You have chosen cheese and tomato. The cost for this is 3.50" > elif pizza_choice == 2: > print ("You have chosen ham and pineapple. The cost for this is 4.20") > elif pizza_choice == 3: > print ("You have chosen vegetarian. The cost for this is 5.20") > elif pizza_choice == 4: > print ("You have chosen meat feast. The cost for this is 5.80") > elif pizza_choice == 5: > print ("You have chosen sea food. The cost for this is 5.60") > > print ("------------------") > > pizza_amount = input ("Enter the amount of Pizzas that you want to order ") > while pizza_amount > 10 or pizza_amount <=0: > pizza_amount = input ("Maximum amount is 10, Please enter again ") > > print ("--------------------") > > #base > > print ("Base") > > print ( > "1 = thin and crispy," > "2 = traditional" ) > > base = input ("Select a base from 1-2 \n") > while base>2 or base<=1: > base = input ("There are only 2 types, Please enter again ") > > if base == 1: > print "You have chosen thin and crispy" > elif base == 2: > print ("You have chosen traditional") > > print ("-------------------") > > #extra toppings > > print ("Extra Toppings") > > toppings = input ("Enter a number for your choice of extra topping \n > Enter 1 for extra cheese \n Enter 2 for extra pepperoni \n Enter 3 for > extra pineapple \n Enter 4 for extra peppers \n" ) > while toppings >4 or toppings < 0: > toppings = input ("There are only 4 types of extra toppings, Please > try again " ) > > if toppings == 1: > print ("You have chosen extra cheese. The cost for this is 0.50") > elif toppings == 2: > print ("You have chosen pepperoni. The cost for this is 0.50") > elif toppings == 3: > print ("You have chosen pineapple. The cost for this is 0.50") > elif toppings == 4: > print ("You have chosen peppers. The cost for this is 0.50") > > print ("-------------------------") > > #drink > > print ("Drink") > > print ( > "1 = Cola: 0.90, " > "2 = Lemonande: 0.80, " > "3 = Fizzy Orange: 0.90 " ) > > drink = input ("Enter a number for your choice of drinks " ) > while drink>3 or drink<0: > drink = input ("Choices start from 0 to 3 " ) > > if drink == 1: > print "You have chosen Cola. The cost for this is 0.90" > elif drink == 2: > print ("You have chosen Lemonande. The cost for this is 0.80") > elif drink == 3: > print ("You have chosen Fizzy Orange. The cost for this is 0.90") > > drink_amount = input ("Enter the amount of drinks") > while drink_amount >10 or drink_amount<0: > drink_amount = input (" You can only have upto 10 drinks, Please try > again") > > print ("--------------------------------") > print ("Calculating bill") > print ("--------------------------------") > print ("--------------------------------") > > print ("Thank You for ordering at Pizza Shed! ") > > > Hey, this is my code.. > I need to calculate the total cost, but I m not sure how to do that. > > Can someone please help me. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > There is a whole thread with this exact same content over the last few days. If that person is your classmate, maybe you should get together. If you are the same person, using a different email address, please don't -- Joel Goldstick http://joelgoldstick.com/ http://cc-baseballstats.info/ From alan.gauld at btinternet.com Wed Mar 30 15:30:04 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 30 Mar 2016 20:30:04 +0100 Subject: [Tutor] How to calculate the total cost In-Reply-To: <513F9845-1B50-49A7-9E9E-A1428B44EFBC@yahoo.co.uk> References: <513F9845-1B50-49A7-9E9E-A1428B44EFBC@yahoo.co.uk> Message-ID: On 30/03/16 13:43, Nevina Dias via Tutor wrote: > import random > import time > > print ("Welcome to Pizza Shed!") > > tablenum = input ("Enter table number from 1-25 \n ") > while tablenum>25 or tablenum <=0: > tablenum = input ("Enter the correct table number, there are only 25 tables ") Assuming you are using python v3 you have more serious problems to solve first. Try to get you existing code to run then we can consider how to add all the different totals. Hint: The sum() function might help. In particular input() in v3 doesn't do what you seem to think it does. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Wed Mar 30 15:35:36 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 30 Mar 2016 20:35:36 +0100 Subject: [Tutor] (no subject) In-Reply-To: <2a0c27248ed9$14621c66$49fcd2a6$@leeu.edu> References: <2a0c27248ed9$14621c66$49fcd2a6$@leeu.edu> Message-ID: On 30/03/16 13:18, Jay Li wrote: > > http://idealwm.com/miles.php > > Best regards, > Jay Li Apologies, a couple of these messages have snuck through this week. It's been entirely my fault, I've hit the approve button when I meant to hit reject. The server is working fine, it's human error. Too many late nights fighting with Java... :-( -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Wed Mar 30 19:46:12 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 31 Mar 2016 00:46:12 +0100 Subject: [Tutor] How to calculate the total cost In-Reply-To: <1634814221.4629846.1459368183484.JavaMail.yahoo@mail.yahoo.com> References: <1634814221.4629846.1459368183484.JavaMail.yahoo@mail.yahoo.com> Message-ID: <56FC6544.8050107@btinternet.com> Forwarding to the list, please always use Reply All or reply List when responding to tutor messages. On 30/03/16 21:03, Nevina Dias wrote: > Hey, > I'm not sure.. > This is how our teacher said to do. He said to use input.. input() is the correct thing to use in v3 but you are using it wrongly. But first please confirm whether you are using Python v2 or v3? input() works very differently depending on which version you use. What happens when you try to run your program as it is? Do you get an error message? One of the most important techniques to learn in Python is to write small amounts of code and then test them. Only when the first small part is working should you write more code. Then if it breaks you know which bit of code(the new bit) must be faulty. So before worrying about totals get the existing code to run without errors. > > pizzatype = [3.50,4.20,5.20,5.80,5.60] > drinktype = [0.90,0.80,0.90] > topping = [0.50,0.50,0.50,0.50] > > def Total_cost_cal (pt ,dt ,t): > total = pt + dt + t > return total > > but it didn't work. > That code doesn't do anything. You just define some values but never use them. But saying "it didn't work" is not helpful. It doesn't tell us how it didn't work. Did you get an error message? If so what? If not did you get any output? - what? Was it what you expected? If not what did you expect? If you provide more detailed information you will get more useful feedback. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From joel.goldstick at gmail.com Thu Mar 31 08:03:41 2016 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 31 Mar 2016 08:03:41 -0400 Subject: [Tutor] URGENT: PYTHON QUESTION In-Reply-To: <2054043799.274548.1459424819906.JavaMail.yahoo@mail.yahoo.com> References: <1117948189.183231.1459415454853.JavaMail.yahoo.ref@mail.yahoo.com> <1117948189.183231.1459415454853.JavaMail.yahoo@mail.yahoo.com> <699618452.247874.1459424629520.JavaMail.yahoo@mail.yahoo.com> <2054043799.274548.1459424819906.JavaMail.yahoo@mail.yahoo.com> Message-ID: direct your question to tutor at python.org. Also provide the results you have gotten from your code, and what you think is wrong On Thu, Mar 31, 2016 at 7:46 AM, accessmuah wrote: > Hi > > > > Pls, helped review it as i cant proceed to the next stage > > def manipulate_data(kind, data): > if kind == 'list': > return list(data)[::-1] > elif kind == 'set': > data=set({"a", "b", "c", "d", "e", "ANDELA", "TIA", "AFRICA"}) > return set(data) > elif kind == 'dictionary': > return dict.keys(data) > manipulate_data("list", range(1,6)) > manipulate_data("set", {"a", "b", "c", "d", "e", "ANDELA", "TIA", > "AFRICA"}) > manipulate_data("dictionary", {"apples": 23, "oranges": 15, "mangoes": 3, > "grapes": 45}) > > > > > I > DS LAB > Create a function manipulate_data that does the following > Accepts as the first parameter a string specifying the data structure to > be used "list", "set" or "dictionary" Accepts as the second parameter the > data to be manipulated based on the data structure specified e.g [1, 4, > 9, 16, 25] for a list data structure Based off the first parameter > > - return the reverse of a list or > - add items `"ANDELA"`, `"TIA"` and `"AFRICA"` to the set and return > the resulting set > - return the keys of a dictionary > > > Thanks > > Regards > > Shittu > > > IF YOU THINK YOU CAN'T, YOU CAN'T; IF YOU YOU THINK YOU CAN, YOU CAN !!! > N.G.U > > > > > -- Joel Goldstick http://joelgoldstick.com/ http://cc-baseballstats.info/ From accessmuah at yahoo.com Thu Mar 31 08:47:21 2016 From: accessmuah at yahoo.com (accessmuah) Date: Thu, 31 Mar 2016 12:47:21 +0000 (UTC) Subject: [Tutor] Fw: URGENT: PYTHON QUESTION In-Reply-To: References: <1117948189.183231.1459415454853.JavaMail.yahoo.ref@mail.yahoo.com> <1117948189.183231.1459415454853.JavaMail.yahoo@mail.yahoo.com> <699618452.247874.1459424629520.JavaMail.yahoo@mail.yahoo.com> <2054043799.274548.1459424819906.JavaMail.yahoo@mail.yahoo.com> Message-ID: <619875992.268345.1459428442108.JavaMail.yahoo@mail.yahoo.com> Hi, Pls, assist with this Question....Kindly stroll to the end DS LABCreate a function?manipulate_data?that does the followingAccepts as the first parameter a string specifying the data structure to be used?"list",?"set"?or?"dictionary"?Accepts as the second parameter the data to be manipulated based on the data structure specified e.g?[1, 4, 9, 16, 25]?for a?list?data structure Based off the first parameter - return the reverse of a list or - add items `"ANDELA"`, `"TIA"` and `"AFRICA"` to the set and return the resulting set - return the keys of a dictionary My Answer below - Kindly helped reviewed it def manipulate_data(kind, data):?? ? if kind == 'list':?? ? ? ? return list(data)[::-1]?? ? elif kind == 'set':?? ? ? ? data=set({"a", "b", "c", "d", "e", "ANDELA", "TIA", "AFRICA"})? ? ? ? return set(data)?? ? elif kind == 'dictionary':?? ? ? ? return dict.keys(data)?manipulate_data("list", range(1,6))?manipulate_data("set", {"a", "b", "c", "d", "e", "ANDELA", "TIA", "AFRICA"})manipulate_data("dictionary", {"apples": 23, "oranges": 15, "mangoes": 3, "grapes": 45}) CODE RESULT ?But i cant proceed to next stage...see error below ? Pls assist Thanks Regards? Shittu From steve at pearwood.info Thu Mar 31 12:45:04 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 1 Apr 2016 03:45:04 +1100 Subject: [Tutor] Fw: URGENT: PYTHON QUESTION In-Reply-To: <619875992.268345.1459428442108.JavaMail.yahoo@mail.yahoo.com> References: <1117948189.183231.1459415454853.JavaMail.yahoo.ref@mail.yahoo.com> <1117948189.183231.1459415454853.JavaMail.yahoo@mail.yahoo.com> <699618452.247874.1459424629520.JavaMail.yahoo@mail.yahoo.com> <2054043799.274548.1459424819906.JavaMail.yahoo@mail.yahoo.com> <619875992.268345.1459428442108.JavaMail.yahoo@mail.yahoo.com> Message-ID: <20160331164504.GT12526@ando.pearwood.info> On Thu, Mar 31, 2016 at 12:47:21PM +0000, accessmuah via Tutor wrote: > Hi, > Pls, assist with this Question....Kindly stroll to the end > DS LABCreate a function?manipulate_data?that does the followingAccepts > as the first parameter a string specifying the data structure to be > used?"list",?"set"?or?"dictionary"?Accepts as the second parameter the > data to be manipulated based on the data structure specified e.g?[1, > 4, 9, 16, 25]?for a?list?data structure Based off the first parameter > - return the reverse of a list or > - add items `"ANDELA"`, `"TIA"` and `"AFRICA"` to the set and return the resulting set > - return the keys of a dictionary > > > My Answer below - Kindly helped reviewed it > def manipulate_data(kind, data):?? ? if kind == 'list':?? ? ? ? return > list(data)[::-1]?? ? elif kind == 'set':?? ? ? ? data=set({"a", "b", > "c", "d", "e", "ANDELA", "TIA", "AFRICA"})? ? ? ? return set(data)?? ? > elif kind == 'dictionary':?? ? ? ? return > dict.keys(data)?manipulate_data("list", > range(1,6))?manipulate_data("set", {"a", "b", "c", "d", "e", "ANDELA", > "TIA", "AFRICA"})manipulate_data("dictionary", {"apples": 23, > "oranges": 15, "mangoes": 3, "grapes": 45}) Unfortunately your code has been mangled by the email. Can you try sending it again WITHOUT using Yahoo's "Rich Text" (HTML mail)? I will try to reverse-engineer what you meant: def manipulate_data(kind, data): ?? ?if kind == 'list': ?? ? ? ?return list(data)[::-1] ? ? elif kind == 'set': ? ? ? ? data=set({"a", "b", "c", "d", "e", "ANDELA", "TIA", "AFRICA"}) ? ? ? ? return set(data) elif kind == 'dictionary': ? ? ? ? return dict.keys(data)? manipulate_data("list", range(1,6))? manipulate_data("set", {"a", "b", "c", "d", "e", "ANDELA", "TIA", "AFRICA"}) manipulate_data("dictionary", {"apples": 23, "oranges": 15, "mangoes": 3, "grapes": 45}) Is that what you intended? > CODE RESULT > > > ?But i cant proceed to next stage...see error below ? Pls assist I looked below, but you have not included the error. Perhaps you included it as an attachment? In that case, it would probably be deleted, and if it is a screen-shot, it will be useless to anyone who is blind or visually impaired and reading this using a screen reader. Please COPY and PASTE the text of the error into your email. > > > > Thanks > Regards? > Shittu > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From oscar.j.benjamin at gmail.com Thu Mar 31 15:27:04 2016 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Thu, 31 Mar 2016 20:27:04 +0100 Subject: [Tutor] Best tool for programming interactive games in Python In-Reply-To: <56FB0F21.1010205@btinternet.com> References: <56FB0F21.1010205@btinternet.com> Message-ID: On 30 March 2016 at 00:26, Alan Gauld wrote: > On 29/03/16 22:17, Oscar Benjamin wrote: >> >> On 29 Mar 2016 22:20, "Alan Gauld" > > wrote: >> >> > investigate. And of course there is OpenGL which plays very >> > well with MacOSX. >> >> OpenGL plays nicely with Windows and Linux as well. >> > > But not so well as MacOS X because the OS itself (or the GUI part) is > written in/for OpenGL. So in addition to raw OpenGL you also get to > mix n' match the OSX graphics libraries. You can't do that as easily > in X or Windows is an add-on library, not a native part of the OS. That's interesting. I've used OpenGL on Windows and Linux but not on OSX so I'm not sure exactly what you mean. Modern Linux desktops (Unity, Gnome3, KDE4, etc.) use OpenGL-based compositing just like OSX does and I'm fairly sure Android does as well. Does it just work out better on OSX? I know that work is under way to replace X itself with Wayland and reimplement the core toolkits (Gtk, Qt, etc) on top of Wayland with OpenGL as the core and without the vagaries of the X protocol and without needing the DRI2 extension. Perhaps that would lead to the sort of situation that there is on OSX... -- Oscar From alan.gauld at btinternet.com Thu Mar 31 18:14:08 2016 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 31 Mar 2016 23:14:08 +0100 Subject: [Tutor] Best tool for programming interactive games in Python In-Reply-To: References: <56FB0F21.1010205@btinternet.com> Message-ID: On 31/03/16 20:27, Oscar Benjamin wrote: >>> OpenGL plays nicely with Windows and Linux as well. >> >> mix n' match the OSX graphics libraries. You can't do that as easily >> in X or Windows is an add-on library, not a native part of the OS. > > That's interesting. I've used OpenGL on Windows and Linux but not on > OSX so I'm not sure exactly what you mean. I can't speak for Linux because, although it's my main platform I've not done much graphics on it. But on Windows the core OS APIs all use a device context or GDI object to do their painting. To use OpenGL you need to bridge between the GDI of native windows and the OpenGL libraries. If you want to draw a moving string for instance you need to either use the Windows graphics system or the OpenGL system. In MacOS X the ODS system is OpenGL so you can use the native API interleaved with your OpenGL code. > (Unity, Gnome3, KDE4, etc.) use OpenGL-based compositing just like OSX > does and I'm fairly sure Android does as well. Does it just work out > better on OSX? That's news to me, I thought they(Linux) all worked through the X layers (Xlib, Xt etc). > I know that work is under way to replace X itself with Wayland and > reimplement the core toolkits (Gtk, Qt, etc) on top of Wayland with > OpenGL as the core Yes, and at that point I'd expect Linux to be as seamless as MacOS. But for now it seems to me that you still have to initialise libraries and explicitly link your OpenGL objects to your OS (X)windows etc. In short you have to tell the OS GUI that you are choosing to render on OpenGL and/or use the OpenGL library routines to do any drawing. It's a one or the other approach. In MacOS it's (almost) a mix n match approach, you can use whichever API call is easier for you, OS or OpenGL native and interleave them. There are some issues that arise but I don't do enough graphics work to fully understand them! For my simple needs it all pretty much just worked. PS. When I write MacOS above I suspect I should really be saying Cocoa, but I'm, not even expert enough in MacOSX to be sure of that! :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From dvnsarma at gmail.com Thu Mar 31 21:06:20 2016 From: dvnsarma at gmail.com (=?UTF-8?B?RC5WLk4uU2FybWEg4LCh4LC/LuCwteCwvy7gsI7gsKjgsY0u4LC24LCw4LGN4LCu?=) Date: Fri, 1 Apr 2016 06:36:20 +0530 Subject: [Tutor] Fw: URGENT: PYTHON QUESTION In-Reply-To: <20160331164504.GT12526@ando.pearwood.info> References: <1117948189.183231.1459415454853.JavaMail.yahoo.ref@mail.yahoo.com> <1117948189.183231.1459415454853.JavaMail.yahoo@mail.yahoo.com> <699618452.247874.1459424629520.JavaMail.yahoo@mail.yahoo.com> <2054043799.274548.1459424819906.JavaMail.yahoo@mail.yahoo.com> <619875992.268345.1459428442108.JavaMail.yahoo@mail.yahoo.com> <20160331164504.GT12526@ando.pearwood.info> Message-ID: This is working fine. What is the problem? def manipulate_data(kind, data): if kind == 'list': return list(data)[::-1] elif kind == 'set': #data=set({"a", "b", "c", "d", "e", "ANDELA", "TIA", "AFRICA"}) return set(data) elif kind == 'dictionary': return dict.keys(data) print manipulate_data("list", range(1,6)) print manipulate_data("set", {"a", "b", "c", "d", "e", "ANDELA", "TIA", "AFRICA"}) print manipulate_data("dictionary", {"apples": 23, "oranges": 15, "mangoes": 3, "grapes": 45}) regards, Sarma. On Thu, Mar 31, 2016 at 10:15 PM, Steven D'Aprano wrote: > On Thu, Mar 31, 2016 at 12:47:21PM +0000, accessmuah via Tutor wrote: >> Hi, >> Pls, assist with this Question....Kindly stroll to the end > >> DS LABCreate a function manipulate_data that does the followingAccepts >> as the first parameter a string specifying the data structure to be >> used "list", "set" or "dictionary" Accepts as the second parameter the >> data to be manipulated based on the data structure specified e.g [1, >> 4, 9, 16, 25] for a list data structure Based off the first parameter >> - return the reverse of a list or >> - add items `"ANDELA"`, `"TIA"` and `"AFRICA"` to the set and return the resulting set >> - return the keys of a dictionary >> >> >> My Answer below - Kindly helped reviewed it >> def manipulate_data(kind, data): if kind == 'list': return >> list(data)[::-1] elif kind == 'set': data=set({"a", "b", >> "c", "d", "e", "ANDELA", "TIA", "AFRICA"}) return set(data) >> elif kind == 'dictionary': return >> dict.keys(data) manipulate_data("list", >> range(1,6)) manipulate_data("set", {"a", "b", "c", "d", "e", "ANDELA", >> "TIA", "AFRICA"})manipulate_data("dictionary", {"apples": 23, >> "oranges": 15, "mangoes": 3, "grapes": 45}) > > Unfortunately your code has been mangled by the email. Can you try > sending it again WITHOUT using Yahoo's "Rich Text" (HTML mail)? > > I will try to reverse-engineer what you meant: > > def manipulate_data(kind, data): > if kind == 'list': > return list(data)[::-1] > elif kind == 'set': > data=set({"a", "b", "c", "d", "e", "ANDELA", "TIA", "AFRICA"}) > return set(data) > elif kind == 'dictionary': > return dict.keys(data) > > manipulate_data("list", range(1,6)) > manipulate_data("set", {"a", "b", "c", "d", "e", "ANDELA", "TIA", "AFRICA"}) > manipulate_data("dictionary", {"apples": 23, "oranges": 15, "mangoes": 3, "grapes": 45}) > > > Is that what you intended? > > > >> CODE RESULT >> >> >> But i cant proceed to next stage...see error below Pls assist > > I looked below, but you have not included the error. Perhaps you > included it as an attachment? In that case, it would probably be > deleted, and if it is a screen-shot, it will be useless to anyone who is > blind or visually impaired and reading this using a screen reader. > > Please COPY and PASTE the text of the error into your email. > > > > > > >> >> >> >> Thanks >> Regards >> Shittu >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From daniellasapo at gmail.com Thu Mar 31 23:26:38 2016 From: daniellasapo at gmail.com (Daniella Sapozhnikova) Date: Thu, 31 Mar 2016 23:26:38 -0400 Subject: [Tutor] Week 10 warmup assignment Message-ID: Umm I'm new to this whole tutoring list and I'm having a little bit of trouble in school with my programming classes (hopefully it's not too late to pass my class) but anyway, here's the code I've written: #!/usr/bin/env python # -*- coding: utf-8 -*- """Task 07: declaring a dictionary, creating a function, return a funky total """ DATA = {2: 7493945, 76: 4654320, 3: 4091979, 90: 1824881, 82: 714422, 45: 1137701, 10: 374362, 0: 326226, -15: 417203, -56: 333525, 67: 323451, 99: 321696, 21: 336753, -100: 361237, 55: 1209714, 5150: 1771800, 42: 4714011, 888: 14817667, 3500: 13760234, 712: 10903322, 7: 10443792, 842: 11716264, 18584: 10559923, 666: 9275602, 70: 11901200, 153: 12074784, 8: 4337229} def iter_dict_funky_sum(**DATA): """function that takes one dictionary argument declaring a running total variable, extracting key/value pairs from DATA simultaneously in a for loop, assigning and appending the product of the value minus the key to the running total variable and returning the total.""" funky = 0 for key, value in DATA.iteritems(): funky += value - key return funky Now, everything it's returning is correct, the only problems I'm having is the 2 errors pylint is throwing me, which are: task_07.py:36: [W0621(redefined-outer-name), iter_dict_funky_sum] Redefining name 'DATA' from outer scope (line 7) task_07.py:36: [C0103(invalid-name), iter_dict_funky_sum] Invalid argument name "DATA" What does it mean and how can I fix it?