From reno.esper at gmail.com Mon Jun 1 04:39:03 2015 From: reno.esper at gmail.com (Boy Sandy Gladies Arriezona) Date: Mon, 1 Jun 2015 09:39:03 +0700 Subject: [Tutor] Retain UTF-8 Character in Python List Message-ID: Hi, it's my first time in here. I hope you don't mind if I straight to the question. I do some work in python 2 and my job is to collect some query and then send it to java program via json. We're doing batch update in Apache Phoenix, that's why I collect those query beforehand. My question is: *Can we retain utf-8 character in list without changing its form into \xXX or \u00XX?* The reason is because that java program insert it directly "as is" without iterating the list. So, my query will be the same as we print the list directly. Example: c = 'sffs ? fafd' l = list() l.append(c) print l ['sffs \xc2\xa9 fafd'] # this will be inserted, not ['sffs ? fafd'] --- Best regards, Boy Sandy Gladies Arriezona From stephanie.quiles001 at albright.edu Mon Jun 1 06:01:38 2015 From: stephanie.quiles001 at albright.edu (Stephanie Quiles) Date: Mon, 1 Jun 2015 00:01:38 -0400 Subject: [Tutor] creat a program that reads frequency of words in file Message-ID: Hello. i need serious help. i am a very very new python programmer. I have never done any code in my life. I am lost with these assignments for a class i am taking. I hope someone can assist. below is what i have so far which i know is incorrect. my question is how do i create a dictionary and save the words plus counts to it? i created an empty dictionary and i understand the program should read the entire file and create dictionary and store the data into it. but the only way i could get it to run at all was in the way you see below. i don?t think anything is actually being saved into the dictionary. i am so lost? ??" Word Frequency Write a program that reads the contents of a text file. The program should create a dictionary in which the keys are the individual words found in the file and the values are the number of times each word appears. for example, if the word 'the' appears 128 times, the dictionary would contain an element with 'the' as the key and 128 as the value. the program should either display the frequency of each word or create a second file containing a list of each words and its frequency. """ def main(): dict = {} count = 0 text = input('enter word: ') data = open("words.txt").readlines() for line in data: if text in line: count += 1 print("This word appears", count, "times in the file") main() From __peter__ at web.de Mon Jun 1 11:55:56 2015 From: __peter__ at web.de (Peter Otten) Date: Mon, 01 Jun 2015 11:55:56 +0200 Subject: [Tutor] Retain UTF-8 Character in Python List References: Message-ID: Boy Sandy Gladies Arriezona wrote: > Hi, it's my first time in here. Welcome! > I hope you don't mind if I straight to the > question. > I do some work in python 2 and my job is to collect some query and then > send it to java program via json. We're doing batch update in Apache > Phoenix, that's why I collect those query beforehand. > > My question is: > *Can we retain utf-8 character in list without changing its form into \xXX > or \u00XX?* The reason is because that java program insert it directly "as > is" without iterating the list. So, my query will be the same as we print > the list directly. > > Example: > c = 'sffs ? fafd' > l = list() > > l.append(c) > > print l > ['sffs \xc2\xa9 fafd'] # this will be inserted, not ['sffs ? fafd'] >>> import json >>> items = [u"sffs ? fafd"] # unicode preferrable over str for non-ascii data >>> print json.dumps(items, ensure_ascii=False) ["sffs ? fafd"] From alan.gauld at btinternet.com Mon Jun 1 11:56:08 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 01 Jun 2015 10:56:08 +0100 Subject: [Tutor] creat a program that reads frequency of words in file In-Reply-To: References: Message-ID: On 01/06/15 05:01, Stephanie Quiles wrote: > Hello. i need serious help. i am a very very new python programmer. Welcome. > Write a program that reads the contents of a text file. OK, Well you have done that bit OK. > The program should create a dictionary in which the > keys are the individual words found in the file But you are failing on this bit. As you said you are not storing anything in the dictionary. You need to split your lines into individual words, then store each word in the dictionary. I suggest you simplify the problem for now and try just doing that. Don't worry about counting them for now just save the words into the dictionary. You should end up with the dictionary containing one entry for each of the different words in the file. Some other comments below. > def main(): > dict = {} Don't use dict as a variable because thats a Python function for creating dictionaries. By using it as a name you hide the function. AS a general rule never name variables after their type, name them after their purpose. In this case it could be called 'words' or 'counts' or something similar. > count = 0 > text = input('enter word: ') You weren't asked to read a word from the user. All the data you need is in the file. > data = open("words.txt").readlines() > for line in data: You don't need the readlines() line you can just do for line in open("words.txt"): However, best practice says that this is even better: with open("words.txt") as data: for line in data: This ensures that the file is correctly closed at the end. > if text in line: > count += 1 > print("This word appears", count, "times in the file") And this is, of course, completely off track. You need to split the line into its separate words and store each word into the dictionary. 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 Mon Jun 1 13:22:22 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 1 Jun 2015 21:22:22 +1000 Subject: [Tutor] Retain UTF-8 Character in Python List In-Reply-To: References: Message-ID: <20150601112222.GY932@ando.pearwood.info> On Mon, Jun 01, 2015 at 09:39:03AM +0700, Boy Sandy Gladies Arriezona wrote: > Hi, it's my first time in here. I hope you don't mind if I straight to the > question. > I do some work in python 2 and my job is to collect some query and then > send it to java program via json. We're doing batch update in Apache > Phoenix, that's why I collect those query beforehand. In Python 2, regular strings "" are actually ASCII byte strings, and cannot include Unicode characters. If you try, you'll get something platform dependent, which may be UTF-8, but could be something else. So for example: py> s = "a?b" # Not a Unicode string py> len(s) # Expecting 3. 4 py> for c in s: print c, repr(c) ... a 'a' ? '\xc2' ? '\xa9' b 'b' Not what you want! Instead, you have to use Unicode strings, u"". py> s = u"a?b" # Unicode string py> len(s) 3 py> for c in s: print c, repr(c) ... a u'a' ? u'\xa9' b u'b' py> print s a?b Remember, the u is not part of the string, it is part of the delimiter: ASCII byte string uses delimiters " " or ' ' Unicode string uses delimiters u" " or u' ' > My question is: > *Can we retain utf-8 character in list without changing its form into \xXX > or \u00XX?* The reason is because that java program insert it directly "as > is" without iterating the list. So, my query will be the same as we print > the list directly. What do you mean, the Java program inserts it directly? Inserts it into what? > Example: > c = 'sffs ? fafd' > l = list() > l.append(c) > print l > ['sffs \xc2\xa9 fafd'] # this will be inserted, not ['sffs ? fafd'] Change the string 'sffs...' to a Unicode string u'sffs...' and your example will work. *However*, don't be fooled by Python's list display: py> mylist = [u'a?b'] py> print mylist [u'a\xa9b'] "Oh no!", you might think, "Python has messed up my string and converted the ? into \xa9 which is exactly what I don't want!" But don't be fooled, that's just the list's default display. The string is actually still exactly what you want, it just displays anything which is not ASCII as an escape sequence. But if you print the string directly, you will see it as you intended: py> print mylist[0] # just the string inside the list a?b By the way, if you can use Python 3 instead of Python 2, you may find the Unicode handling is a bit simpler and less confusing. For example, in Python 3, the way lists are printed is a bit more sensible: py> mylist = ['a?b'] # No need for the u' delimiter in Python 3. py> print(mylist) ['a?b'] Python 2.7 will do the job, if you must, but it will be a bit harder and more confusing. Python 3.3 or higher is a better choice for Unicode. -- Steve From robertvstepp at gmail.com Mon Jun 1 16:27:07 2015 From: robertvstepp at gmail.com (boB Stepp) Date: Mon, 1 Jun 2015 09:27:07 -0500 Subject: [Tutor] Should error checking be duplicated for both functions if one function calls another one? Message-ID: Suppose in a given state of a program, function 1 calls function 2. Function 1 includes checks for possible error conditions. If there are no issues, then function 2 should execute with no issues as well. The question is, should function 2 include the error checking done in function 1 if function 2 is only ever called by function 1? My inclination is to say yes, as in some future incarnation of the program function 2 might get called in new ways. What are your thoughts? -- boB From dpalao.python at gmail.com Mon Jun 1 16:33:32 2015 From: dpalao.python at gmail.com (David Palao) Date: Mon, 1 Jun 2015 16:33:32 +0200 Subject: [Tutor] Should error checking be duplicated for both functions if one function calls another one? In-Reply-To: References: Message-ID: Hello, Not sure if I got it, but, in my opinion functions should do only one thing.So if function 2 finds an error, it should raise it. There should be another function (function 1 in your case?) taking care of possible raised errors. Best 2015-06-01 16:27 GMT+02:00 boB Stepp : > Suppose in a given state of a program, function 1 calls function 2. > Function 1 includes checks for possible error conditions. If there are > no issues, then function 2 should execute with no issues as well. The > question is, should function 2 include the error checking done in > function 1 if function 2 is only ever called by function 1? > > My inclination is to say yes, as in some future incarnation of the > program function 2 might get called in new ways. What are your > thoughts? > > -- > boB > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From robertvstepp at gmail.com Mon Jun 1 16:37:47 2015 From: robertvstepp at gmail.com (boB Stepp) Date: Mon, 1 Jun 2015 09:37:47 -0500 Subject: [Tutor] Should error checking be duplicated for both functions if one function calls another one? In-Reply-To: References: Message-ID: On Mon, Jun 1, 2015 at 9:33 AM, David Palao wrote: > Hello, > Not sure if I got it, but, in my opinion functions should do only one > thing.So if function 2 finds an error, it should raise it. There > should be another function (function 1 in your case?) taking care of > possible raised errors. I guess my question was not clearly worded. The idea is that function 1 calls another function. Function 1 checks for possible errors that are relevant. Some or all of these checks are also relevant to the called function. Should the called function also include these relevant error checks? boB From __peter__ at web.de Mon Jun 1 17:30:15 2015 From: __peter__ at web.de (Peter Otten) Date: Mon, 01 Jun 2015 17:30:15 +0200 Subject: [Tutor] Should error checking be duplicated for both functions if one function calls another one? References: Message-ID: boB Stepp wrote: > On Mon, Jun 1, 2015 at 9:33 AM, David Palao > wrote: >> Hello, >> Not sure if I got it, but, in my opinion functions should do only one >> thing.So if function 2 finds an error, it should raise it. There >> should be another function (function 1 in your case?) taking care of >> possible raised errors. > > I guess my question was not clearly worded. The idea is that function > 1 calls another function. Function 1 checks for possible errors that > are relevant. Some or all of these checks are also relevant to the > called function. Should the called function also include these > relevant error checks? I think more important than not repeating the checks is that you avoid duplicate code that does the same thing. If the checks are relatively cheap I don't see a problem with def check(a): """Verify that a ... Helper for f1() and f2(). """ if ...: raise ValueError def f1(a, b): check(a) c = ... f2(a, c) def f2(a, c): check(a) ... # actual work Alternatively you can make f2() private by convention: def f1(a, b): check(a) c = ... _f2(a, c) def _f2(a, c): """Frobnicate a with c. Should only be called by f1() which first verifies that `a` cannot explode. """ ... Should you need a standalone version of f2() later just implement it as def f2(a, c): check(a) return _f2(a, c) From lac at openend.se Mon Jun 1 17:58:03 2015 From: lac at openend.se (Laura Creighton) Date: Mon, 01 Jun 2015 17:58:03 +0200 Subject: [Tutor] Should error checking be duplicated for both functions if one function calls another one? References: Message-ID: <201506011558.t51Fw3bJ028392@fido.openend.se> How many layers do you expect your program to have? (And if the answer is 'a whole lot' then maybe your design needs to be reconsidered.) Dealing with the exception at the lowest level that can deal with it is usually a good idea. Also dealing with the exception at the top level, so that when bad things happen (i.e. the low level that was supposed to catch it had a bug and didn't) your program doesn't terminate, but bravely tries to do the best it can -- this often a good idea. Copy and pasting the same wretched error handling code into every layer of your program is pretty much never a good idea. Laura From steve at pearwood.info Mon Jun 1 18:36:01 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 2 Jun 2015 02:36:01 +1000 Subject: [Tutor] Should error checking be duplicated for both functions if one function calls another one? In-Reply-To: References: Message-ID: <20150601163601.GC932@ando.pearwood.info> On Mon, Jun 01, 2015 at 09:27:07AM -0500, boB Stepp wrote: > Suppose in a given state of a program, function 1 calls function 2. > Function 1 includes checks for possible error conditions. If there are > no issues, then function 2 should execute with no issues as well. The > question is, should function 2 include the error checking done in > function 1 if function 2 is only ever called by function 1? The answer is, "that depends". Suppose *both* functions are public functions, which anyone can use. Some people will call function 1 directly, some will call function 2 directly. In this case, both functions need to do their own error checking, because they cannot trust their arguments will be correct. For example: def greet(name): if name == '': raise ValueError('you must give a name') return "Hello " + name def long_greet(name): if name == '': raise ValueError('you must give a name') return "Greetings and salutations! " + greet(name) Of course, if the error checking is complicated, you should factor it out into a third function: def greet(name): check(name) ... def long_greet(name): check(name) ... There's another possibility. Suppose that only the first function is for public consumption, part of your library's public API. Since anyone might use the first function, including beginners, idiots and people who don't read the documentation, it needs to check the argument. But the second function is only used by *you*, as an internal detail. Of course you give the second function a name starting with an underscore, so that others will know not to use it. (Single underscore names are "private, don't touch".) In this case, the second function doesn't need to check it's arguments because it can trust that the first function will always do the right thing. def function(arg): if arg > 0: return _other_function(arg) else: raise ValueError def _other_function(arg): return ... After all, you would never make a mistake and pass the wrong value, would you? Hmmm... perhaps we should be a little more careful... (Note: in Python, this failure to check arguments is not as dangerous as it may be in some other languages. You typically won't crash the computer, or cause some horrible security vulnerability that lets criminals or the NSA take over your computer. You will probably just get an exception. So there are circumstances where you might choose to just completely ignore any error checking.) What we can do is an intermediate level of error checking between the full checking of arguments done by public functions, and the unconditional trust of the private function, by using assertions. Assertions are checks which can be turned off. (Although, in truth, most people never bother.) Our public function stays the same, and the private one becomes: def _other_function(arg): assert arg > 0 return ... If the assertion is ever false, arg is not larger than 0, Python will raise an AssertionError exception and stop the program. You will then be suitably embarrassed and fix the bug, before it is released to your customers and users. But, unlike the regular form of error checking, the assumption here is that assertions should always pass. Since they will always pass, they don't do anything, and can be turned off safely. You do that by running Python with the -O (for optimize) commandline switch, which disables asserts. This style of coding is often called "Design By Contract", and it is a powerful system for ensuring the safety of error checking during development and the speed of skipping unnecessary checks after deployment. You can read more about the use of assert here: http://import-that.dreamwidth.org/676.html -- Steve From reno.esper at gmail.com Mon Jun 1 18:02:11 2015 From: reno.esper at gmail.com (Boy Sandy Gladies Arriezona) Date: Mon, 1 Jun 2015 23:02:11 +0700 Subject: [Tutor] Retain UTF-8 Character in Python List In-Reply-To: <20150601112222.GY932@ando.pearwood.info> References: <20150601112222.GY932@ando.pearwood.info> Message-ID: On Mon, Jun 1, 2015 at 6:22 PM, Steven D'Aprano wrote: What do you mean, the Java program inserts it directly? Inserts it into what? I mean that java program use the list and directly send it into apache phoenix to do "batch upsert". I thought that because the list is not show me the way I set it, then it will send the wrong data into apache phoenix. I still haven't found the problem yet, I don't know which program is at fault. Anyway, your explanation is really good, thank you. On Mon, Jun 1, 2015 at 4:55 PM, Peter Otten <__peter__ at web.de> wrote: import json items = [u"sffs ? fafd"] # unicode preferrable over str for non-ascii data print json.dumps(items, ensure_ascii=False) ["sffs ? fafd"] I haven't try that, using unicode strings before append it into the list. Awesome, I'll try it out later when I got in the office. Thank you very much. --- Best regards, Boy Sandy Gladies Arriezona From breamoreboy at yahoo.co.uk Mon Jun 1 22:03:40 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 01 Jun 2015 21:03:40 +0100 Subject: [Tutor] Should error checking be duplicated for both functions if one function calls another one? In-Reply-To: References: Message-ID: On 01/06/2015 15:37, boB Stepp wrote: > On Mon, Jun 1, 2015 at 9:33 AM, David Palao wrote: >> Hello, >> Not sure if I got it, but, in my opinion functions should do only one >> thing.So if function 2 finds an error, it should raise it. There >> should be another function (function 1 in your case?) taking care of >> possible raised errors. > > I guess my question was not clearly worded. The idea is that function > 1 calls another function. Function 1 checks for possible errors that > are relevant. Some or all of these checks are also relevant to the > called function. Should the called function also include these > relevant error checks? > > boB > No, the end result would be horrendous code bloat if that was applied across the board. Function 2 should do the checking and raise an error if there's a problem. Function 1 can catch that and proceed or not as it sees fit, as can any other piece of code calling function 2. It's the DRY principle, see http://c2.com/cgi/wiki?DontRepeatYourself -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From paradox at pobox.com Mon Jun 1 23:35:10 2015 From: paradox at pobox.com (Thomas C. Hicks) Date: Tue, 02 Jun 2015 05:35:10 +0800 Subject: [Tutor] creat a program that reads frequency of words in file :p: In-Reply-To: References: Message-ID: <556CD00E.4000107@pobox.com> On 06/01/2015 05:56 PM, Alan Gauld wrote: >> if text in line: >> count += 1 >> print("This word appears", count, "times in the file") > > And this is, of course, completely off track. You need > to split the line into its separate words and store > each word into the dictionary. OP may want to research the setdefault and get methods for dictionaries. SDG, tom From ilakumar at sas.upenn.edu Mon Jun 1 21:50:26 2015 From: ilakumar at sas.upenn.edu (Ila Kumar) Date: Mon, 1 Jun 2015 15:50:26 -0400 Subject: [Tutor] Trouble using bioread to convert files from .acq to .mat Message-ID: Hello, I am a new Python user attempting to use bioread ( https://pypi.python.org/pypi/bioread/0.9.5) to convert files from aqknowledge to matlab. I am using a 64-bit PC, and I have downloaded Matlab, Python, numpy, scipy and bioread. Can someone walk me through the installation process for this package? I can't seem to get it to work. Thank you so much for your help!! From alan.gauld at btinternet.com Tue Jun 2 00:50:33 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 01 Jun 2015 23:50:33 +0100 Subject: [Tutor] Trouble using bioread to convert files from .acq to .mat In-Reply-To: References: Message-ID: On 01/06/15 20:50, Ila Kumar wrote: > Hello, > > I am a new Python user attempting to use bioread ( > https://pypi.python.org/pypi/bioread/0.9.5) to convert files from > aqknowledge to matlab. I am using a 64-bit PC, and I have downloaded > Matlab, Python, numpy, scipy and bioread. Can someone walk me through the > installation process for this package? I can't seem to get it to work. This list is really for questions about core Python and its standard library. None of the packages you mention fall into that category so you will likely get better support on their dedicated fora. The SciPy packages in particular have an active community. That having been said, if you are struggling with installation, try getting one of the SciPy bundles such as Anaconda or Canopy which install all (or most) of the modules you mention as default. However, if you do have questions about core python feel free to ask those here. -- 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 breamoreboy at yahoo.co.uk Tue Jun 2 01:01:38 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 02 Jun 2015 00:01:38 +0100 Subject: [Tutor] Trouble using bioread to convert files from .acq to .mat In-Reply-To: References: Message-ID: On 01/06/2015 23:50, Alan Gauld wrote: > On 01/06/15 20:50, Ila Kumar wrote: >> Hello, >> >> I am a new Python user attempting to use bioread ( >> https://pypi.python.org/pypi/bioread/0.9.5) to convert files from >> aqknowledge to matlab. I am using a 64-bit PC, and I have downloaded >> Matlab, Python, numpy, scipy and bioread. Can someone walk me through the >> installation process for this package? I can't seem to get it to work. > > This list is really for questions about core Python and its > standard library. None of the packages you mention fall into > that category so you will likely get better support on their > dedicated fora. The SciPy packages in particular have an > active community. > > That having been said, if you are struggling with installation, > try getting one of the SciPy bundles such as Anaconda or > Canopy which install all (or most) of the modules you mention > as default. > > However, if you do have questions about core python feel > free to ask those here. > If the OP comes back please provide your OS and Python versions and a specific problem. For all we know "I can't seem to get it to work" might mean that everything is going along beautifully but you just can't see the output because your monitor has failed :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From badouglas at gmail.com Tue Jun 2 01:06:53 2015 From: badouglas at gmail.com (bruce) Date: Mon, 1 Jun 2015 19:06:53 -0400 Subject: [Tutor] Parsing/Crawling test College Class Site. Message-ID: Hi. I'm creating a test py app to do a quick crawl of a couple of pages of a psoft class schedule site. Before I start asking questions/pasting/posting code... I wanted to know if this is the kind of thing that can/should be here.. The real issues I'm facing aren't so much pythonic as much as probably dealing with getting the cookies/post attributes correct. There's ongoing jscript on the site, but I'm hopeful/confident :) that if the cookies/post is correct, then the target page can be fetched.. If this isn't the right list, let me know! And if it is, I'll start posting.. Thanks -bd From alan.gauld at btinternet.com Tue Jun 2 01:48:26 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 02 Jun 2015 00:48:26 +0100 Subject: [Tutor] Parsing/Crawling test College Class Site. In-Reply-To: References: Message-ID: On 02/06/15 00:06, bruce wrote: > Hi. I'm creating a test py app to do a quick crawl of a couple of > pages of a psoft class schedule site. Before I start asking > questions/pasting/posting code... I wanted to know if this is the kind > of thing that can/should be here.. > Probably. we are targeted at beginners to Python and focus on core language and standard library. If you are using the standard library modules to build your app then certainly., If you are using a third party module then we may/may not be able to help depending on who, if anyone, within the group is familiar with it. In that case you may be better on the forum. > The real issues I'm facing aren't so much pythonic as much as probably > dealing with getting the cookies/post attributes correct. There's > ongoing jscript on the site, but I'm hopeful/confident :) that if the > cookies/post is correct, then the target page can be fetched.. Post sample code, any errors you get and as specific a description of the issue as you can. Include OS and Python versions. Use plain text not HTML to preserve code formatting. If it turns out to be way off topic we'll tell you (politely) where you should go for 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 alan.gauld at btinternet.com Tue Jun 2 01:42:22 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 02 Jun 2015 00:42:22 +0100 Subject: [Tutor] creat a program that reads frequency of words in file In-Reply-To: References: Message-ID: <556CEDDE.6020308@btinternet.com> I've CCd the list. Please use reply all when responding to the list. Also please use plain text as HTML/RTF doesn't work on all systems and code in particular often gets mangled. On 01/06/15 23:59, Stephanie Quiles wrote: > Hello again, > > here is the final code? I think :) please see below. Is this is the > easiest way to go about it? I appreciate your assistance! > > defmain(): > words = {} > count =0 Do you need count? What is its purpose? > withopen('words.txt')asdata: > forlineindata: > text = line.split() > forwordintext: > ifwordnot inwords: > words[word] =1 > else: > words[word] +=1 Look into the setdefault() method of dictionaries. It can replace the if/else above. > count +=1 > print(words) Aside from the two comments above, good job! -- 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 breamoreboy at yahoo.co.uk Tue Jun 2 07:42:37 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 02 Jun 2015 06:42:37 +0100 Subject: [Tutor] Parsing/Crawling test College Class Site. In-Reply-To: References: Message-ID: On 02/06/2015 00:06, bruce wrote: > Hi. I'm creating a test py app to do a quick crawl of a couple of > pages of a psoft class schedule site. Before I start asking > questions/pasting/posting code... I wanted to know if this is the kind > of thing that can/should be here.. > > The real issues I'm facing aren't so much pythonic as much as probably > dealing with getting the cookies/post attributes correct. There's > ongoing jscript on the site, but I'm hopeful/confident :) that if the > cookies/post is correct, then the target page can be fetched.. > > If this isn't the right list, let me know! And if it is, I'll start posting.. > > Thanks > > -bd You'll almost certainly need the main list at https://mail.python.org/mailman/listinfo/python-list alternatively available as gmane.comp.python.general However just to get you going take a look at these. https://pypi.python.org/pypi/requests https://pypi.python.org/pypi/beautifulsoup4 -- 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 Tue Jun 2 09:19:52 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 02 Jun 2015 08:19:52 +0100 Subject: [Tutor] creat a program that reads frequency of words in file In-Reply-To: <556CEDDE.6020308@btinternet.com> References: <556CEDDE.6020308@btinternet.com> Message-ID: On 02/06/15 00:42, Alan Gauld wrote: >> forwordintext: >> ifwordnot inwords: >> words[word] =1 >> else: >> words[word] +=1 > > Look into the setdefault() method of dictionaries. > It can replace the if/else above. > On reflection, the get() method might be even more useful. -- 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 Jun 2 09:27:28 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 02 Jun 2015 08:27:28 +0100 Subject: [Tutor] Fwd: Re: Parsing/Crawling test College Class Site. In-Reply-To: References: Message-ID: <556D5AE0.7060203@btinternet.com> Forwarding to list. Always use ReplyAll (or reply List if you have that option) to include the list. -------- Forwarded Message -------- Subject: Re: [Tutor] Parsing/Crawling test College Class Site. Date: Mon, 1 Jun 2015 20:42:48 -0400 From: bruce To: Alan Gauld Seriously embarrassed!! The issue that's happening is the process doesn't generate the page with the classlist!! forgot to mention why I was posting this... On Mon, Jun 1, 2015 at 8:40 PM, bruce wrote: > Hi Alan. > > Thanks. So, here goes! > > The target site is: > https://my.unlv.nevada.edu/psc/lvporprd/EMPLOYEE/HRMS/c/COMMUNITY_ACCESS.CLASS_SEARCH.GBL > > The following is a sample of the test code, as well as the url/posts > of the pages as produced by the Firefox/Firebug process. > > Basically, a user accesses the initial url, and then selects a couple > of items on the page, followed by the "Search" btn at the bottom of > the page. > > The items (in order to be input/selected) by the user are: > -subject (insert ACC) for accounting > -uncheck "Show Open Classes Only" > -select the "Additional Search Criteria" expansion (bottom of the page) > --In the "Days of Week" dropdown, select the "include any of these days" > --select all days except Sat/Sun > > finally, select the "Search" btn, which generates the actual class > list for the ACC dept. > > During each action, the app might generate ajax which > updates/interfaces with the backend. All of this can be seen/tracked > (I think) if you have the Firebug plugin for firefox running, where > you can then track the cookies/post actions. The same data can be > generated running LiveHttpHeaders (or some other network app). > > The process is running on centos, using V2.6.6. > > The test app is a mix of standard py, and liberal use of the system > curl cmd. In order to generate one of the post vars, XPath is used to > extract the value from the initial generated file/content. > > > #!/usr/bin/python > #------------------------------------------------------------- > # > # FileName: > # unlvClassTest.py > # > # Creation date: > # jun/1/15 > # > # Modification/update: > # > # > # Purpose: > # test generating of the psoft dept data > # > # Usage: > # cmdline unlvClassTest.py > # > # App Logic: > # > # > # > # > # > # > #------------------------------------------------------------- > > #test python script > import subprocess > import re > import libxml2dom > import urllib > import urllib2 > import sys, string > import time > import os > import os.path > from hashlib import sha1 > from libxml2dom import Node > from libxml2dom import NodeList > import hashlib > import pycurl > import StringIO > import uuid > import simplejson > from string import ascii_uppercase > > #======================================= > > > execfile('/apps/parseapp2/ascii_strip.py') > execfile('dir_defs_inc.py') > appDir="/apps/parseapp2/" > > # data output filename > datafile="unlvDept.dat" > > > # global var for the parent/child list json > plist={} > > > cname="unlv.lwp" > > #---------------------------------------- > > if __name__ == "__main__": > # main app > > # > # get the input struct, parse it, determine the level > # > > cmd="echo '' > "+datafile > proc=subprocess.Popen(cmd, shell=True,stdout=subprocess.PIPE) > res=proc.communicate()[0].strip() > > cmd="echo '' > "+cname > proc=subprocess.Popen(cmd, shell=True,stdout=subprocess.PIPE) > res=proc.communicate()[0].strip() > > cmd='curl -vvv ' > cmd=cmd+'-A "Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.0.11) > Gecko/2009061118 Fedora/3.0.11-1.fc9 Firefox/3.0.11"' > cmd=cmd+' --cookie-jar '+cname+' --cookie '+cname+' ' > cmd=cmd+'-L "http://www.lonestar.edu/class-search.htm"' > #proc=subprocess.Popen(cmd, shell=True,stdout=subprocess.PIPE) > #res=proc.communicate()[0].strip() > #print res > > cmd='curl -vvv ' > cmd=cmd+'-A "Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.0.11) > Gecko/2009061118 Fedora/3.0.11-1.fc9 Firefox/3.0.11"' > cmd=cmd+' --cookie-jar '+cname+' --cookie '+cname+' ' > cmd=cmd+'-L "https://campus.lonestar.edu/classsearch.htm"' > #proc=subprocess.Popen(cmd, shell=True,stdout=subprocess.PIPE) > #res1=proc.communicate()[0].strip() > #print res1 > > > #initial page > cmd='curl -vvv ' > cmd=cmd+'-A "Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.0.11) > Gecko/2009061118 Fedora/3.0.11-1.fc9 Firefox/3.0.11"' > cmd=cmd+' --cookie-jar '+cname+' --cookie '+cname+' ' > cmd=cmd+'-L "https://my.unlv.nevada.edu/psc/lvporprd/EMPLOYEE/HRMS/c/COMMUNITY_ACCESS.CLASS_SEARCH.GBL"' > proc=subprocess.Popen(cmd, shell=True,stdout=subprocess.PIPE) > res2=proc.communicate()[0].strip() > #print cmd+"\n\n" > > print res2 > > sys.exit() > > > > # s contains HTML not XML text > d = libxml2dom.parseString(res2, html=1) > > #-----------Form------------ > > selpath="//input[@id='ICSID']//attribute::value" > > sel_ = d.xpath(selpath) > > > if (len(sel_) == 0): > #--print svpath > #--print "llllll" > #--print " select error" > sys.exit() > > val="" > ndx=0 > for a in sel_: > > val=a.textContent.strip() > > print val > #sys.exit() > > if(val==""): > sys.exit() > > > #build the 1st post > > ddd=1 > > post="" > post="ICAJAX=1" > post=post+"&ICAPPCLSDATA=" > post=post+"&ICAction=DERIVED_CLSRCH_SSR_EXPAND_COLLAPS%24149%24%241" > post=post+"&ICActionPrompt=false" > post=post+"&ICAddCount=" > post=post+"&ICAutoSave=0" > post=post+"&ICBcDomData=undefined" > post=post+"&ICChanged=-1" > post=post+"&ICElementNum=0" > post=post+"&ICFind=" > post=post+"&ICFocus=" > post=post+"&ICNAVTYPEDROPDOWN=0" > post=post+"&ICResubmit=0" > post=post+"&ICSID="+urllib.quote(val) > post=post+"&ICSaveWarningFilter=0" > post=post+"&ICStateNum="+str(ddd) > post=post+"&ICType=Panel" > post=post+"&ICXPos=0" > post=post+"&ICYPos=114" > post=post+"&ResponsetoDiffFrame=-1" > post=post+"&SSR_CLSRCH_WRK_SSR_OPEN_ONLY$chk$3=N" > post=post+"&SSR_CLSRCH_WRK_SUBJECT$0=ACC" > post=post+"&TargetFrameName=None" > > cmd='curl -vvv ' > cmd=cmd+'-A "Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.0.11) > Gecko/2009061118 Fedora/3.0.11-1.fc9 Firefox/3.0.11"' > cmd=cmd+' --cookie-jar '+cname+' --cookie '+cname+' ' > cmd=cmd+'-e "https://my.unlv.nevada.edu/psc/lvporprd/EMPLOYEE/HRMS/c/COMMUNITY_ACCESS.CLASS_SEARCH.GBL?&" > ' > cmd=cmd+'-d "'+post+'" ' > cmd=cmd+'-L "https://my.unlv.nevada.edu/psc/lvporprd/EMPLOYEE/HRMS/c/COMMUNITY_ACCESS.CLASS_SEARCH.GBL"' > proc=subprocess.Popen(cmd, shell=True,stdout=subprocess.PIPE) > res3=proc.communicate()[0].strip() > print cmd+"\n" > print res3 > > > > ##2nd post > ddd=ddd+1 > > post="" > post="ICAJAX=1" > post=post+"&ICAPPCLSDATA=" > post=post+"&ICNAVTYPEDROPDOWN=0" > post=post+"&ICType=Panel" > post=post+"&ICElementNum=0" > post=post+"&ICStateNum="+str(ddd) > post=post+"&ICAction=SSR_CLSRCH_WRK_SUBJECT%240" > post=post+"&ICXPos=0" > post=post+"&ICYPos=501" > post=post+"&ResponsetoDiffFrame=-1" > post=post+"&TargetFrameName=None" > post=post+"&FacetPath=None" > post=post+"&ICSaveWarningFilter=0" > post=post+"&ICChanged=-1" > post=post+"&ICAutoSave=0" > post=post+"&ICResubmit=0" > post=post+"&ICSID="+urllib.quote(val) > post=post+"&ICActionPrompt=false" > post=post+"&ICBcDomData=undefined" > post=post+"&ICFind=" > post=post+"&ICAddCount=" > post=post+"&ICFocus=SSR_CLSRCH_WRK_INCLUDE_CLASS_DAYS%246" > post=post+"&SSR_CLSRCH_WRK_SUBJECT$0=ACC" > post=post+"&SSR_CLSRCH_WRK_SSR_OPEN_ONLY$chk$3=N" > > > cmd='curl -vvv ' > cmd=cmd+'-A "Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.0.11) > Gecko/2009061118 Fedora/3.0.11-1.fc9 Firefox/3.0.11"' > cmd=cmd+' --cookie-jar '+cname+' --cookie '+cname+' ' > cmd=cmd+'-e "https://my.unlv.nevada.edu/psc/lvporprd/EMPLOYEE/HRMS/c/COMMUNITY_ACCESS.CLASS_SEARCH.GBL?&" > ' > cmd=cmd+'-d "'+post+'" ' > cmd=cmd+'-L "https://my.unlv.nevada.edu/psc/lvporprd/EMPLOYEE/HRMS/c/COMMUNITY_ACCESS.CLASS_SEARCH.GBL"' > proc=subprocess.Popen(cmd, shell=True,stdout=subprocess.PIPE) > res3=proc.communicate()[0].strip() > print cmd+"\n" > print res3+"\n\n\n\n\n" > print post > > > > ##sys.exit() > > ##3rd post > ddd=ddd+1 > > post="" > post="ICAJAX=1" > post=post+"&ICNAVTYPEDROPDOWN=0" > post=post+"&ICType=Panel" > post=post+"&ICElementNum=0" > post=post+"&ICStateNum="+str(ddd) > post=post+"&ICAction=CLASS_SRCH_WRK2_SSR_PB_CLASS_SRCH" > post=post+"&ICXPos=0" > post=post+"&ICYPos=501" > post=post+"&ResponsetoDiffFrame=-1" > post=post+"&TargetFrameName=None" > post=post+"&FacetPath=None" > post=post+"&ICFocus=" > post=post+"&ICSaveWarningFilter=0" > post=post+"&ICChanged=-1" > post=post+"&ICAutoSave=0" > post=post+"&ICResubmit=0" > post=post+"&ICSID="+urllib.quote(val) > post=post+"&ICActionPrompt=false" > post=post+"&ICBcDomData=undefined" > post=post+"&ICFind=" > post=post+"&ICAddCount=" > post=post+"&ICAPPCLSDATA=" > post=post+"&SSR_CLSRCH_WRK_INCLUDE_CLASS_DAYS$6=J" > post=post+"&SSR_CLSRCH_WRK_MON$chk$6=Y" > post=post+"&SSR_CLSRCH_WRK_MON$6=Y" > post=post+"&SSR_CLSRCH_WRK_TUES$chk$6=Y" > post=post+"&SSR_CLSRCH_WRK_TUES$6=Y" > post=post+"&SSR_CLSRCH_WRK_WED$chk$6=Y" > post=post+"&SSR_CLSRCH_WRK_WED$6=Y" > post=post+"&SSR_CLSRCH_WRK_THURS$chk$6=Y" > post=post+"&SSR_CLSRCH_WRK_THURS$6=Y" > post=post+"&SSR_CLSRCH_WRK_FRI$chk$6=Y" > post=post+"&SSR_CLSRCH_WRK_FRI$6=Y" > > > cmd='curl -vvv ' > cmd=cmd+'-A "Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.0.11) > Gecko/2009061118 Fedora/3.0.11-1.fc9 Firefox/3.0.11"' > cmd=cmd+' --cookie-jar '+cname+' --cookie '+cname+' ' > cmd=cmd+'-e "https://my.unlv.nevada.edu/psc/lvporprd/EMPLOYEE/HRMS/c/COMMUNITY_ACCESS.CLASS_SEARCH.GBL?&" > ' > cmd=cmd+'-d "'+post+'" ' > cmd=cmd+'-L "https://my.unlv.nevada.edu/psc/lvporprd/EMPLOYEE/HRMS/c/COMMUNITY_ACCESS.CLASS_SEARCH.GBL"' > proc=subprocess.Popen(cmd, shell=True,stdout=subprocess.PIPE) > res3=proc.communicate()[0].strip() > print cmd+"\n" > print res3+"\n\n\n\n\n" > print post > > > > sys.exit() > > > ------------------------------------------------------------------------------------- > The Firefox Actions: > -The initianl url > https://my.unlv.nevada.edu/psc/lvporprd/EMPLOYEE/HRMS/c/COMMUNITY_ACCESS.CLASS_SEARCH.GBL > (performs a get) > > > --Select the "Additional Search Criteria" > ---generates the backend ajax, -- seen by the post action > ------https://my.unlv.nevada.edu/psc/lvporprd/EMPLOYEE/HRMS/c/COMMUNITY_ACCESS.CLASS_SEARCH.GBL > post [ICAJAX=1&ICNAVTYPEDROPDOWN=0&ICType=Panel&ICElementNum=0&ICStateNum=1&ICAction=DERIVED_CLSRCH_SSR_EXPAND_COLLAPS%24149%24%241&ICXPos=0&ICYPos=191&ResponsetoDiffFrame=-1&TargetFrameName=None&FacetPath=None&ICFocus=&ICSaveWarningFilter=0&ICChanged=-1&ICAutoSave=0&ICResubmit=0&ICSID=NwBLGklapJeRFylfen15jatQIwoGcJoQa%2BaO5AyhcwU%3D&ICActionPrompt=false&ICBcDomData=undefined&ICFind=&ICAddCount=&ICAPPCLSDATA=&SSR_CLSRCH_WRK_SSR_OPEN_ONLY$chk$3=N] > > --selecting ACC as the dept > --post url --- https://my.unlv.nevada.edu/psc/lvporprd/EMPLOYEE/HRMS/c/COMMUNITY_ACCESS.CLASS_SEARCH.GBL > > post[ICAJAX=1&ICNAVTYPEDROPDOWN=0&ICType=Panel&ICElementNum=0&ICStateNum=2&ICAction=SSR_CLSRCH_WRK_SUBJECT%240&ICXPos=0&ICYPos=362&ResponsetoDiffFrame=-1&TargetFrameName=None&FacetPath=None&ICFocus=SSR_CLSRCH_WRK_INCLUDE_CLASS_DAYS%246&ICSaveWarningFilter=0&ICChanged=-1&ICAutoSave=0&ICResubmit=0&ICSID=NwBLGklapJeRFylfen15jatQIwoGcJoQa%2BaO5AyhcwU%3D&ICActionPrompt=false&ICBcDomData=undefined&ICFind=&ICAddCount=&ICAPPCLSDATA=&SSR_CLSRCH_WRK_SUBJECT$0=ACC] > > > -selecting the "SearchBTN" > --post URL > https://my.unlv.nevada.edu/psc/lvporprd/EMPLOYEE/HRMS/c/COMMUNITY_ACCESS.CLASS_SEARCH.GBL > > post [ICAJAX=1&ICNAVTYPEDROPDOWN=0&ICType=Panel&ICElementNum=0&ICStateNum=3&ICAction=CLASS_SRCH_WRK2_SSR_PB_CLASS_SRCH&ICXPos=0&ICYPos=633&ResponsetoDiffFrame=-1&TargetFrameName=None&FacetPath=None&ICFocus=&ICSaveWarningFilter=0&ICChanged=-1&ICAutoSave=0&ICResubmit=0&ICSID=NwBLGklapJeRFylfen15jatQIwoGcJoQa%2BaO5AyhcwU%3D&ICActionPrompt=false&ICBcDomData=undefined&ICFind=&ICAddCount=&ICAPPCLSDATA=&SSR_CLSRCH_WRK_INCLUDE_CLASS_DAYS$6=J&SSR_CLSRCH_WRK_MON$chk$6=Y&SSR_CLSRCH_WRK_MON$6=Y&SSR_CLSRCH_WRK_TUES$chk$6=Y&SSR_CLSRCH_WRK_TUES$6=Y&SSR_CLSRCH_WRK_WED$chk$6=Y&SSR_CLSRCH_WRK_WED$6=Y&SSR_CLSRCH_WRK_THURS$chk$6=Y&SSR_CLSRCH_WRK_THURS$6=Y&SSR_CLSRCH_WRK_FRI$chk$6=Y&SSR_CLSRCH_WRK_FRI$6=Y] > > > > On Mon, Jun 1, 2015 at 7:48 PM, Alan Gauld wrote: >> On 02/06/15 00:06, bruce wrote: >>> >>> Hi. I'm creating a test py app to do a quick crawl of a couple of >>> pages of a psoft class schedule site. Before I start asking >>> questions/pasting/posting code... I wanted to know if this is the kind >>> of thing that can/should be here.. >>> >> >> Probably. we are targeted at beginners to Python and focus >> on core language and standard library. If you are using >> the standard library modules to build your app then certainly., >> >> If you are using a third party module then we may/may not >> be able to help depending on who, if anyone, within the >> group is familiar with it. In that case you may be better >> on the forum. >> >>> The real issues I'm facing aren't so much pythonic as much as probably >>> dealing with getting the cookies/post attributes correct. There's >>> ongoing jscript on the site, but I'm hopeful/confident :) that if the >>> cookies/post is correct, then the target page can be fetched.. >> >> >> Post sample code, any errors you get and as specific a >> description of the issue as you can. >> Include OS and Python versions. >> Use plain text not HTML to preserve code formatting. >> >> >> If it turns out to be way off topic we'll tell you (politely) >> where you should go for 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 >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor From stephanie.quiles001 at albright.edu Tue Jun 2 01:19:41 2015 From: stephanie.quiles001 at albright.edu (Stephanie Quiles) Date: Mon, 1 Jun 2015 19:19:41 -0400 Subject: [Tutor] creating a dictionary for capital quiz program Message-ID: Good evening, As you may have noticed i am really struggling with functions and dictionaries. I need to figure out why this program is allowing me to continue entering incorrect data instead of telling me my answer is incorrect. also at the end it?s not tallying the incorrect/correct responses properly. please any help would be appreciated. Write a program that creates a dictionary containing the U.S. States as keys and their capitals as values. (Use the internet to get a list of the states and their capitals.) The program should then randomly quiz the user by displaying the name of a state and asking the usr to enter that state's capital. The program should keep a count of the number of correct and incorrect responses. (As an alternative to the US states, the program can use the names of countries and their capitals.)""" import pickle def main(): right = 0 wrong = 0 capitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau', \ \ "Arizona": 'Phoenix', \ \ 'Arkansas': 'Little Rock', 'California': 'Sacramento', \ \ 'Colorado': 'Denver', \ \ 'Connecticut': 'Hartford', 'Delaware': 'Dover', \ \ 'Florida': 'Tallahassee', \ \ 'Georgia': 'Atlanta', 'Hawaii': 'Honolulu', \ \ 'Idaho': 'Boise', \ \ 'Illinois': 'Springfield', 'Indiana': 'Indianapolis', \ \ 'Iowa': 'Des Moines', \ \ 'Kansas': 'Topeka', 'Kentucky': 'Frankfort', \ \ 'Louisiana': 'Baton Rouge', \ \ 'Maine': 'Augusta', 'Maryland': 'Annapolis', \ \ 'Massachusetts': 'Boston', \ \ 'Michigan': 'Lansing', 'Minnesota': 'Saint Paul', \ \ 'Mississippi': 'Jackson', \ \ 'Missouri': 'Jefferson City', 'Montana': 'Helena', \ \ 'Nebraska': 'Lincoln', \ \ 'Nevada': 'Carson City', 'New Hampshire': 'Concord', \ \ 'New Jersey': 'Trenton', \ \ 'New Mexico': 'Santa Fe', 'New York': 'Albany', \ \ 'North Carolina': 'Raleigh', \ \ 'North Dakota': 'Bismarck', 'Ohio': 'Columbus', \ \ 'Oklahoma': 'Oklahoma City', \ \ 'Oregon': 'Salem', 'Pennsylvania': 'Harrisburg', \ \ 'Rhode Island': 'Providence', \ \ 'South Carolina': 'Columbia', \ \ 'South Dakota': 'Pierre', 'Tennessee': 'Nashville', \ \ 'Texas': 'Austin', 'Utah': 'Salt Lake City', \ \ 'Vermont': 'Montpelier', \ \ 'Virginia': 'Richmond', 'Washington': 'Olympia', \ \ 'West Virginia': 'Charleston', \ \ 'Wisconsin': 'Madison', 'Wyoming': 'Cheyenne'} for k in capitals.keys(): state = input('Enter the capital of '+k+' :') if state.upper() == capitals[k].upper(): right += 1 print('Correct') else: wrong += 1 print('Incorrect') choice = input('Do you want to play again y/n: ') if choice.upper() == 'N': print('end of game') else: choice.upper() != 'Y' print("invalid choice") print('Number of correct answers is: ', right) print("Number of incorrect answers is:", wrong) main() From stephanie.quiles001 at albright.edu Tue Jun 2 03:35:16 2015 From: stephanie.quiles001 at albright.edu (Stephanie Quiles) Date: Mon, 1 Jun 2015 21:35:16 -0400 Subject: [Tutor] creat a program that reads frequency of words in file In-Reply-To: <556CEDDE.6020308@btinternet.com> References: <556CEDDE.6020308@btinternet.com> Message-ID: thanks on the help. I am now stuck on this program for quizzing on state capitals. Do you mind taking a look please? I can?t get it to tell me the answer is incorrect it just keeps asking me for capitals whether the answer is right or wrong. It also is not giving me correct counts for correct and incorrect answers. Any help would be appreciated. Not sure if i turned HTML. my laptop is fairly new and I?m still assimilating to iOS. Please let me know if the code is hard to read. Thanks _______________________________________________________________________________ Write a program that creates a dictionary containing the U.S. States as keys and their capitals as values. (Use the internet to get a list of the states and their capitals.) The program should then randomly quiz the user by displaying the name of a state and asking the usr to enter that state's capital. The program should keep a count of the number of correct and incorrect responses. (As an alternative to the US states, the program can use the names of countries and their capitals.)""" import pickle def main(): right = 0 wrong = 0 capitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau', \ \ "Arizona": 'Phoenix', \ \ 'Arkansas': 'Little Rock', 'California': 'Sacramento', \ \ 'Colorado': 'Denver', \ \ 'Connecticut': 'Hartford', 'Delaware': 'Dover', \ \ 'Florida': 'Tallahassee', \ \ 'Georgia': 'Atlanta', 'Hawaii': 'Honolulu', \ \ 'Idaho': 'Boise', \ \ 'Illinois': 'Springfield', 'Indiana': 'Indianapolis', \ \ 'Iowa': 'Des Moines', \ \ 'Kansas': 'Topeka', 'Kentucky': 'Frankfort', \ \ 'Louisiana': 'Baton Rouge', \ \ 'Maine': 'Augusta', 'Maryland': 'Annapolis', \ \ 'Massachusetts': 'Boston', \ \ 'Michigan': 'Lansing', 'Minnesota': 'Saint Paul', \ \ 'Mississippi': 'Jackson', \ \ 'Missouri': 'Jefferson City', 'Montana': 'Helena', \ \ 'Nebraska': 'Lincoln', \ \ 'Nevada': 'Carson City', 'New Hampshire': 'Concord', \ \ 'New Jersey': 'Trenton', \ \ 'New Mexico': 'Santa Fe', 'New York': 'Albany', \ \ 'North Carolina': 'Raleigh', \ \ 'North Dakota': 'Bismarck', 'Ohio': 'Columbus', \ \ 'Oklahoma': 'Oklahoma City', \ \ 'Oregon': 'Salem', 'Pennsylvania': 'Harrisburg', \ \ 'Rhode Island': 'Providence', \ \ 'South Carolina': 'Columbia', \ \ 'South Dakota': 'Pierre', 'Tennessee': 'Nashville', \ \ 'Texas': 'Austin', 'Utah': 'Salt Lake City', \ \ 'Vermont': 'Montpelier', \ \ 'Virginia': 'Richmond', 'Washington': 'Olympia', \ \ 'West Virginia': 'Charleston', \ \ 'Wisconsin': 'Madison', 'Wyoming': 'Cheyenne'} for k in capitals.keys(): state = input('Enter the capital of '+k+' :') if state.upper() == capitals[k].upper(): right += 1 print('Correct') else: wrong += 1 print('Incorrect') choice = input('Do you want to play again y/n: ') if choice.upper() == 'N': print('end of game') else: choice.upper() != 'Y' print("invalid choice") print('Number of correct answers is: ', right) print("Number of incorrect answers is:", wrong) main() > On Jun 1, 2015, at 7:42 PM, Alan Gauld wrote: > > I've CCd the list. Please use reply all when responding to the list. > Also please use plain text as HTML/RTF doesn't work on all > systems and code in particular often gets mangled. > > On 01/06/15 23:59, Stephanie Quiles wrote: >> Hello again, >> >> here is the final code? I think :) please see below. Is this is the easiest way to go about it? I appreciate your assistance! >> >> defmain(): >> words = {} >> count =0 > > Do you need count? What is its purpose? >> withopen('words.txt')asdata: >> forlineindata: >> text = line.split() >> forwordintext: >> ifwordnot inwords: >> words[word] =1 >> else: >> words[word] +=1 > > Look into the setdefault() method of dictionaries. > It can replace the if/else above. > >> count +=1 >> print(words) > > Aside from the two comments above, good job! > > -- > 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 Tue Jun 2 09:43:17 2015 From: __peter__ at web.de (Peter Otten) Date: Tue, 02 Jun 2015 09:43:17 +0200 Subject: [Tutor] creating a dictionary for capital quiz program References: Message-ID: Stephanie Quiles wrote: > Good evening, > > As you may have noticed i am really struggling with functions and > dictionaries. I need to figure out why this program is allowing me to > continue entering incorrect data instead of telling me my answer is > incorrect. also at the end it?s not tallying the incorrect/correct > responses properly. please any help would be appreciated. > for k in capitals.keys(): > state = input('Enter the capital of '+k+' :') > if state.upper() == capitals[k].upper(): > right += 1 > print('Correct') > else: > wrong += 1 > print('Incorrect') When and how often is the line if state.upper() == capitals[k].upper(): executed? Hint: look at the indentation in the quoted code. PS: > capitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau', \ > \ > "Arizona": 'Phoenix', \ > \ > 'Arkansas': 'Little Rock', 'California': 'Sacramento', \ You don't need these backslashes as long as you're inside parens, brackets or braces. Python will happily accept dicts, lists etc. that spread over multiple lines. From lac at openend.se Tue Jun 2 10:45:29 2015 From: lac at openend.se (Laura Creighton) Date: Tue, 02 Jun 2015 10:45:29 +0200 Subject: [Tutor] Trouble using bioread to convert files from .acq to .mat In-Reply-To: Message from Ila Kumar of "Mon, 01 Jun 2015 15:50:26 -0400." References: Message-ID: <201506020845.t528jTgm020498@fido.openend.se> In a message of Mon, 01 Jun 2015 15:50:26 -0400, Ila Kumar writes: >Hello, > >I am a new Python user attempting to use bioread ( >https://pypi.python.org/pypi/bioread/0.9.5) to convert files from >aqknowledge to matlab. I am using a 64-bit PC, and I have downloaded >Matlab, Python, numpy, scipy and bioread. Can someone walk me through the >installation process for this package? I can't seem to get it to work. > >Thank you so much for your help!! >_______________________________________________ >Tutor maillist - Tutor at python.org >To unsubscribe or change subscription options: >https://mail.python.org/mailman/listinfo/tutor You are getting something like: Command python setup.py egg_info failed with error code 1 in /tmp/pip-build-T3JieI/bioread Storing debug log for failure in /home/lac/.pip/pip.log when you run pip, correct? So you go read the package documentation and discover that bioread uses easy_install (which you are beginning to learn to hate) instead of pip. So then you try that and you get crud like this: .... File "/usr/lib/python2.7/dist-packages/setuptools/sandbox.py", line 43, in _execfile exec(code, globals, locals) File "/tmp/easy_install-PGpger/bioread-0.9.5/setup.py", line 3, in ImportError: No module named ez_setup Correct? If this is your problem, go install this package: https://pypi.python.org/pypi/ez_setup And then install bioread, still with easy_install If this isn't your problem, write back with more of what is not working, please. Hope this is it :) Laura From alan.gauld at btinternet.com Tue Jun 2 11:48:21 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 02 Jun 2015 10:48:21 +0100 Subject: [Tutor] creat a program that reads frequency of words in file In-Reply-To: References: <556CEDDE.6020308@btinternet.com> Message-ID: On 02/06/15 02:35, Stephanie Quiles wrote: > import pickle You don;t need pickle > def main(): > right = 0 > wrong = 0 > capitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau', \ > \ > "Arizona": 'Phoenix', \ You don't need the \ Inside {} you can put newlines as much as you like: 'Arkansas': 'Little Rock', 'California': 'Sacramento', 'Colorado': 'Denver', 'Connecticut': 'Hartford', 'Delaware': 'Dover', 'Florida': 'Tallahassee', etc... > for k in capitals.keys(): > state = input('Enter the capital of '+k+' :') This loop just keeps reading the inputs but does nothing with them. I suspect you intended to have the following lines inside the loop? > if state.upper() == capitals[k].upper(): > right += 1 > print('Correct') > else: > wrong += 1 > print('Incorrect') > choice = input('Do you want to play again y/n: ') > if choice.upper() == 'N': > print('end of game') You need to provide a mechanism for exiting the loop. The break statement can do that for you. > else: > choice.upper() != 'Y' > print("invalid choice") > > print('Number of correct answers is: ', right) > print("Number of incorrect answers is:", wrong) -- 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 Jun 2 12:07:46 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 02 Jun 2015 11:07:46 +0100 Subject: [Tutor] Fwd: Re: Parsing/Crawling test College Class Site. In-Reply-To: <556D5AE0.7060203@btinternet.com> References: <556D5AE0.7060203@btinternet.com> Message-ID: On 02/06/15 08:27, Alan Gauld wrote: >> The following is a sample of the test code, as well as the url/posts >> of the pages as produced by the Firefox/Firebug process. I'm not really answering your question but addressing some issues in your code... >> execfile('/apps/parseapp2/ascii_strip.py') >> execfile('dir_defs_inc.py') I'm not sure what these do but usually its better to import the files as modules then execute their functions directly. >> appDir="/apps/parseapp2/" >> >> # data output filename >> datafile="unlvDept.dat" >> >> >> # global var for the parent/child list json >> plist={} >> >> >> cname="unlv.lwp" >> >> #---------------------------------------- >> >> if __name__ == "__main__": >> # main app It makes testing (and reuse) easier if you put the main code in a function called main() and then just call that here. Also your code could be broken up into smaller functions which again will make testing and debugging easier. >> # >> # get the input struct, parse it, determine the level >> # >> >> cmd="echo '' > "+datafile >> proc=subprocess.Popen(cmd, shell=True,stdout=subprocess.PIPE) >> res=proc.communicate()[0].strip() Its easier and more efficient/reliable to create the file directly from Python. Calling the subprocess modyule each time starts up extra processes. Also you store the result but never use it... >> cmd="echo '' > "+cname >> proc=subprocess.Popen(cmd, shell=True,stdout=subprocess.PIPE) >> res=proc.communicate()[0].strip() See above >> >> cmd='curl -vvv ' >> cmd=cmd+'-A "Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.0.11) >> Gecko/2009061118 Fedora/3.0.11-1.fc9 Firefox/3.0.11"' >> cmd=cmd+' --cookie-jar '+cname+' --cookie '+cname+' ' >> cmd=cmd+'-L "http://www.lonestar.edu/class-search.htm"' You build up strings like this many times but its very inefficient. There are several better options: 1) create a list of substrings then use join() to convert the list to a string. 2) use a triple quoted string to create the string once only. And since you are mostly passing them to Popen look at the docs to see how to pass a list of args instead of one large string, its more secure and generally better practice. >> cmd='curl -vvv ' >> cmd=cmd+'-A "Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.0.11) >> Gecko/2009061118 Fedora/3.0.11-1.fc9 Firefox/3.0.11"' >> cmd=cmd+' --cookie-jar '+cname+' --cookie '+cname+' ' >> cmd=cmd+'-L "https://campus.lonestar.edu/classsearch.htm"' >> >> #initial page >> cmd='curl -vvv ' >> cmd=cmd+'-A "Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.0.11) >> Gecko/2009061118 Fedora/3.0.11-1.fc9 Firefox/3.0.11"' >> cmd=cmd+' --cookie-jar '+cname+' --cookie '+cname+' ' >> cmd=cmd+'-L >> "https://my.unlv.nevada.edu/psc/lvporprd/EMPLOYEE/HRMS/c/COMMUNITY_ACCESS.CLASS_SEARCH.GBL"' >> >> proc=subprocess.Popen(cmd, shell=True,stdout=subprocess.PIPE) >> res2=proc.communicate()[0].strip() >> >> print res2 >> >> sys.exit() Since this is non conditional you always exit here so nothing else ever gets executed. This may be the cause of your problem? >> # s contains HTML not XML text >> d = libxml2dom.parseString(res2, html=1) >> >> #-----------Form------------ >> >> selpath="//input[@id='ICSID']//attribute::value" >> >> sel_ = d.xpath(selpath) >> >> >> if (len(sel_) == 0): >> sys.exit() >> >> val="" >> ndx=0 >> for a in sel_: >> val=a.textContent.strip() >> >> print val >> #sys.exit() >> >> if(val==""): >> sys.exit() >> >> >> #build the 1st post >> >> ddd=1 >> >> post="" This does nothing since you immediately replace it with the next line. >> post="ICAJAX=1" >> post=post+"&ICAPPCLSDATA=" >> post=post+"&ICAction=DERIVED_CLSRCH_SSR_EXPAND_COLLAPS%24149%24%241" >> post=post+"&ICActionPrompt=false" >> post=post+"&ICAddCount=" >> post=post+"&ICAutoSave=0" >> post=post+"&ICBcDomData=undefined" >> post=post+"&ICChanged=-1" >> post=post+"&ICElementNum=0" >> post=post+"&ICFind=" >> post=post+"&ICFocus=" >> post=post+"&ICNAVTYPEDROPDOWN=0" >> post=post+"&ICResubmit=0" >> post=post+"&ICSID="+urllib.quote(val) >> post=post+"&ICSaveWarningFilter=0" >> post=post+"&ICStateNum="+str(ddd) >> post=post+"&ICType=Panel" >> post=post+"&ICXPos=0" >> post=post+"&ICYPos=114" >> post=post+"&ResponsetoDiffFrame=-1" >> post=post+"&SSR_CLSRCH_WRK_SSR_OPEN_ONLY$chk$3=N" >> post=post+"&SSR_CLSRCH_WRK_SUBJECT$0=ACC" >> post=post+"&TargetFrameName=None" Since these are all hard coded strings you might as well have just hard coded the final string and saved a lot of processing. (and code space) >> cmd='curl -vvv ' >> cmd=cmd+'-A "Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.0.11) >> Gecko/2009061118 Fedora/3.0.11-1.fc9 Firefox/3.0.11"' >> cmd=cmd+' --cookie-jar '+cname+' --cookie '+cname+' ' >> cmd=cmd+'-e >> "https://my.unlv.nevada.edu/psc/lvporprd/EMPLOYEE/HRMS/c/COMMUNITY_ACCESS.CLASS_SEARCH.GBL?&" This looks awfully similar to the code up above. Could you have reused the command? Maybe with some parameters - check out string formatting operations. eg: 'This string takes %s as a parameter" % 'a string' I'll stop here, its all getting a bit repetitive. Which is, in itself a sign that you need to create some functions. -- 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 s.shall at virginmedia.com Tue Jun 2 12:59:11 2015 From: s.shall at virginmedia.com (Sydney Shall) Date: Tue, 02 Jun 2015 11:59:11 +0100 Subject: [Tutor] unittest with random population data In-Reply-To: <20150602065949.GA28833@ando.pearwood.info> References: <55699BF1.5090704@virginmedia.com> <20150530234135.GV932@ando.pearwood.info> <556C904C.7070204@virginmedia.com> <20150602065949.GA28833@ando.pearwood.info> Message-ID: <556D8C7F.4080509@virginmedia.com> On 02/06/2015 07:59, Steven D'Aprano wrote: > Please keep your replies on the tutor list, so that others may offer > advice, and learn from your questions. > > Thanks, > > Steve > > On Mon, Jun 01, 2015 at 06:03:08PM +0100, Sydney Shall wrote: >> On 31/05/2015 00:41, Steven D'Aprano wrote: >>> On Sat, May 30, 2015 at 12:16:01PM +0100, Sydney Shall wrote: >>> >>>> I have written a unittest class which works OK. >>>> But the problem I have is that because I use the random module to >>>> populate my initial arrays, my data is not strictly predictable even >>>> though I am using seed(0). >>> >>> Please show us how you populate your arrays, because what you describe >>> sounds wrong. Seeding to the same value should give the same sequence of >>> values: >>> >>> py> import random >>> py> random.seed(0) >>> py> a = [random.random() for i in range(10**6)] >>> py> random.seed(0) >>> py> b = [random.random() for i in range(10**6)] >>> py> a == b >>> True >>> >>> >> Thank you for the advice Steven. >> I was of course aware that I had to use random.seed(0), which I had >> done. I was puzzled by the fact that it did not give me reprocibly >> results, which it did when I was learning python. But because you drew >> attention to the problem, I have looked at again. I surmised that >> perhaps I had put the seed statement in the wrong place. I have tried >> several places, but I always get the sam spread of results. >> >> Perhaps, to help get advice I should explain that I populate a a list thus: >> self.ucc = np.random.normal(self.mean_ucc, self.sigma_ucc, 200) >> This does give me list of 200 slightly different numbers. >> The mean_ucc is always 15.0 and the sigma value is always 3.75. >> The actual mean and sigma of the random numbers is checked that it is >> within 5.0% of 15.0 and 3.75 respectively. >> Following your advice I did a little test. I repeated a little test >> program that I have written, which gives me sensible and proper results. >> I repeated the test 8 times and a then noted a useful output result. >> When I plot the actual mean of the population used against the output >> result I chose, I obtain a perfect straight line, which I should. >> >> Now I still think that I am using the random.seed(0) either incorrectly >> or in the wrong place. >> If there is any other information that might clarify my problem, I will >> be grateful to be told. >> I would be most grateful for any guidance you may have, indicating where >> I should look for what I suspect is a beginner's error. >> >> -- >> Sydney >> > Apolgies. I thought that I had dione so. I will be more careeful infuture. -- Sydney From joel.goldstick at gmail.com Tue Jun 2 14:49:56 2015 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 2 Jun 2015 08:49:56 -0400 Subject: [Tutor] creating a dictionary for capital quiz program In-Reply-To: References: Message-ID: On Tue, Jun 2, 2015 at 3:43 AM, Peter Otten <__peter__ at web.de> wrote: > Stephanie Quiles wrote: > >> Good evening, >> >> As you may have noticed i am really struggling with functions and >> dictionaries. I need to figure out why this program is allowing me to >> continue entering incorrect data instead of telling me my answer is >> incorrect. also at the end it?s not tallying the incorrect/correct >> responses properly. please any help would be appreciated. > >> for k in capitals.keys(): >> state = input('Enter the capital of '+k+' :') The above statement won't print the name of the capital. try something like this: state = input('Enter the capital of' + k + ':') >> if state.upper() == capitals[k].upper(): >> right += 1 >> print('Correct') >> else: >> wrong += 1 >> print('Incorrect') > > When and how often is the line > > if state.upper() == capitals[k].upper(): > > executed? > > Hint: look at the indentation in the quoted code. > > PS: > >> capitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau', \ >> \ >> "Arizona": 'Phoenix', \ >> \ >> 'Arkansas': 'Little Rock', 'California': 'Sacramento', \ > > You don't need these backslashes as long as you're inside parens, brackets > or braces. Python will happily accept dicts, lists etc. that spread over > multiple lines. > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor -- Joel Goldstick http://joelgoldstick.com From JAKUB.ZBUDNIEWEK at arimr.gov.pl Tue Jun 2 10:45:57 2015 From: JAKUB.ZBUDNIEWEK at arimr.gov.pl (ZBUDNIEWEK.JAKUB) Date: Tue, 2 Jun 2015 10:45:57 +0200 Subject: [Tutor] creating a dictionary for capital quiz program In-Reply-To: References: Message-ID: I'm a newbie, but was able to tune it to correctly reply to user inputs. 1. My question is can it be optimized in any way? 2. Why (on Windows) do I have to give inputs in quotes not to cause an error (for ll input the error is ' NameError: name 'll' is not defined')? def main(): right = 0 wrong = 0 capitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau', "Arizona": 'Phoenix', \ 'Arkansas': 'Little Rock', 'California': 'Sacramento', \ 'Colorado': 'Denver', 'Connecticut': 'Hartford', 'Delaware': 'Dover', \ 'Florida': 'Tallahassee', \ 'Georgia': 'Atlanta', 'Hawaii': 'Honolulu', \ 'Idaho': 'Boise', \ 'Illinois': 'Springfield', 'Indiana': 'Indianapolis', \ 'Iowa': 'Des Moines', \ 'Kansas': 'Topeka', 'Kentucky': 'Frankfort', \ 'Louisiana': 'Baton Rouge', \ 'Maine': 'Augusta', 'Maryland': 'Annapolis', \ 'Massachusetts': 'Boston', \ 'Michigan': 'Lansing', 'Minnesota': 'Saint Paul', \ 'Mississippi': 'Jackson', \ 'Missouri': 'Jefferson City', 'Montana': 'Helena', \ 'Nebraska': 'Lincoln', \ 'Nevada': 'Carson City', 'New Hampshire': 'Concord', \ 'New Jersey': 'Trenton', \ 'New Mexico': 'Santa Fe', 'New York': 'Albany', \ 'North Carolina': 'Raleigh', \ 'North Dakota': 'Bismarck', 'Ohio': 'Columbus', \ 'Oklahoma': 'Oklahoma City', \ 'Oregon': 'Salem', 'Pennsylvania': 'Harrisburg', \ 'Rhode Island': 'Providence', \ 'South Carolina': 'Columbia', \ 'South Dakota': 'Pierre', 'Tennessee': 'Nashville', \ 'Texas': 'Austin', 'Utah': 'Salt Lake City', \ 'Vermont': 'Montpelier', \ 'Virginia': 'Richmond', 'Washington': 'Olympia', \ 'West Virginia': 'Charleston', \ 'Wisconsin': 'Madison', 'Wyoming': 'Cheyenne'} for k in capitals.keys(): state = input('Enter the capital of '+k+' :') if state.upper() == capitals[k].upper(): right += 1 print('Correct') else: wrong += 1 print('Incorrect') choice = input('Do you want to play again y/n: ') if choice.upper() == 'N': print('end of game') break elif choice.upper() != 'Y': print("invalid choice") print('Number of correct answers is: ', right) print("Number of incorrect answers is:", wrong) main() Regards, Jakub -----Original Message----- From: Tutor [mailto:tutor-bounces+jakub.zbudniewek=arimr.gov.pl at python.org] On Behalf Of Peter Otten Sent: Tuesday, June 02, 2015 9:43 AM To: tutor at python.org Subject: Re: [Tutor] creating a dictionary for capital quiz program Stephanie Quiles wrote: > Good evening, > > As you may have noticed i am really struggling with functions and > dictionaries. I need to figure out why this program is allowing me to > continue entering incorrect data instead of telling me my answer is > incorrect. also at the end it?s not tallying the incorrect/correct > responses properly. please any help would be appreciated. > for k in capitals.keys(): > state = input('Enter the capital of '+k+' :') > if state.upper() == capitals[k].upper(): > right += 1 > print('Correct') > else: > wrong += 1 > print('Incorrect') When and how often is the line if state.upper() == capitals[k].upper(): executed? Hint: look at the indentation in the quoted code. PS: > capitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau', \ > \ > "Arizona": 'Phoenix', \ > \ > 'Arkansas': 'Little Rock', 'California': 'Sacramento', \ You don't need these backslashes as long as you're inside parens, brackets or braces. Python will happily accept dicts, lists etc. that spread over multiple lines. _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor ************************************************************************************ Wiadomo?? ta jest przeznaczona jedynie dla osoby lub podmiotu, kt?ry jest jej adresatem i mo?e zawiera? poufne i/lub uprzywilejowane informacje. Zakazane jest jakiekolwiek przegl?danie, przesy?anie, rozpowszechnianie lub inne wykorzystanie tych informacji lub podj?cie jakichkolwiek dzia?a? odno?nie tych informacji przez osoby lub podmioty inne ni? zamierzony adresat. Je?eli Pa?stwo otrzymali przez pomy?k? t? informacj? prosimy o poinformowanie o tym nadawcy i usuni?cie tej wiadomo?ci z wszelkich komputer?w. -------------------------------------------------------------------------------- The information transmitted is intended only for the person or entity to which it is addressed and may contain confidential and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon, this information by persons or entities other than the intended recipient is prohibited. If you received this in error, please contact the sender and delete the material from any computer. ************************************************************************************ From __peter__ at web.de Tue Jun 2 16:15:15 2015 From: __peter__ at web.de (Peter Otten) Date: Tue, 02 Jun 2015 16:15:15 +0200 Subject: [Tutor] creating a dictionary for capital quiz program References: Message-ID: ZBUDNIEWEK. JAKUB wrote: > I'm a newbie, but was able to tune it to correctly reply to user inputs. > 2. Why (on Windows) do I have to give inputs in quotes not to cause an > error (for ll input the error is ' NameError: name 'll' is not defined')? If you are running the script under Python 2 you should use raw_input() instead of input(). input() will take the user input and also run eval() on it: Python 2.7.6 (default, Mar 22 2014, 22:59:56) [GCC 4.8.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> input("? ") ? 1 + 1 2 >>> raw_input("? ") ? 1 + 1 '1 + 1' Python 3 has no raw_input() and input() will behave like raw_input() in Python 2. > 1. My question is can it be optimized in any way? In Python 2 capital.keys() builds a list. You can avoid that by iterating over the dict directly: for k in capitals: ... Not an optimization, but if the user enters neither Y nor N you might ask again instead of assuming Y. > def main(): > > right = 0 > wrong = 0 > capitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau', "Arizona": > 'Phoenix', \ > 'Arkansas': 'Little Rock', 'California': 'Sacramento', \ > 'Colorado': 'Denver', 'Connecticut': 'Hartford', > 'Delaware': 'Dover', \ 'Florida': 'Tallahassee', \ > 'Georgia': 'Atlanta', 'Hawaii': 'Honolulu', \ > 'Idaho': 'Boise', \ > 'Illinois': 'Springfield', 'Indiana': 'Indianapolis', \ > 'Iowa': 'Des Moines', \ > 'Kansas': 'Topeka', 'Kentucky': 'Frankfort', \ > 'Louisiana': 'Baton Rouge', \ > 'Maine': 'Augusta', 'Maryland': 'Annapolis', \ > 'Massachusetts': 'Boston', \ > 'Michigan': 'Lansing', 'Minnesota': 'Saint Paul', \ > 'Mississippi': 'Jackson', \ > 'Missouri': 'Jefferson City', 'Montana': 'Helena', \ > 'Nebraska': 'Lincoln', \ > 'Nevada': 'Carson City', 'New Hampshire': 'Concord', \ > 'New Jersey': 'Trenton', \ > 'New Mexico': 'Santa Fe', 'New York': 'Albany', \ > 'North Carolina': 'Raleigh', \ > 'North Dakota': 'Bismarck', 'Ohio': 'Columbus', \ > 'Oklahoma': 'Oklahoma City', \ > 'Oregon': 'Salem', 'Pennsylvania': 'Harrisburg', \ > 'Rhode Island': 'Providence', \ > 'South Carolina': 'Columbia', \ > 'South Dakota': 'Pierre', 'Tennessee': 'Nashville', \ > 'Texas': 'Austin', 'Utah': 'Salt Lake City', \ > 'Vermont': 'Montpelier', \ > 'Virginia': 'Richmond', 'Washington': 'Olympia', \ > 'West Virginia': 'Charleston', \ > 'Wisconsin': 'Madison', 'Wyoming': 'Cheyenne'} > > for k in capitals.keys(): > state = input('Enter the capital of '+k+' :') > if state.upper() == capitals[k].upper(): > right += 1 > print('Correct') > else: > wrong += 1 > print('Incorrect') > choice = input('Do you want to play again y/n: ') > if choice.upper() == 'N': > print('end of game') > break > elif choice.upper() != 'Y': > print("invalid choice") > > print('Number of correct answers is: ', right) > print("Number of incorrect answers is:", wrong) > > main() > > Regards, > Jakub From stephanie.quiles001 at albright.edu Tue Jun 2 16:50:22 2015 From: stephanie.quiles001 at albright.edu (Stephanie Quiles) Date: Tue, 2 Jun 2015 10:50:22 -0400 Subject: [Tutor] creating a dictionary for capital quiz program In-Reply-To: References: Message-ID: <8A70E451-67A3-499D-A1BC-03C286D0D936@albright.edu> Thank you all for your help! I have a text today but I am not confident with this. So basically, what I did wrong was the indentation? Thanks Stephanie Quiles Sent from my iPhone > On Jun 2, 2015, at 10:15 AM, Peter Otten <__peter__ at web.de> wrote: > > ZBUDNIEWEK. JAKUB wrote: > >> I'm a newbie, but was able to tune it to correctly reply to user inputs. > >> 2. Why (on Windows) do I have to give inputs in quotes not to cause an >> error (for ll input the error is ' NameError: name 'll' is not defined')? > > If you are running the script under Python 2 you should use > raw_input() instead of input(). input() will take the user input and also > run eval() on it: > > Python 2.7.6 (default, Mar 22 2014, 22:59:56) > [GCC 4.8.2] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> input("? ") > ? 1 + 1 > 2 >>>> raw_input("? ") > ? 1 + 1 > '1 + 1' > > Python 3 has no raw_input() and input() will behave like raw_input() in > Python 2. > >> 1. My question is can it be optimized in any way? > > In Python 2 capital.keys() builds a list. You can avoid that by iterating > over the dict directly: > > for k in capitals: > ... > > Not an optimization, but if the user enters neither Y nor N you might ask > again instead of assuming Y. > > >> def main(): >> >> right = 0 >> wrong = 0 >> capitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau', "Arizona": >> 'Phoenix', \ >> 'Arkansas': 'Little Rock', 'California': 'Sacramento', \ >> 'Colorado': 'Denver', 'Connecticut': 'Hartford', >> 'Delaware': 'Dover', \ 'Florida': 'Tallahassee', \ >> 'Georgia': 'Atlanta', 'Hawaii': 'Honolulu', \ >> 'Idaho': 'Boise', \ >> 'Illinois': 'Springfield', 'Indiana': 'Indianapolis', \ >> 'Iowa': 'Des Moines', \ >> 'Kansas': 'Topeka', 'Kentucky': 'Frankfort', \ >> 'Louisiana': 'Baton Rouge', \ >> 'Maine': 'Augusta', 'Maryland': 'Annapolis', \ >> 'Massachusetts': 'Boston', \ >> 'Michigan': 'Lansing', 'Minnesota': 'Saint Paul', \ >> 'Mississippi': 'Jackson', \ >> 'Missouri': 'Jefferson City', 'Montana': 'Helena', \ >> 'Nebraska': 'Lincoln', \ >> 'Nevada': 'Carson City', 'New Hampshire': 'Concord', \ >> 'New Jersey': 'Trenton', \ >> 'New Mexico': 'Santa Fe', 'New York': 'Albany', \ >> 'North Carolina': 'Raleigh', \ >> 'North Dakota': 'Bismarck', 'Ohio': 'Columbus', \ >> 'Oklahoma': 'Oklahoma City', \ >> 'Oregon': 'Salem', 'Pennsylvania': 'Harrisburg', \ >> 'Rhode Island': 'Providence', \ >> 'South Carolina': 'Columbia', \ >> 'South Dakota': 'Pierre', 'Tennessee': 'Nashville', \ >> 'Texas': 'Austin', 'Utah': 'Salt Lake City', \ >> 'Vermont': 'Montpelier', \ >> 'Virginia': 'Richmond', 'Washington': 'Olympia', \ >> 'West Virginia': 'Charleston', \ >> 'Wisconsin': 'Madison', 'Wyoming': 'Cheyenne'} >> >> for k in capitals.keys(): >> state = input('Enter the capital of '+k+' :') >> if state.upper() == capitals[k].upper(): >> right += 1 >> print('Correct') >> else: >> wrong += 1 >> print('Incorrect') >> choice = input('Do you want to play again y/n: ') >> if choice.upper() == 'N': >> print('end of game') >> break >> elif choice.upper() != 'Y': >> print("invalid choice") >> >> print('Number of correct answers is: ', right) >> print("Number of incorrect answers is:", wrong) >> >> main() >> >> Regards, >> Jakub > > > _______________________________________________ > 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 Jun 2 17:38:08 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 02 Jun 2015 16:38:08 +0100 Subject: [Tutor] creating a dictionary for capital quiz program In-Reply-To: <8A70E451-67A3-499D-A1BC-03C286D0D936@albright.edu> References: <8A70E451-67A3-499D-A1BC-03C286D0D936@albright.edu> Message-ID: On 02/06/15 15:50, Stephanie Quiles wrote: > So basically, what I did wrong was the indentation? Yes. In Python indentation is all important. When you write a for (or while) loop Python executes all the indented code under the opening loop statement. When it sees an unindented statement it reads that as the next line to execute *after* the loop completes. -- 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 Jun 2 17:45:54 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 02 Jun 2015 16:45:54 +0100 Subject: [Tutor] creating a dictionary for capital quiz program In-Reply-To: References: Message-ID: On 02/06/15 15:15, Peter Otten wrote: > Not an optimization, but if the user enters neither Y nor N you might ask > again instead of assuming Y. He does. He only breaks if the user enters N >> choice = input('Do you want to play again y/n: ') >> if choice.upper() == 'N': >> print('end of game') >> break >> elif choice.upper() != 'Y': >> print("invalid choice") Y goes round again silently. Anything other than Y or N prints the error then tries again. -- 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 Jun 2 17:43:38 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 02 Jun 2015 16:43:38 +0100 Subject: [Tutor] creating a dictionary for capital quiz program In-Reply-To: References: Message-ID: On 02/06/15 09:45, ZBUDNIEWEK.JAKUB wrote: > I'm a newbie, but was able to tune it to correctly reply to user inputs. > 1. My question is can it be optimized in any way? Code can nearly always be optimised. Whether it is worth doing so depends on the need to do so. In this case I douybt its worthwhile :-) > 2. Why (on Windows) do I have to give inputs in quotes not to cause > an error (for ll input the error is ' NameError: name 'll' is > not defined')? As Peter has said, you are probably running Python 2 rather than Python 3. input() changed behaviour in the upgrade. > def main(): > > right = 0 > wrong = 0 > capitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau', "Arizona": 'Phoenix', \ > 'Arkansas': 'Little Rock', 'California': 'Sacramento', \ You don't need the backslashes. Python is quite happy to read capitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau', "Arizona": 'Phoenix', 'Arkansas': 'Little Rock', 'California': 'Sacramento', ...etc... } So long as its inside (),{}, or {} (or triple quotes, although they are slightly different) you don;t need line continuation marks (\). > > for k in capitals.keys(): > state = input('Enter the capital of '+k+' :') > if state.upper() == capitals[k].upper(): > right += 1 > print('Correct') > else: > wrong += 1 > print('Incorrect') > choice = input('Do you want to play again y/n: ') > if choice.upper() == 'N': > print('end of game') > break > elif choice.upper() != 'Y': > print("invalid choice") > > print('Number of correct answers is: ', right) > print("Number of incorrect answers is:", wrong) -- 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 Tue Jun 2 18:17:09 2015 From: __peter__ at web.de (Peter Otten) Date: Tue, 02 Jun 2015 18:17:09 +0200 Subject: [Tutor] creating a dictionary for capital quiz program References: Message-ID: Alan Gauld wrote: > On 02/06/15 15:15, Peter Otten wrote: > >> Not an optimization, but if the user enters neither Y nor N you might ask >> again instead of assuming Y. > > He does. He only breaks if the user enters N > >>> choice = input('Do you want to play again y/n: ') >>> if choice.upper() == 'N': >>> print('end of game') >>> break >>> elif choice.upper() != 'Y': >>> print("invalid choice") > > Y goes round again silently. > Anything other than Y or N prints the error then tries again. ... with the next state. I meant that instead the question "Do you want to play again y/n:" should be repeated until there is a valid answer, either y or n. Current behaviour: $ python capitals.py Enter the capital of Mississippi :Jackson Correct Do you want to play again y/n: x invalid choice Enter the capital of Oklahoma : ... So "x" is a synonum for "n". Suggested behaviour: $ python capitals.py Enter the capital of Mississippi :Jackson Correct Do you want to play again y/n: x invalid choice Do you want to play again y/n: z invalid choice Do you want to play again y/n: n end of game ... From stephanie.quiles001 at albright.edu Tue Jun 2 18:25:25 2015 From: stephanie.quiles001 at albright.edu (Stephanie Quiles) Date: Tue, 2 Jun 2015 12:25:25 -0400 Subject: [Tutor] creating a dictionary for capital quiz program In-Reply-To: References: Message-ID: <1956C7A7-7CDC-4593-B870-65D78EFC0E43@albright.edu> What is the +k+ called? How exactly does it work? I'm a big confused on that... Stephanie Quiles Sent from my iPhone > On Jun 2, 2015, at 12:17 PM, Peter Otten <__peter__ at web.de> wrote: > > Alan Gauld wrote: > >>> On 02/06/15 15:15, Peter Otten wrote: >>> >>> Not an optimization, but if the user enters neither Y nor N you might ask >>> again instead of assuming Y. >> >> He does. He only breaks if the user enters N >> >>>> choice = input('Do you want to play again y/n: ') >>>> if choice.upper() == 'N': >>>> print('end of game') >>>> break >>>> elif choice.upper() != 'Y': >>>> print("invalid choice") >> >> Y goes round again silently. >> Anything other than Y or N prints the error then tries again. > > ... with the next state. I meant that instead the question "Do you want to > play again y/n:" should be repeated until there is a valid answer, either y > or n. > > Current behaviour: > > $ python capitals.py > Enter the capital of Mississippi :Jackson > Correct > Do you want to play again y/n: x > invalid choice > Enter the capital of Oklahoma : > ... > > So "x" is a synonum for "n". > > Suggested behaviour: > > $ python capitals.py > Enter the capital of Mississippi :Jackson > Correct > Do you want to play again y/n: x > invalid choice > Do you want to play again y/n: z > invalid choice > Do you want to play again y/n: n > end of game > ... > > > _______________________________________________ > 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 Jun 2 20:30:31 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 02 Jun 2015 19:30:31 +0100 Subject: [Tutor] creating a dictionary for capital quiz program In-Reply-To: References: Message-ID: On 02/06/15 17:17, Peter Otten wrote: >>>> choice = input('Do you want to play again y/n: ') >>>> if choice.upper() == 'N': >>>> print('end of game') >>>> break >>>> elif choice.upper() != 'Y': >>>> print("invalid choice") >> >> Y goes round again silently. >> Anything other than Y or N prints the error then tries again. > > ... with the next state. I meant that instead the question "Do you want to > play again y/n:" should be repeated until there is a valid answer, either y > or n. OK, I agree that it's a rad unconventional. I thought you thought he was just quitting with the error message. > Suggested behaviour: > > $ python capitals.py > Enter the capital of Mississippi :Jackson > Correct > Do you want to play again y/n: x > invalid choice > Do you want to play again y/n: z > invalid choice Yes this would be the normal idiom. -- 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 Jun 2 20:39:52 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 02 Jun 2015 19:39:52 +0100 Subject: [Tutor] creating a dictionary for capital quiz program In-Reply-To: <1956C7A7-7CDC-4593-B870-65D78EFC0E43@albright.edu> References: <1956C7A7-7CDC-4593-B870-65D78EFC0E43@albright.edu> Message-ID: On 02/06/15 17:25, Stephanie Quiles wrote: > What is the +k+ called? How exactly does it work? I'm a big confused on that... You seem to be replying to the wrong post. I assume you mean this one from Joel? ----------------- >> for k in capitals.keys(): >> state = input('Enter the capital of '+k+' :') The above statement won't print the name of the capital. try something like this: state = input('Enter the capital of' + k + ':') ------------------ The '+k+' isn't called anything per s. It's an example of string concatenation, and the only difference in Joel's rendition is the spacing, to clarify what's going on. (He may have misread your original code and thought it was in error?) Joel's version is easier to read, although it does lose some spaces in the prompt string. FWIW You could clarify it further by using better variable names such as: for state in capitals.keys(): guess = input('Enter the capital of ' + state +' :') Or you could have used string formatting: for state in capitals.keys(): guess = input('Enter the capital of %s:' % state) 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 s.shall at virginmedia.com Mon Jun 1 19:14:26 2015 From: s.shall at virginmedia.com (Sydney Shall) Date: Mon, 01 Jun 2015 18:14:26 +0100 Subject: [Tutor] unittest with random population data In-Reply-To: <20150531020052.GA44913@cskk.homeip.net> References: <55699BF1.5090704@virginmedia.com> <20150531020052.GA44913@cskk.homeip.net> Message-ID: <556C92F2.9010805@virginmedia.com> On 31/05/2015 03:00, Cameron Simpson wrote: > On 30May2015 12:16, Sydney Shall wrote: >> Following advice from you generous people, I have chosen a project >> >that interests me, to develop some knowledge of python. >> My projest is a simulation of a biological population. >> I have a base class and a simulation function, which uses instances of >> the class. >> This, after many months of work and lots of advice, now seems to work >> well. It generates sensible data and when I write a small test program >> it gives sensible output. >> Now I want to learn to use unittest. >> I have written a unittest class which works OK. >> But the problem I have is that because I use the random module to >> populate my initial arrays, my data is not strictly predictable even >> though I am using seed(0). So the tests return many *fails* because >> the numbers are not exactly correct, although they are all rather >> close, consistent with the sigma value I have chosen for the spread of >> my population. I do of course use *almostEqual* and not *Equal*. > > First of all, several people have posted suggestions for getting > identical results on every run. > > However, there is another approach, which you might consider. (And use > in addition, not inseadt of, the reproducable suggestions). > > It is all very well to have a unit test that runs exactly the same with > a test set of data - it lets you have confidence that algorithm changes > do not change the outcome. But on for that data set. > > You say that your results are "all rather close, consistent with the sigma > value I have chosen for the spread of my population". I would advocate > making some "contraint" tests that verify this property for _any_ input > data set. > > Then you can run with random and _changing_ input data sets to verify > that your code produces the expected _kind_ of results with many data sets. > > So you would have one test which ran with a fixed data set which > confirms preidctable unchanging results. And you have other tests with > run with randomly chosen data and confirms that outcomes fall within the > parameters you expect. You can apply those checks ("outcome in range") > to both sets of tests. > > As an exmaple, I have a few classes which maintain data structures which > are sensitive to boundary conditions. The glaring example is a numeric > range class which stores contiguous ranges efficiently (a sequence of > (low,high) pairs). It has a few add/remove operations which are meant to > maintain that sequence on ordered minimal form. cutting and merging > adjacent ranges is very easy to get wrong, very sensitive to off-by-one > logic errors. > > So my tests for this class include some random tests which do random > unpredictable add/remove operations, and run a consistency check on the > object after each operation. This gives me good odds of exercising some > tricky sequence which I have not considered explicitly myself. > > You can see the test suite here: > > https://bitbucket.org/cameron_simpson/css/src/tip/lib/python/cs/range_tests.py > > It has a bunch of explicit specific tests up the top, and then the > random consistency test down the bottom as "test30random_set_equivalence". > > Cheers, > Cameron Simpson > > MS-Word is Not a document exchange format - Jeff Goldberg > http://www.goldmark.org/netrants/no-word/attach.html > Cameron, Thanks for your most helpful reply. I have studied the material you indicated and it has been most helpful. I think that I have understood the principle involved, but I have had some problem implementing it. The range tests are mostly clear to me but there is one aspect I cannot follow. You use in this suite imports from Range, including Range, overlap, spans and Span. Are these programs that you have written? If so, are they specific to your set up or are they generic? If so, is it possible to obtain these programs? I have established a very primitive test suite based on your cs.range notions and it works fine, but it would be better, I am sure, to do it properly. Finally, I have one comment for the respected Moderator, if he is not out on a walk in the highlands in this cold and wet weather. I have taken the liberty of raising my problem here rather than elsewhere, because I have observed that the biological and bio-medical community, who always come late to new notions, is now rapidly discovering python. A great deal of work in these fields involve either stochastic simulations or statistical problems of analysis. The latter are more or less straight-forward, but the simulations are not. Thanks for all the help. You people are a model of how we could perhaps civilize humanity. -- Sydney From alan.gauld at btinternet.com Wed Jun 3 10:04:46 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 03 Jun 2015 09:04:46 +0100 Subject: [Tutor] unittest with random population data In-Reply-To: <556C92F2.9010805@virginmedia.com> References: <55699BF1.5090704@virginmedia.com> <20150531020052.GA44913@cskk.homeip.net> <556C92F2.9010805@virginmedia.com> Message-ID: On 01/06/15 18:14, Sydney Shall wrote: > Finally, I have one comment for the respected Moderator, if he is not > out on a walk in the highlands in this cold and wet weather. No, that's on tomorrow's schedule :-) > I have taken the liberty of raising my problem here rather than > elsewhere, because I have observed that the biological and bio-medical > community, who always come late to new notions, is now rapidly > discovering python. A great deal of work in these fields involve either > stochastic simulations or statistical problems of analysis. The latter > are more or less straight-forward, but the simulations are not. I have no problem with this kind of material on tutor because, although the list is for "beginners to Python", that includes those with much experience in other languages and who may expect to use TDD from the beginning. So TDD techniques using standard library modules is a valid topic even though it may be too advanced for those beginners who are new to programming. We need to balance coverage to cater for both categories of "beginner". -- 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 cs at zip.com.au Wed Jun 3 10:06:21 2015 From: cs at zip.com.au (Cameron Simpson) Date: Wed, 3 Jun 2015 18:06:21 +1000 Subject: [Tutor] unittest with random population data In-Reply-To: <556C92F2.9010805@virginmedia.com> References: <556C92F2.9010805@virginmedia.com> Message-ID: <20150603080621.GA65818@cskk.homeip.net> [ I've taken this discussion back to the tutor list. - Cameron ] On 01Jun2015 18:14, Sydney Shall wrote: >On 31/05/2015 03:00, Cameron Simpson wrote: >>You say that your results are "all rather close, consistent with the sigma >>value I have chosen for the spread of my population". I would advocate >>making some "contraint" tests that verify this property for _any_ input >>data set. >> >>Then you can run with random and _changing_ input data sets to verify >>that your code produces the expected _kind_ of results with many data sets. [...] >>range class which stores contiguous ranges efficiently (a sequence of >>(low,high) pairs). It has a few add/remove operations which are meant to >>maintain that sequence on ordered minimal form. cutting and merging >>adjacent ranges is very easy to get wrong, very sensitive to off-by-one >>logic errors. >> >>So my tests for this class include some random tests which do random >>unpredictable add/remove operations, and run a consistency check on the >>object after each operation. This gives me good odds of exercising some >>tricky sequence which I have not considered explicitly myself. >> >>You can see the test suite here: >> https://bitbucket.org/cameron_simpson/css/src/tip/lib/python/cs/range_tests.py > >I have studied the material you indicated and it has been most >helpful. I think that I have understood the principle involved, but I >have had some problem implementing it. > >The range tests are mostly clear to me but there is one aspect I >cannot follow. >You use in this suite imports from Range, including Range, overlap, >spans and Span. >Are these programs that you have written? If so, are they specific to >your set up or are they generic? If so, is it possible to obtain these >programs? The "cs.range" is a module of my own. As you might imagine, cs.range_tests has the entire purpose of testing cs.range. cs.range is here: https://bitbucket.org/cameron_simpson/css/src/tip/lib/python/cs/range.py Feel free. Since it in turn has some dependencies the easiest way to get it is to use "pip" to install it, as pip will also fetch and insteall its dependencies. But if you just want something to read, fetch and enjoy. >I have established a very primitive test suite based on your cs.range >notions and it works fine, but it would be better, I am sure, to do it >properly. There are many other people whose test writing ability surpasses mine. But you're welcome to learn anything you can from mine, and to ask questions. >Finally, I have one comment for the respected Moderator, if he is not >out on a walk in the highlands in this cold and wet weather. > >I have taken the liberty of raising my problem here rather than >elsewhere, because I have observed that the biological and bio-medical >community, who always come late to new notions, is now rapidly >discovering python. A great deal of work in these fields involve >either stochastic simulations or statistical problems of analysis. The >latter are more or less straight-forward, but the simulations are not. You might ask a separate question on the python-list at python.org about simulations. It has a wider audience than the tutor list and may well include people doing simulation work, or who know where to look. >Thanks for all the help. You people are a model of how we could >perhaps civilize humanity. Nah. We might all be striving to be a model of how humanity might be when civilised though... Cheers, Cameron Simpson You my man are a danger to society and should be taken out of society for all our sakes. As to what is done to you once removed I couldn't care less. - Roy G. Culley, Unix Systems Administrator From ilakumar at sas.upenn.edu Wed Jun 3 14:57:38 2015 From: ilakumar at sas.upenn.edu (Ila Kumar) Date: Wed, 3 Jun 2015 08:57:38 -0400 Subject: [Tutor] Trouble using bioread to convert files from .acq to .mat In-Reply-To: <201506020845.t528jTgm020498@fido.openend.se> References: <201506020845.t528jTgm020498@fido.openend.se> Message-ID: Laura, that was it! Thank you so much. However, now I am confused about what I need to type into the Command prompt window (on a 64-bit windows computer, using python 2.7) in order to convert a folder of data files. Does anyone know the proper code to do this? On Tue, Jun 2, 2015 at 4:45 AM, Laura Creighton wrote: > In a message of Mon, 01 Jun 2015 15:50:26 -0400, Ila Kumar writes: > >Hello, > > > >I am a new Python user attempting to use bioread ( > >https://pypi.python.org/pypi/bioread/0.9.5) to convert files from > >aqknowledge to matlab. I am using a 64-bit PC, and I have downloaded > >Matlab, Python, numpy, scipy and bioread. Can someone walk me through the > >installation process for this package? I can't seem to get it to work. > > > >Thank you so much for your help!! > >_______________________________________________ > >Tutor maillist - Tutor at python.org > >To unsubscribe or change subscription options: > >https://mail.python.org/mailman/listinfo/tutor > > You are getting something like: > Command python setup.py egg_info failed with error code 1 in > /tmp/pip-build-T3JieI/bioread > Storing debug log for failure in /home/lac/.pip/pip.log > > when you run pip, correct? > > So you go read the package documentation and discover that bioread > uses easy_install (which you are beginning to learn to hate) instead of > pip. > > So then you try that and you get crud like this: > .... > File "/usr/lib/python2.7/dist-packages/setuptools/sandbox.py", line 43, > in _execfile > exec(code, globals, locals) > File "/tmp/easy_install-PGpger/bioread-0.9.5/setup.py", line 3, in > > ImportError: No module named ez_setup > > Correct? > > If this is your problem, go install this package: > > https://pypi.python.org/pypi/ez_setup > > And then install bioread, still with easy_install > > If this isn't your problem, > write back with more of what is not working, please. > > Hope this is it :) > Laura > > From alan.gauld at btinternet.com Wed Jun 3 18:18:06 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 03 Jun 2015 17:18:06 +0100 Subject: [Tutor] Trouble using bioread to convert files from .acq to .mat In-Reply-To: References: <201506020845.t528jTgm020498@fido.openend.se> Message-ID: On 03/06/15 13:57, Ila Kumar wrote: > However, now I am confused about what I need to type into the Command > prompt window (on a 64-bit windows computer, using python 2.7) in order to > convert a folder of data files. Does anyone know the proper code to do this? You will need to give us a lot more detail than that to help you. Convert what kind of data file? To what kind of output file? Also for most such tasks you won;t be typing it at the prompt you will be writing a script and executing that. Do you have any experience of Python scripting/programming? If not you should find a tutorial and follow that. If you know how to program in another language then the official web site tutorial should be just fine. If you are a complete beginner to programming try one of these: https://wiki.python.org/moin/BeginnersGuide/NonProgrammers Or try mine (see link below)... The code you need could be as simple as ################# import os def convertFile(fname): # your code to do the conversion goes here dir = /your/folder/path/here for fileName in os.listdir(dir): convertFile(fileName) ################## But if there are subfolders to consider, or errors to handle, then it all gets more messy quite quickly. -- 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 chrisstinemetz at gmail.com Wed Jun 3 18:39:34 2015 From: chrisstinemetz at gmail.com (Chris Stinemetz) Date: Wed, 3 Jun 2015 11:39:34 -0500 Subject: [Tutor] dictionary of lists Message-ID: I am trying to create a dictionary of lists as I read a file. I envision it looking like: {key: [float_type],[string_type]} For the first item in the list I am trying to add the value to the existing value where the key matches but I am getting the following error: Resetting execution engine Running C:\Users\cs062x\Desktop\python\projects\PanHandle\PanHandle\PanHandle.py The Python REPL process has exited Traceback (most recent call last): File "C:\Users\cs062x\Desktop\python\projects\PanHandle\PanHandle\PanHandle.py", line 22, in d[IMEI] += Elapsed_Mins TypeError: 'float' object is not iterable Here is the code. My question is how can I keep it list type and just sumup the first element in the list as I read it? d = defaultdict(list) for fname in os.listdir('.'): with open (fname) as csvfile: spamreader = csv.reader(csvfile, delimiter=',', quotechar='|') next(spamreader) for row in spamreader: if row[8]: device = row[36] Elapsed_Mins = float(row[7]) IMEI = row[8].replace("'", "") d[IMEI] += Elapsed_Mins ## this is where the error occurs. Thanks in advance, Chris From grey.eric at gmail.com Wed Jun 3 18:49:11 2015 From: grey.eric at gmail.com (Eric Grey) Date: Wed, 3 Jun 2015 12:49:11 -0400 Subject: [Tutor] FTP GET from Variables Stored in File Message-ID: I'm fairly new to programming and as a result, Python too. I've been researching the Tutor archives trying to find a solution to my need, however, haven't stumbled across the exact example and are now in information overload. Wondering if I could get some help? I have the need to perform an FTP GET for specific files in a large directory of files. There are many examples out there of FTP'ing from a server after doing the equivalent to a Unix 'ls -la' command and thus, getting all files in the directory or matching on a pattern (i.e., all files ending with *.txt). My problem is I don't have files with a clear pattern of association to allow a pattern match. For example I have 1000 files in a directly with file names like: apple.txt, blue.txt, car.txt, sky.rtf, etc. I know the filenames I want, however it could be say 75 of 1000 files I need to issue a GET on. Inefficient to individually code all 75 explicit file name declarations in a script. So I have the name of each file (i.e., apple.txt, blue.txt) in a separate "seed file" that I want the script to read in and treat each line of the "seed file" as the variable I want to request the FTP GET on. So something like: seedfile.txt contents = apple.com, blue.com. car.txt Open FTP CD Read "seedfile.txt" For each line in "seedfile.txt" use the line as the variable and issue FTP GET on that variable Repeat till end of "sendfile.txt" quit. Thoughts? Help? Thanks. //eric From richkappler at gmail.com Wed Jun 3 21:10:42 2015 From: richkappler at gmail.com (richard kappler) Date: Wed, 3 Jun 2015 15:10:42 -0400 Subject: [Tutor] string delimiters Message-ID: for formatting a string and adding descriptors: test = 'datetimepart1part2part3the_rest' newtest = 'date=' + test[0:4] + ' time=' + test[4:8] + ' part1=' + test[8:13] + ' part2=' + test[13:18] + ' part3=' + test[18:23] + ' the rest=' + test[23:] and while this may be ugly, it does what I want it to do. The question is, if instead of 'the_rest' I have ']the_rest' and sometimes there's not just one. how do I handle that? In other words, this script will iterate over numerous lines in a file, and each one is identical up to the delimiter before the rest, and sometimes there is only one, sometimes there is two, they vary in length. Can I stop using position numbers and start looking for specific characters (the delimiter) and proceed to the end (which is always a constant string btw). regards, Richard -- Windows assumes you are an idiot?Linux demands proof. From alan.gauld at btinternet.com Wed Jun 3 21:53:14 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 03 Jun 2015 20:53:14 +0100 Subject: [Tutor] string delimiters In-Reply-To: References: Message-ID: On 03/06/15 20:10, richard kappler wrote: > for formatting a string and adding descriptors: > > test = 'datetimepart1part2part3the_rest' If this is really about parsing dates and times have you looked at the datetime module and its parsing/formatting functions (ie strptime/strftime)? > Can I stop using position numbers and start looking for specific characters > (the delimiter) and proceed to the end (which is always a constant string > btw). The general answer is probably to look at regular expressions. But they get messy fast so usually I'd suggest trying regular string searches/replaces and splits first. But if your pattern is genuinely complex and variable then regex may be the right solution. But if its dates check the strptime() functions first. -- 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 Jun 3 21:58:45 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 03 Jun 2015 20:58:45 +0100 Subject: [Tutor] FTP GET from Variables Stored in File In-Reply-To: References: Message-ID: On 03/06/15 17:49, Eric Grey wrote: > declarations in a script. So I have the name of each file (i.e., > apple.txt, blue.txt) in a separate "seed file" that I want the script to > read in and treat each line of the "seed file" as the variable I want to > request the FTP GET on. > > So something like: > seedfile.txt contents = apple.com, blue.com. car.txt > Open FTP > CD > Read "seedfile.txt" > For each line in "seedfile.txt" use the line as the variable and issue FTP > GET on that variable > Repeat till end of "sendfile.txt" > quit. > > Thoughts? Help? Yes that looks like a sensible approach and is almost Python. What bits of it are you struggling with? Convert your pseudo code into Python code and show us what breaks. Let me do one step towards that for you... Open FTP FTP.CD with open("seedfile.txt") as filenames: for name in filenames: FTP.GET(name.strip()) Close FTP Can you fill in the blanks? -- 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 Jun 3 22:15:26 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 03 Jun 2015 21:15:26 +0100 Subject: [Tutor] dictionary of lists In-Reply-To: References: Message-ID: On 03/06/15 17:39, Chris Stinemetz wrote: > I am trying to create a dictionary of lists as I read a file. I > envision it looking like: {key: [float_type],[string_type]} Thats not a dictionary of lists. You maybe mean: {key: [[float_type],[string_type]]} Which is a dictionary of lists of lists? > For the first item in the list I am trying to add the value to the > existing value where the key matches Sorry, I'm sure that made sense to you but not to me. Which value are you adding to which existing value? Can you give a before/after example? > Resetting execution engine > Running C:\Users\cs062x\Desktop\python\projects\PanHandle\PanHandle\PanHandle.py > The Python REPL process has exited That's slightly unusual. How are you running this? > Traceback (most recent call last): > File "C:\Users\cs062x\Desktop\python\projects\PanHandle\PanHandle\PanHandle.py", > line 22, in > d[IMEI] += Elapsed_Mins > TypeError: 'float' object is not iterable > d = defaultdict(list) > for fname in os.listdir('.'): > with open (fname) as csvfile: > spamreader = csv.reader(csvfile, delimiter=',', quotechar='|') > next(spamreader) > for row in spamreader: > > if row[8]: > device = row[36] > Elapsed_Mins = float(row[7]) > IMEI = row[8].replace("'", "") So IMEA is a string and Elapsed_Mins is a float and d is a default dict that sets its defaults to lists. > d[IMEI] += Elapsed_Mins ## this is where the error occurs. So this is trying to add a float to a list. >>> L = [] >>> L += f Traceback (most recent call last): File "", line 1, in TypeError: 'float' object is not iterable look familiar? Now, what I don't know, is what you are trying to do. Are you trying to append the float to the list? Or to replace the list with the float? Or to add the float to the value of the first(or last?) element in the list - if it exists (and if it doesn't? Then what?) -- 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 richkappler at gmail.com Wed Jun 3 22:13:03 2015 From: richkappler at gmail.com (richard kappler) Date: Wed, 3 Jun 2015 16:13:03 -0400 Subject: [Tutor] string delimiters In-Reply-To: References: Message-ID: I was trying to keep it simple, you'd think by now I'd know better. My fault and my apology. It's definitely not all dates and times, the data and character types vary. This is the output from my log parser script which you helped on the other day. there are essentially two types of line: Tue Jun 2 10:22:42 2015SE201506012200310389PS01CT1407166S0011.40009.00007.6IN 000000000018.1LB000258]C10259612019466862270088094]L0223PDF Tue Jun 2 10:22:43 2015SE0389icdim01307755C0038.20033.20012.0IN1000000000 0032]C10259612804038813568089577 I have to do several things: the first type can be of variable length, everything after the ] is an identifier that I have to separate, some lines have one, some have more than one, variable length, always delimited by a ] the second type (line 2) doesn't have the internal datetime stamp, so I just need to add 14 x's to fill in the space where that date time stamp would be. and finally, I have to break these apart and put a descriptor with each. While I was waiting for a response to this, I put together a script to start figuring things out (what could possibly go wrong?!?!?! :-) ) and I can't post the exact script but the following is the guts of it: f1 = open('unformatted.log', 'r') f2 = open('formatted.log', 'a') for line in f1: for tag in ("icdm"): if tag in line: newline = 'log datestamp:' + line[0:24] # + and so on to format the lines with icdm in them including adding 14 x's for the missing timestamp f2.write(newline) #write the formatted output to the new log else: newline = 'log datestamp:' + line[0:24] # + and so on to format the non-icdm lines f2.write(newline) The problems are: 1. for some reason this iterates over the 24 line file 5 times, and it writes the 14 x's to every file, so my non-icdm code (the else:) isn't getting executed. I'm missing something basic and obvious but have no idea what. 2. I still don't know how to handle the differences in the end of the non-icdm files (potentially more than identifier ] delimited as described above). regards, Richard On Wed, Jun 3, 2015 at 3:53 PM, Alan Gauld wrote: > On 03/06/15 20:10, richard kappler wrote: > >> for formatting a string and adding descriptors: >> >> test = 'datetimepart1part2part3the_rest' >> > > If this is really about parsing dates and times have > you looked at the datetime module and its parsing/formatting > functions (ie strptime/strftime)? > > Can I stop using position numbers and start looking for specific >> characters >> (the delimiter) and proceed to the end (which is always a constant string >> btw). >> > > The general answer is probably to look at regular expressions. > But they get messy fast so usually I'd suggest trying regular > string searches/replaces and splits first. > > But if your pattern is genuinely complex and variable then > regex may be the right solution. > > But if its dates check the strptime() functions first. > > > -- > 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 > -- Windows assumes you are an idiot?Linux demands proof. From richkappler at gmail.com Wed Jun 3 22:23:37 2015 From: richkappler at gmail.com (richard kappler) Date: Wed, 3 Jun 2015 16:23:37 -0400 Subject: [Tutor] string delimiters In-Reply-To: References: Message-ID: hold the phone!!!! I have no idea why it worked, would love an explanation, but I changed my previous test script by eliminating for tag in ("icdm"): and changing if tag in line to if 'icdm' in line: and it works perfectly! It only iterates over the file once, and the else executes so both types of lines format correctly except for the multiple identifiers in the non-icdm lines I could still use some help with that bit, please. regards, Richard On Wed, Jun 3, 2015 at 4:13 PM, richard kappler wrote: > I was trying to keep it simple, you'd think by now I'd know better. My > fault and my apology. > > It's definitely not all dates and times, the data and character types > vary. This is the output from my log parser script which you helped on the > other day. there are essentially two types of line: > > Tue Jun 2 10:22:42 2015 name="SE">SE201506012200310389PS01CT1407166S0011.40009.00007.6IN > 000000000018.1LB000258]C10259612019466862270088094]L0223PDF > Tue Jun 2 10:22:43 2015 name="SE">SE0389icdim01307755C0038.20033.20012.0IN1000000000 > 0032]C10259612804038813568089577 > > I have to do several things: > the first type can be of variable length, everything after the ] is an > identifier that I have to separate, some lines have one, some have more > than one, variable length, always delimited by a ] > the second type (line 2) doesn't have the internal datetime stamp, so I > just need to add 14 x's to fill in the space where that date time stamp > would be. > > and finally, I have to break these apart and put a descriptor with each. > > While I was waiting for a response to this, I put together a script to > start figuring things out (what could possibly go wrong?!?!?! :-) ) > > and I can't post the exact script but the following is the guts of it: > > f1 = open('unformatted.log', 'r') > f2 = open('formatted.log', 'a') > > for line in f1: > for tag in ("icdm"): > if tag in line: > newline = 'log datestamp:' + line[0:24] # + and so on to > format the lines with icdm in them including adding 14 x's for the missing > timestamp > f2.write(newline) #write the formatted output to the new log > else: > newline = 'log datestamp:' + line[0:24] # + and so on to > format the non-icdm lines > f2.write(newline) > > The problems are: > 1. for some reason this iterates over the 24 line file 5 times, and it > writes the 14 x's to every file, so my non-icdm code (the else:) isn't > getting executed. I'm missing something basic and obvious but have no idea > what. > 2. I still don't know how to handle the differences in the end of the > non-icdm files (potentially more than identifier ] delimited as described > above). > > regards, Richard > > On Wed, Jun 3, 2015 at 3:53 PM, Alan Gauld > wrote: > >> On 03/06/15 20:10, richard kappler wrote: >> >>> for formatting a string and adding descriptors: >>> >>> test = 'datetimepart1part2part3the_rest' >>> >> >> If this is really about parsing dates and times have >> you looked at the datetime module and its parsing/formatting >> functions (ie strptime/strftime)? >> >> Can I stop using position numbers and start looking for specific >>> characters >>> (the delimiter) and proceed to the end (which is always a constant >>> string >>> btw). >>> >> >> The general answer is probably to look at regular expressions. >> But they get messy fast so usually I'd suggest trying regular >> string searches/replaces and splits first. >> >> But if your pattern is genuinely complex and variable then >> regex may be the right solution. >> >> But if its dates check the strptime() functions first. >> >> >> -- >> 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 >> > > > > -- > > Windows assumes you are an idiot?Linux demands proof. > -- Windows assumes you are an idiot?Linux demands proof. From alan.gauld at btinternet.com Wed Jun 3 22:31:30 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 03 Jun 2015 21:31:30 +0100 Subject: [Tutor] string delimiters In-Reply-To: References: Message-ID: <556F6422.2040404@btinternet.com> On 03/06/15 21:23, richard kappler wrote: > hold the phone!!!! > > I have no idea why it worked, would love an explanation, but I changed > my previous test script by eliminating > > for tag in ("icdm"): This loops over the string assigning the characters i,c,d and m to tag > if 'icdm' in line: This checks if the 4 character string 'icdm' is in the line. Completely different. -- 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 Jun 3 22:29:48 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 03 Jun 2015 21:29:48 +0100 Subject: [Tutor] string delimiters In-Reply-To: References: Message-ID: <556F63BC.4080409@btinternet.com> On 03/06/15 21:13, richard kappler wrote: > I was trying to keep it simple, you'd think by now I'd know better. My > fault and my apology. > > It's definitely not all dates and times, the data and character types > vary. This is the output from my log parser script which you helped on > the other day. there are essentially two types of line: > > Tue Jun 2 10:22:42 2015 name="SE">SE201506012200310389PS01CT1407166S0011.40009.00007.6IN > 000000000018.1LB000258]C10259612019466862270088094]L0223PDF > Tue Jun 2 10:22:43 2015 name="SE">SE0389icdim01307755C0038.20033.20012.0IN1000000000 > 0032]C10259612804038813568089577 > > I have to do several things: > the first type can be of variable length, everything after the ] is an > identifier that I have to separate, some lines have one, some have > more than one, variable length, always delimited by a ] So why not just split by ']'? identifiers = line.split(']')[1:] # lose the first one > and finally, I have to break these apart and put a descriptor with each. > Nope. I don't understand that. Break what apart? and how do you 'put a descriptor with each'? What is a descriptor for that matter?! > While I was waiting for a response to this, I put together a script to > start figuring things out (what could possibly go wrong?!?!?! :-) ) > > and I can't post the exact script but the following is the guts of it: > > f1 = open('unformatted.log', 'r') > f2 = open('formatted.log', 'a') > > for line in f1: > for tag in ("icdm"): > if tag in line: > newline = 'log datestamp:' + line[0:24] # + and so on to > format the lines with icdm in them including adding 14 x's for the > missing timestamp > f2.write(newline) #write the formatted output to the new log > else: > newline = 'log datestamp:' + line[0:24] # + and so on to > format the non-icdm lines > f2.write(newline) > So this checks each line for the 4 tags: i,c,d and m. if the tag is in the line it does the if clause, including writing to f2 If the tag is not in the line it does the else which also writes to f2. So you always write 4 lines to f2. Is that correct? > The problems are: > 1. for some reason this iterates over the 24 line file 5 times, and it > writes the 14 x's to every file, so my non-icdm code (the else:) isn't > getting executed. I'm missing something basic and obvious but have no > idea what. That's not what I'd expect. I'd expect it to write 4 lines out for every input line. What gets written depending on however many of the 4 tags are found in the line. Since we only have partial code we don't know what the formatted lines look like. > 2. I still don't know how to handle the differences in the end of the > non-icdm files (potentially more than identifier ] delimited as > described above). I'm not clear on this yet either. I suspect that once you clarify what you are trying to do you will know how to do 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 richkappler at gmail.com Wed Jun 3 22:37:52 2015 From: richkappler at gmail.com (richard kappler) Date: Wed, 3 Jun 2015 16:37:52 -0400 Subject: [Tutor] string delimiters In-Reply-To: <556F6422.2040404@btinternet.com> References: <556F6422.2040404@btinternet.com> Message-ID: figured that out from your last post, and thank you, now I understand how that works. I thought I was looking for the entire string, not each character. That bit all makes sense now. A descriptor is, for example, for the following part of a string '0032.4' the descriptor would be weight, so the formatted output would be weight:0032.4, and so on. each bit of the strings in the post where I provided the two examples has specific meaning, and I have to parse the lines so that I add a descriptor (okay, bad word, what should I use?) to each bit of data from the line. At the moment I'm doing it by position, which is, I'm sure, a really bad way to do it, but I need this quickly and don't know enough to know if there is a better way. I have to parse and output the entire line, but there are, as I said, two 'types' of string and some are variable in length. I'm eager for direction. What other information would better help explain? regards, Richard On Wed, Jun 3, 2015 at 4:31 PM, Alan Gauld wrote: > On 03/06/15 21:23, richard kappler wrote: > >> hold the phone!!!! >> >> I have no idea why it worked, would love an explanation, but I changed my >> previous test script by eliminating >> >> for tag in ("icdm"): >> > > This loops over the string assigning the characters i,c,d and m to tag > > if 'icdm' in line: >> > > This checks if the 4 character string 'icdm' is in the line. > Completely different. > > > -- > 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 > > -- Windows assumes you are an idiot?Linux demands proof. From akleider at sonic.net Wed Jun 3 23:16:09 2015 From: akleider at sonic.net (Alex Kleider) Date: Wed, 03 Jun 2015 14:16:09 -0700 Subject: [Tutor] string delimiters In-Reply-To: References: Message-ID: <5fe5d767cd5b2c5444a5c8f24787af72@sonic.net> On 2015-06-03 12:53, Alan Gauld wrote: ... > If this is really about parsing dates and times have > you looked at the datetime module and its parsing/formatting > functions (ie strptime/strftime)? I asssume strftime gets its name from 'string from time.' What about strptime? How did that get its name? From richkappler at gmail.com Wed Jun 3 23:35:54 2015 From: richkappler at gmail.com (richard kappler) Date: Wed, 3 Jun 2015 17:35:54 -0400 Subject: [Tutor] string delimiters In-Reply-To: <5fe5d767cd5b2c5444a5c8f24787af72@sonic.net> References: <5fe5d767cd5b2c5444a5c8f24787af72@sonic.net> Message-ID: Perhaps the better way for me to have asked this question would have been: How can I find the location within a string of every instance of a character such as ']'? regards, Richard On Wed, Jun 3, 2015 at 5:16 PM, Alex Kleider wrote: > On 2015-06-03 12:53, Alan Gauld wrote: > ... > >> If this is really about parsing dates and times have >> you looked at the datetime module and its parsing/formatting >> functions (ie strptime/strftime)? >> > > I asssume strftime gets its name from 'string from time.' > What about strptime? How did that get its name? > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Windows assumes you are an idiot?Linux demands proof. From __peter__ at web.de Thu Jun 4 00:00:57 2015 From: __peter__ at web.de (Peter Otten) Date: Thu, 04 Jun 2015 00:00:57 +0200 Subject: [Tutor] string delimiters References: <5fe5d767cd5b2c5444a5c8f24787af72@sonic.net> Message-ID: richard kappler wrote: > Perhaps the better way for me to have asked this question would have been: > > How can I find the location within a string of every instance of a > character such as ']'? >>> import re >>> s = "alpha]beta]gamma]delta" >>> [m.start() for m in re.finditer(r"]", s)] [5, 10, 16] But do you really need these locations? Why not just split() as in >>> s.split("]") ['alpha', 'beta', 'gamma', 'delta'] From breamoreboy at yahoo.co.uk Thu Jun 4 00:13:24 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 03 Jun 2015 23:13:24 +0100 Subject: [Tutor] string delimiters In-Reply-To: <5fe5d767cd5b2c5444a5c8f24787af72@sonic.net> References: <5fe5d767cd5b2c5444a5c8f24787af72@sonic.net> Message-ID: On 03/06/2015 22:16, Alex Kleider wrote: > On 2015-06-03 12:53, Alan Gauld wrote: > ... >> If this is really about parsing dates and times have >> you looked at the datetime module and its parsing/formatting >> functions (ie strptime/strftime)? > > I asssume strftime gets its name from 'string from time.' > What about strptime? How did that get its name? > 'f' for format, 'p' for parse, having originally come from plain old C. More here https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior As Alan has hinted at earlier in this thread, if you're using dates and/or times it's certainly far easier to use the built-in functions rather than try to roll your own. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From akleider at sonic.net Thu Jun 4 00:19:10 2015 From: akleider at sonic.net (Alex Kleider) Date: Wed, 03 Jun 2015 15:19:10 -0700 Subject: [Tutor] string delimiters In-Reply-To: References: <5fe5d767cd5b2c5444a5c8f24787af72@sonic.net> Message-ID: On 2015-06-03 15:13, Mark Lawrence wrote: > 'f' for format, 'p' for parse, having originally come from plain old > C. More here > https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior So I was wrong about the 'f' as well as having no clue about the 'p'! Thank you very much for clearing that up for me. cheers, Alex From chrisstinemetz at gmail.com Wed Jun 3 22:39:49 2015 From: chrisstinemetz at gmail.com (Chris Stinemetz) Date: Wed, 3 Jun 2015 15:39:49 -0500 Subject: [Tutor] dictionary of lists In-Reply-To: References: Message-ID: > >> Resetting execution engine >> Running >> C:\Users\cs062x\Desktop\python\projects\PanHandle\PanHandle\PanHandle.py >> The Python REPL process has exited > > > That's slightly unusual. How are you running this? > I am running it with Microsoft Visual Studio Community 2013 using Python Tools for Visual Studio > > Now, what I don't know, is what you are trying to do. > Are you trying to append the float to the list? > Or to replace the list with the float? > Or to add the float to the value of the first(or last?) > element in the list - if it exists > (and if it doesn't? Then what?) > > Although I am certain it is not very efficient I was able to accomplish what I wanted with the following code I wrote: import os import pprint import csv from collections import defaultdict print_map = {'MOU':0, 'Call_Att':1, 'Device':2} header = ['IMEI','MOUs','Call_Att','Device'] path = 'C:/Users/cs062x/Desktop/Panhandle' os.chdir(path) running_MOU = {} call_attempts = {} d = defaultdict(list) for fname in os.listdir('.'): with open (fname) as csvfile: spamreader = csv.reader(csvfile, delimiter=',', quotechar='|') next(spamreader) for row in spamreader: if row[8]: device = row[36] Elapsed_Mins = float(row[7]) IMEI = row[8].replace("'", "") if IMEI in running_MOU.keys(): running_MOU[IMEI] += Elapsed_Mins else: running_MOU[IMEI] = Elapsed_Mins if IMEI in call_attempts.keys(): call_attempts[IMEI] += 1 else: call_attempts[IMEI] = 1 # if key matches append mou else append 0. d[IMEI] = [running_MOU[IMEI]] d[IMEI].append([call_attempts[IMEI]]) d[IMEI].append([device]) print ",".join(header) for k,v in sorted(d.items()): print k, ",", d[k][print_map['MOU']],",", d[k][print_map['Call_Att']][0],",", d[k][print_map['Device']][0] print "complete" From alan.gauld at btinternet.com Thu Jun 4 01:57:01 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 04 Jun 2015 00:57:01 +0100 Subject: [Tutor] string delimiters In-Reply-To: <5fe5d767cd5b2c5444a5c8f24787af72@sonic.net> References: <5fe5d767cd5b2c5444a5c8f24787af72@sonic.net> Message-ID: On 03/06/15 22:16, Alex Kleider wrote: > On 2015-06-03 12:53, Alan Gauld wrote: > ... >> If this is really about parsing dates and times have >> you looked at the datetime module and its parsing/formatting >> functions (ie strptime/strftime)? > > I asssume strftime gets its name from 'string from time.' > What about strptime? How did that get its name? f = format - for creating date/time strings p = parse - for extracting date/time fierlds from a string -- 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 cs at zip.com.au Thu Jun 4 02:45:21 2015 From: cs at zip.com.au (Cameron Simpson) Date: Thu, 4 Jun 2015 10:45:21 +1000 Subject: [Tutor] string delimiters In-Reply-To: <5fe5d767cd5b2c5444a5c8f24787af72@sonic.net> References: <5fe5d767cd5b2c5444a5c8f24787af72@sonic.net> Message-ID: <20150604004521.GA92171@cskk.homeip.net> On 03Jun2015 14:16, Alex Kleider wrote: >On 2015-06-03 12:53, Alan Gauld wrote: >... >>If this is really about parsing dates and times have >>you looked at the datetime module and its parsing/formatting >>functions (ie strptime/strftime)? > >I asssume strftime gets its name from 'string from time.' >What about strptime? How did that get its name? No, they both come from the standard C library functions of the same names, being "(f)ormat a time as a string" and "(p)arse a time from a string". The shape of the name is because they're "str"ing related functions, hence the prefix. See "man 3 strptime" and "man 3 strftime". Cheers, Cameron Simpson A program in conformance will not tend to stay in conformance, because even if it doesn't change, the standard will. - Norman Diamond From cs at zip.com.au Thu Jun 4 02:54:27 2015 From: cs at zip.com.au (Cameron Simpson) Date: Thu, 4 Jun 2015 10:54:27 +1000 Subject: [Tutor] string delimiters In-Reply-To: References: Message-ID: <20150604005427.GA20424@cskk.homeip.net> On 03Jun2015 17:35, richard kappler wrote: >Perhaps the better way for me to have asked this question would have been: > >How can I find the location within a string of every instance of a >character such as ']'? With the str.find method! s = 'a]b]c' pos = s.find(']') while pos >= 0: print("pos =", pos) pos = s.find(']', pos + 1) Obviously you could recast that as a generator funciton yielding positions for general purpose use. Cheers, Cameron Simpson Serious error. All shortcuts have disappeared. Screen. Mind. Both are blank. - Haiku Error Messages http://www.salonmagazine.com/21st/chal/1998/02/10chal2.html From richkappler at gmail.com Thu Jun 4 04:37:18 2015 From: richkappler at gmail.com (richard kappler) Date: Wed, 3 Jun 2015 22:37:18 -0400 Subject: [Tutor] line iteration in a file Message-ID: Figured out the string delimiters problem, thanks for all the help. Now I've run into another. I've used the re.finditer that I think it was Peter suggested. So I have: for line in file: s = line t = [m.start() for m in re.finditer(r"]", s)] q = len(t) which works fine, in testing it finds the number and position of the ]'s in any line I throw at it. I then wrote a series of if/elif statements based on q, in other words if q == 1: do something elif q == 2: do something else elif q == 3: do a third thing else: pass as I looked through enough example to figure out that the most ]'s I can have is 3, but the pass is there just in case. I keep getting a list index out of range error, and my best guess is that it's because t and q are set on the first line read, not each line read, is that right? If not, what might be the problem and either way, how do I fix it? regards, Richard who is proving to his Linux box that he is an idiot pretty regularly -- Windows assumes you are an idiot?Linux demands proof. From cs at zip.com.au Thu Jun 4 05:09:33 2015 From: cs at zip.com.au (Cameron Simpson) Date: Thu, 4 Jun 2015 13:09:33 +1000 Subject: [Tutor] line iteration in a file In-Reply-To: References: Message-ID: <20150604030933.GA10852@cskk.homeip.net> On 03Jun2015 22:37, richard kappler wrote: >Figured out the string delimiters problem, thanks for all the help. Now >I've run into another. > >I've used the re.finditer that I think it was Peter suggested. So I have: > >for line in file: > s = line > t = [m.start() for m in re.finditer(r"]", s)] > q = len(t) > >which works fine, in testing it finds the number and position of the ]'s in >any line I throw at it. I then wrote a series of if/elif statements based >on q, in other words > >if q == 1: > do something >elif q == 2: > do something else >elif q == 3: > do a third thing >else: > pass > >as I looked through enough example to figure out that the most ]'s I can >have is 3, but the pass is there just in case. > >I keep getting a list index out of range error, and my best guess is that >it's because t and q are set on the first line read, not each line read, is >that right? If not, what might be the problem and either way, how do I fix >it? Please post a self contained example (i.e. small complete code, not snippets) and a transcribe of the full error message with stack backtrace. What you have above is not enough to figure out what is going wrong. If what you display above is accurate then t and q are set for every line read. Another remark, what is the use of your "else: pass" code? Normally one would put some action here, such as raising an exception for the unhandled value or issuing a warning. Cheers, Cameron Simpson My computer always does exactly what I tell it to do but sometimes I have trouble finding out what it was that I told it to do. - Dick Wexelblat From __peter__ at web.de Thu Jun 4 09:30:56 2015 From: __peter__ at web.de (Peter Otten) Date: Thu, 04 Jun 2015 09:30:56 +0200 Subject: [Tutor] dictionary of lists References: Message-ID: Chris Stinemetz wrote: > Although I am certain it is not very efficient I was able to > accomplish what I wanted with the following code I wrote: > > import os > import pprint > import csv > from collections import defaultdict > > print_map = {'MOU':0, 'Call_Att':1, 'Device':2} > header = ['IMEI','MOUs','Call_Att','Device'] > > path = 'C:/Users/cs062x/Desktop/Panhandle' > > os.chdir(path) > running_MOU = {} > call_attempts = {} > d = defaultdict(list) > for fname in os.listdir('.'): > with open (fname) as csvfile: > spamreader = csv.reader(csvfile, delimiter=',', quotechar='|') > next(spamreader) > for row in spamreader: > > if row[8]: > device = row[36] > Elapsed_Mins = float(row[7]) > IMEI = row[8].replace("'", "") > > if IMEI in running_MOU.keys(): For big dicts in Python 2 the test key in some_dict.keys() is indeed very inefficient as it builds a list of keys first and then performs a linear scan for the key. Much better: key in some_dict This test avoids building the list and can also use an efficient lookup algorithm that is independent of the size of the dict. > running_MOU[IMEI] += Elapsed_Mins > else: > running_MOU[IMEI] = Elapsed_Mins > > if IMEI in call_attempts.keys(): > call_attempts[IMEI] += 1 > else: > call_attempts[IMEI] = 1 > > # if key matches append mou else append 0. > d[IMEI] = [running_MOU[IMEI]] > d[IMEI].append([call_attempts[IMEI]]) > d[IMEI].append([device]) > > > print ",".join(header) > for k,v in sorted(d.items()): > print k, ",", d[k][print_map['MOU']],",", > d[k][print_map['Call_Att']][0],",", d[k][print_map['Device']][0] > > print "complete" Here's an alternative that uses only one dict: import csv import os import sys header = ['IMEI', 'MOUs', 'Call_Att', 'Device'] path = 'C:/Users/cs062x/Desktop/Panhandle' d = {} for fname in os.listdir(path): with open(os.path.join(path, fname)) as csvfile: spamreader = csv.reader(csvfile, delimiter=',', quotechar='|') next(spamreader) for row in spamreader: if row[8]: device = row[36] elapsed_mins = float(row[7]) IMEI = row[8].replace("'", "") if IMEI in d: record = d[IMEI] record[1] += elapsed_mins record[2] += 1 else: d[IMEI] = [IMEI, elapsed_mins, 1, device] writer = csv.writer(sys.stdout) writer.writerow(header) writer.writerows(sorted(d.itervalues())) print "complete" From chrisstinemetz at gmail.com Thu Jun 4 15:46:00 2015 From: chrisstinemetz at gmail.com (Chris Stinemetz) Date: Thu, 4 Jun 2015 08:46:00 -0500 Subject: [Tutor] dictionary of lists In-Reply-To: References: Message-ID: On Thu, Jun 4, 2015 at 2:30 AM, Peter Otten <__peter__ at web.de> wrote: > Chris Stinemetz wrote: > >> Although I am certain it is not very efficient I was able to >> accomplish what I wanted with the following code I wrote: >> >> import os >> import pprint >> import csv >> from collections import defaultdict >> >> print_map = {'MOU':0, 'Call_Att':1, 'Device':2} >> header = ['IMEI','MOUs','Call_Att','Device'] >> >> path = 'C:/Users/cs062x/Desktop/Panhandle' >> >> os.chdir(path) >> running_MOU = {} >> call_attempts = {} >> d = defaultdict(list) >> for fname in os.listdir('.'): >> with open (fname) as csvfile: >> spamreader = csv.reader(csvfile, delimiter=',', quotechar='|') >> next(spamreader) >> for row in spamreader: >> >> if row[8]: >> device = row[36] >> Elapsed_Mins = float(row[7]) >> IMEI = row[8].replace("'", "") >> >> if IMEI in running_MOU.keys(): > > For big dicts in Python 2 the test > > key in some_dict.keys() > > is indeed very inefficient as it builds a list of keys first and then > performs a linear scan for the key. Much better: > > key in some_dict > > This test avoids building the list and can also use an efficient lookup > algorithm that is independent of the size of the dict. > >> running_MOU[IMEI] += Elapsed_Mins >> else: >> running_MOU[IMEI] = Elapsed_Mins >> >> if IMEI in call_attempts.keys(): >> call_attempts[IMEI] += 1 >> else: >> call_attempts[IMEI] = 1 >> >> # if key matches append mou else append 0. >> d[IMEI] = [running_MOU[IMEI]] >> d[IMEI].append([call_attempts[IMEI]]) >> d[IMEI].append([device]) >> >> >> print ",".join(header) >> for k,v in sorted(d.items()): >> print k, ",", d[k][print_map['MOU']],",", >> d[k][print_map['Call_Att']][0],",", d[k][print_map['Device']][0] >> >> print "complete" > > Here's an alternative that uses only one dict: > > import csv > import os > import sys > > header = ['IMEI', 'MOUs', 'Call_Att', 'Device'] > > path = 'C:/Users/cs062x/Desktop/Panhandle' > > d = {} > for fname in os.listdir(path): > with open(os.path.join(path, fname)) as csvfile: > spamreader = csv.reader(csvfile, delimiter=',', quotechar='|') > next(spamreader) > for row in spamreader: > if row[8]: > device = row[36] > elapsed_mins = float(row[7]) > IMEI = row[8].replace("'", "") > > if IMEI in d: > record = d[IMEI] > record[1] += elapsed_mins > record[2] += 1 > else: > d[IMEI] = [IMEI, elapsed_mins, 1, device] > > writer = csv.writer(sys.stdout) > writer.writerow(header) > writer.writerows(sorted(d.itervalues())) > > print "complete" Peter - Thank you for showing me how to do this with one dictionary and a more efficient method to lookup dictionary keys. I originally attempted to accomplish this by using one dictionary but could not find a good example that is why I used the defaultdict module. Your approach sped the parsing time up from about 3 minutes to about 15 seconds! Very cool. Thanks, Chris From abhijeet560 at yahoo.in Thu Jun 4 16:09:43 2015 From: abhijeet560 at yahoo.in (abhijeet560 at yahoo.in) Date: Thu, 4 Jun 2015 14:09:43 +0000 (UTC) Subject: [Tutor] Image library Message-ID: <1286356073.3025285.1433426983599.JavaMail.yahoo@mail.yahoo.com> hello , sir i wanted to know that how can i show or display a simple image using python 3.4The thing is that i want to know that there is no image module or library located in the library folder under python 3.4.?sir, please help me out with this basic step.. From lac at openend.se Thu Jun 4 17:47:10 2015 From: lac at openend.se (Laura Creighton) Date: Thu, 04 Jun 2015 17:47:10 +0200 Subject: [Tutor] Image library In-Reply-To: Message from of "Thu, 04 Jun 2015 14:09:43 -0000." <1286356073.3025285.1433426983599.JavaMail.yahoo@mail.yahoo.com> References: <1286356073.3025285.1433426983599.JavaMail.yahoo@mail.yahoo.com> Message-ID: <201506041547.t54FlAq3004184@fido.openend.se> In a message of Thu, 04 Jun 2015 14:09:43 -0000, abhijeet560 at yahoo.in writes: >hello , sir i wanted to know that how can i show or display a simple image using python 3.4The thing is that i want to know that there is no image module or library located in the library folder under python 3.4.?sir, please help me out with this basic step.. I use Pillow. But you may also have to install some libraries in order to show jpegs, etc. See the list here. http://pillow.readthedocs.org/en/latest/installation.html Laura From alan.gauld at btinternet.com Thu Jun 4 17:51:27 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 04 Jun 2015 16:51:27 +0100 Subject: [Tutor] Image library In-Reply-To: <1286356073.3025285.1433426983599.JavaMail.yahoo@mail.yahoo.com> References: <1286356073.3025285.1433426983599.JavaMail.yahoo@mail.yahoo.com> Message-ID: On 04/06/15 15:09, abhijeet560 at yahoo.in wrote: > i wanted to know that how can i show or display a simple image using python 3.4 The Tkinter package in the standard library includes a Canvas widget which can display various forms of image. It depends what format the image is in. You will probably need to create a PhotoImage object then inset that into the canvas. > The thing is that i want to know that there is no image module or library > located in the library folder under python 3.4.? There is no specific image folder but there is the Tkinter GUI tookit There are several 3rd party toolkits you can downloasd too such as Pillow and imageMagick (for manipulating/converting images). Both include very basic display capability. -- 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 Jun 4 18:12:17 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 04 Jun 2015 17:12:17 +0100 Subject: [Tutor] Image library In-Reply-To: References: <1286356073.3025285.1433426983599.JavaMail.yahoo@mail.yahoo.com> Message-ID: On 04/06/15 16:51, Alan Gauld wrote: > There is no specific image folder but there is the Tkinter GUI tookit Oops, I meant "image 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 lac at openend.se Thu Jun 4 22:50:56 2015 From: lac at openend.se (Laura Creighton) Date: Thu, 04 Jun 2015 22:50:56 +0200 Subject: [Tutor] Trouble using bioread to convert files from .acq to .mat (fwd) Message-ID: <201506042050.t54KouIT011276@fido.openend.se> Missed sending this to the list. Sorry. In a message of Wed, 03 Jun 2015 08:56:48 -0400, Ila Kumar writes: >Laura, that was it! Thank you so much. You are most welcome. > >However, now I am confused about what I need to type into the Command >prompt window (on a 64-bit windows computer, using python 2.7) in order to >convert a folder of data files. Does anyone know the proper code to do this? I am not an expert in bioread, alas. I'm an expert in "ARGH! easy_install won't install this module!!!" But there is an example in the github directory for bioread. Maybe it does what you want? No promises. If it doesn't mailing the package author directly may be your best bet. If you talk to him, ask him to put a line in his pypi file saying that you need to install https://pypi.python.org/pypi/ez_setup if you get an ez_setup not found error, please. At any rate, here is the example. I haven't used it. https://github.com/njvack/bioread/blob/master/examples/api_demo.py Laura ------- End of Forwarded Message From adityashaw.slds at gmail.com Fri Jun 5 08:45:23 2015 From: adityashaw.slds at gmail.com (Aditya Shaw) Date: Fri, 5 Jun 2015 12:15:23 +0530 Subject: [Tutor] Problem with installing python In-Reply-To: References: Message-ID: I was trying to install Python 2.7 on my Windows 8.1(x64) PC and got the following error: "There is a problem with this Windows Istaller Package.A DLL required for this install to complete could not be run.Contact your support personnel or package vendor." Please help! From alan.gauld at btinternet.com Fri Jun 5 09:33:35 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 05 Jun 2015 08:33:35 +0100 Subject: [Tutor] Problem with installing python In-Reply-To: References: Message-ID: On 05/06/15 07:45, Aditya Shaw wrote: > I was trying to install Python 2.7 on my Windows 8.1(x64) PC and got > the following error: > "There is a problem with this Windows Istaller Package.A DLL required > for this install to complete could not be run.Contact your support > personnel or package vendor." It may be a corrupt download. Since you are using Windows I recommend using the installer from Activestate.com rather than the python.org version since it includes several useful extras for Windows users. Try a fresh download from activestate.com and see if that installs. -- 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 richkappler at gmail.com Fri Jun 5 18:28:08 2015 From: richkappler at gmail.com (richard kappler) Date: Fri, 5 Jun 2015 12:28:08 -0400 Subject: [Tutor] line iteration in a file In-Reply-To: References: Message-ID: SOLVED: Sometimes one just has to be an idiot. One must remember that computers count from zero, not from one. Changes my list indexes to reflect that small but crucial fundamental point, and all worked fine. regards, Richard On Wed, Jun 3, 2015 at 10:37 PM, richard kappler wrote: > Figured out the string delimiters problem, thanks for all the help. Now > I've run into another. > > I've used the re.finditer that I think it was Peter suggested. So I have: > > for line in file: > s = line > t = [m.start() for m in re.finditer(r"]", s)] > q = len(t) > > which works fine, in testing it finds the number and position of the ]'s > in any line I throw at it. I then wrote a series of if/elif statements > based on q, in other words > > if q == 1: > do something > elif q == 2: > do something else > elif q == 3: > do a third thing > else: > pass > > as I looked through enough example to figure out that the most ]'s I can > have is 3, but the pass is there just in case. > > I keep getting a list index out of range error, and my best guess is that > it's because t and q are set on the first line read, not each line read, is > that right? If not, what might be the problem and either way, how do I fix > it? > > regards, Richard > who is proving to his Linux box that he is an idiot pretty regularly > -- > > Windows assumes you are an idiot?Linux demands proof. > -- Windows assumes you are an idiot?Linux demands proof. From sanelson at gmail.com Fri Jun 5 22:16:33 2015 From: sanelson at gmail.com (Stephen Nelson-Smith) Date: Fri, 5 Jun 2015 21:16:33 +0100 Subject: [Tutor] Sorting a list of list Message-ID: As part of my league secretary program (to which thread I shall reply again shortly), I need to sort a list of lists. I've worked out that I can use sorted() and operator.itemgetter to sort by a value at a known position in each list. Is it possible to do this at a secondary level? So if the items are the same, we use the secondary key? Current function: >>> def sort_table(table, col=0): ... return sorted(table, key=operator.itemgetter(col), reverse=True) ... >>> sort_table(results, 6) [['spip', 2, 2, 0, 10, 0, 4], ['hpip', 2, 0, 2, 2, 8, 0]] S. From __peter__ at web.de Fri Jun 5 22:48:37 2015 From: __peter__ at web.de (Peter Otten) Date: Fri, 05 Jun 2015 22:48:37 +0200 Subject: [Tutor] Sorting a list of list References: Message-ID: Stephen Nelson-Smith wrote: > As part of my league secretary program (to which thread I shall reply > again > shortly), I need to sort a list of lists. I've worked out that I can use > sorted() and operator.itemgetter to sort by a value at a known position in > each list. Is it possible to do this at a secondary level? So if the > items are the same, we use the secondary key? > > Current function: > >>>> def sort_table(table, col=0): > ... return sorted(table, key=operator.itemgetter(col), reverse=True) > ... >>>> sort_table(results, 6) > [['spip', 2, 2, 0, 10, 0, 4], ['hpip', 2, 0, 2, 2, 8, 0]] itemgetter() accepts multiple indices: >>> items = [ ... ["one", "stephen", 20], ... ["two", "stephen", 10], ... ["three", "jim", 20]] >>> from operator import itemgetter >>> sorted(items, key=itemgetter(1, 2)) [['three', 'jim', 20], ['two', 'stephen', 10], ['one', 'stephen', 20]] >>> sorted(items, key=itemgetter(2, 1)) [['two', 'stephen', 10], ['three', 'jim', 20], ['one', 'stephen', 20]] For complex sort orders you can build on the fact that Python's sort is "stable", i. e. equal items do not change their relative position. Just sort by the "least significan key" first: >>> items.sort(key=itemgetter(2), reverse=True) >>> items.sort(key=itemgetter(1)) >>> items [['three', 'jim', 20], ['one', 'stephen', 20], ['two', 'stephen', 10]] From breamoreboy at yahoo.co.uk Fri Jun 5 22:49:27 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 05 Jun 2015 21:49:27 +0100 Subject: [Tutor] Sorting a list of list In-Reply-To: References: Message-ID: On 05/06/2015 21:16, Stephen Nelson-Smith wrote: > As part of my league secretary program (to which thread I shall reply again > shortly), I need to sort a list of lists. I've worked out that I can use > sorted() and operator.itemgetter to sort by a value at a known position in > each list. Is it possible to do this at a secondary level? So if the > items are the same, we use the secondary key? > > Current function: > >>>> def sort_table(table, col=0): > ... return sorted(table, key=operator.itemgetter(col), reverse=True) > ... >>>> sort_table(results, 6) > [['spip', 2, 2, 0, 10, 0, 4], ['hpip', 2, 0, 2, 2, 8, 0]] > > S. > Asked myself the very same thing earlier today so had the answer at my fingertips, taken from https://docs.python.org/3/howto/sorting.html The operator module functions allow multiple levels of sorting. For example, to sort by grade then by age: >>> >>> sorted(student_tuples, key=itemgetter(1,2)) [('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)] -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From lac at openend.se Sat Jun 6 03:54:56 2015 From: lac at openend.se (Laura Creighton) Date: Sat, 06 Jun 2015 03:54:56 +0200 Subject: [Tutor] Sorting a list of list In-Reply-To: Message from Stephen Nelson-Smith of "Fri, 05 Jun 2015 21:16:33 +0100." References: Message-ID: <201506060154.t561su3r018571@fido.openend.se> In a message of Fri, 05 Jun 2015 21:16:33 +0100, Stephen Nelson-Smith writes: >As part of my league secretary program (to which thread I shall reply again >shortly), I need to sort a list of lists. I've worked out that I can use >sorted() and operator.itemgetter to sort by a value at a known position in >each list. Is it possible to do this at a secondary level? So if the >items are the same, we use the secondary key? Certainly. see: https://wiki.python.org/moin/HowTo/Sorting Laura From sunil.techspk at gmail.com Mon Jun 8 11:34:05 2015 From: sunil.techspk at gmail.com (Sunil Tech) Date: Mon, 8 Jun 2015 15:04:05 +0530 Subject: [Tutor] Docstring Message-ID: Hi Team, what is the standard way of using docstrings? for example (Sphinx) def test(x): """ A dummy method Args: x (int): first argument Returns: "true or false" """ and if the method has no arguments? how should be the docstring? Thanks & Regards, Sunil. G From steve at pearwood.info Mon Jun 8 12:34:26 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 8 Jun 2015 20:34:26 +1000 Subject: [Tutor] Docstring In-Reply-To: References: Message-ID: <20150608103426.GK20701@ando.pearwood.info> On Mon, Jun 08, 2015 at 03:04:05PM +0530, Sunil Tech wrote: > Hi Team, > > what is the standard way of using docstrings? There isn't one standard way of using docstrings. Different systems use different conventions. The conventions for the Python standard library are described here: https://www.python.org/dev/peps/pep-0257/ The conventions used by Google are here: http://google-styleguide.googlecode.com/svn/trunk/pyguide.html#Comments Epydoc uses Javadoc conventions: """This is a javadoc style. @param param1: this is a first param @param param2: this is a second param @return: this is a description of what is returned @raise keyError: raises an exception """ Sphinx uses ReST conventions: """This is a ReST style. :param param1: this is a first param :param param2: this is a second param :returns: this is a description of what is returned :raises keyError: raises an exception """ and also understands Google's conventions: """This is Google's style. Parameters: param1 - this is the first param param2 - this is a second param Returns: This is a description of what is returned Raises: KeyError - raises an exception """ Numpy also has their own custom format, which apparently Sphinx also understands. Pycco uses Markdown rather than ReST. There's also Doxygen, but I don't know what it uses. So that's *at least* five different conventions. > for example (Sphinx) > def test(x): > """ > A dummy method > Args: > x (int): first argument > Returns: > "true or false" > """ > > and if the method has no arguments? > how should be the docstring? Just leave it out: """A dummy method. Returns: "true or false" """ -- Steve From sunil.techspk at gmail.com Mon Jun 8 13:06:29 2015 From: sunil.techspk at gmail.com (Sunil Tech) Date: Mon, 8 Jun 2015 16:36:29 +0530 Subject: [Tutor] Docstring In-Reply-To: <20150608103426.GK20701@ando.pearwood.info> References: <20150608103426.GK20701@ando.pearwood.info> Message-ID: Thank you Steven D'Aprano On Mon, Jun 8, 2015 at 4:04 PM, Steven D'Aprano wrote: > On Mon, Jun 08, 2015 at 03:04:05PM +0530, Sunil Tech wrote: > > Hi Team, > > > > what is the standard way of using docstrings? > > There isn't one standard way of using docstrings. Different systems use > different conventions. > > The conventions for the Python standard library are described here: > > https://www.python.org/dev/peps/pep-0257/ > > The conventions used by Google are here: > > http://google-styleguide.googlecode.com/svn/trunk/pyguide.html#Comments > > > Epydoc uses Javadoc conventions: > > """This is a javadoc style. > > @param param1: this is a first param > @param param2: this is a second param > @return: this is a description of what is returned > @raise keyError: raises an exception > """ > > > Sphinx uses ReST conventions: > > """This is a ReST style. > > :param param1: this is a first param > :param param2: this is a second param > :returns: this is a description of what is returned > :raises keyError: raises an exception > """ > > and also understands Google's conventions: > > """This is Google's style. > > Parameters: > param1 - this is the first param > param2 - this is a second param > > Returns: > This is a description of what is returned > > Raises: > KeyError - raises an exception > """ > > > Numpy also has their own custom format, which apparently > Sphinx also understands. Pycco uses Markdown rather than ReST. There's > also Doxygen, but I don't know what it uses. So that's *at least* five > different conventions. > > > > > for example (Sphinx) > > def test(x): > > """ > > A dummy method > > Args: > > x (int): first argument > > Returns: > > "true or false" > > """ > > > > and if the method has no arguments? > > how should be the docstring? > > > Just leave it out: > > > """A dummy method. > > Returns: > "true or false" > """ > > > > -- > Steve > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From jarod_v6 at libero.it Mon Jun 8 16:50:13 2015 From: jarod_v6 at libero.it (jarod_v6 at libero.it) Date: Mon, 8 Jun 2015 16:50:13 +0200 (CEST) Subject: [Tutor] Problem on filtering data Message-ID: <53144316.3563331433775013976.JavaMail.httpd@webmail-58.iol.local> Dear All; I have a very silly problem. with open("Dati_differenzialigistvsminigist_solodiff.csv") as p: for i in p: lines = i.strip("\n").split("\t") if lines[8] != "NA": if lines[8] : print lines[8] Why I continue to obtain "" empity line? "baseMean" "log2FoldChange" "lfcSE" "stat" "pvalue" "padj" "ensembl" "hgnc_symbol" "uniprot" "entrez" "ENSG00000001460" 49.2127074325806 -1.23024931383259 0.386060601796602 -3.18667408201565 0.00143918849913772 0.0214436050108864 "ENSG00000001460" "STPG1" "Q5TH74" 90529 "ENSG00000001631" 104.058286326346 -0.80555704451241 0.294010285837035 -2.73989408982418 0.00614589853281486 0.0574525590840568 "ENSG00000001631" "KRIT1" "O00522" 889 "ENSG00000002933" 1777.43938933705 1.58630255355138 0.608489070400574 2.60695323994414 0.00913518344605639 0.0740469624219782 "ENSG00000002933" "TMEM176A" "Q96HP8" 55365 "ENSG00000003137" 7.12073122713574 2.21265894560888 0.501823258624614 4.40923952324029 1.03734243663752e-05 0.000620867030402752 "ENSG00000003137" "CYP26B1" "Q9NR63" 56603 "ENSG00000003989" 8.98972643541858 -1.19156195325944 0.467992084035133 -2.54611561585728 0.010892910391296 0.0832138232974883 "ENSG00000003989" "SLC7A2" "P52569" 6542 "ENSG00000004478" 352.680009703697 1.07781013614545 0.371617391411002 2.90032210831978 0.00372779367087775 0.041335008661432 "ENSG00000004478" "FKBP4" "Q02790" 2288 "ENSG00000004776" 1808.49276145547 -2.22691975109948 0.560563734648272 -3.97264327578517 7.10794561495787e-05 0.00243688669444854 "ENSG00000004776" "HSPB6" "O14558" 126393 "ENSG00000004779" 110.066557414377 1.0371628629106 0.375665509210244 2.76086794630418 0.00576479803838396 0.0552052693506261 "ENSG0 thanks so much From alan.gauld at btinternet.com Mon Jun 8 17:52:04 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 08 Jun 2015 16:52:04 +0100 Subject: [Tutor] Problem on filtering data In-Reply-To: <53144316.3563331433775013976.JavaMail.httpd@webmail-58.iol.local> References: <53144316.3563331433775013976.JavaMail.httpd@webmail-58.iol.local> Message-ID: On 08/06/15 15:50, jarod_v6--- via Tutor wrote: > with open("Dati_differenzialigistvsminigist_solodiff.csv") as p: You are usually better off processing CSV files (or in your case tab separated) using the CSV module. > for i in p: > lines = i.strip("\n").split("\t") > if lines[8] != "NA": > if lines[8] : > print lines[8] > > Why I continue to obtain "" empity line? What does empty line mean? Do you get a line printed with no content? Or no line printed? I've no idea, but I do notice that you last line is not complete - ie it only has 8 fields. so lines[8] != "NA" should fail with an index error! Also your headings only have 10 entries but your lines have 11? Also you are processing the headings line in the same way as the rest of the data, is that correct? > > "baseMean" "log2FoldChange" "lfcSE" "stat" "pvalue" "padj" "ensembl" "hgnc_symbol" "uniprot" "entrez" > "ENSG00000001460" 49.2127074325806 -1.23024931383259 0.386060601796602 -3.18667408201565 0.00143918849913772 0.0214436050108864 "ENSG00000001460" "STPG1" "Q5TH74" 90529 > "ENSG00000004779" 110.066557414377 1.0371628629106 0.375665509210244 2.76086794630418 0.00576479803838396 0.0552052693506261 "ENSG0 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 Mon Jun 8 17:57:53 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 08 Jun 2015 16:57:53 +0100 Subject: [Tutor] Docstring In-Reply-To: References: Message-ID: On 08/06/15 10:34, Sunil Tech wrote: > what is the standard way of using docstrings? As Steven said there are several "standards". Yet another option is to use the format required by doctest. For your example: def test(x): """ A dummy method >>> test(5) True >>> test(-5) False """ Or whatever test cases 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 steve at pearwood.info Mon Jun 8 18:02:38 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 9 Jun 2015 02:02:38 +1000 Subject: [Tutor] Problem on filtering data In-Reply-To: <53144316.3563331433775013976.JavaMail.httpd@webmail-58.iol.local> References: <53144316.3563331433775013976.JavaMail.httpd@webmail-58.iol.local> Message-ID: <20150608160238.GM20701@ando.pearwood.info> On Mon, Jun 08, 2015 at 04:50:13PM +0200, jarod_v6--- via Tutor wrote: > Dear All; > I have a very silly problem. The right way to handle CSV files is to use the csv module: https://docs.python.org/2/library/csv.html http://pymotw.com/2/csv/ Some more comments further below. > with open("Dati_differenzialigistvsminigist_solodiff.csv") as p: > for i in p: > lines = i.strip("\n").split("\t") > if lines[8] != "NA": > if lines[8] : > print lines[8] > > Why I continue to obtain "" empity line? I don't know. What do you mean 'obtain "" empty line'? Do you mean that every line is empty? Some of the lines are empty? One empty line at the end? How do you know it is empty? You need to explain more. Perhaps put this instead: print repr(lines[8]) to see what it contains. Perhaps there are invisible s p a c e s so it only looks empty. Some more comments: In English, we would describe open("Dati....csv") as a file, and write with open("Dati....csv") as f: # f for file I suppose in Italian you might say "archivio", and write: with open("Dati....csv") as a: But what is "p"? The next line is also confusing: for i in p: "for i in ..." is used for loops over the integers 0, 1, 2, 3, ... and should not be used for anything else. Here, you loop over the lines in the file, so you should write: for line in p: fields = line.strip("\n").split("\t") or perhaps "columns" instead of "fields". But "lines" is completely wrong, because you are looking at one line at a time. -- Steve From jarod_v6 at libero.it Mon Jun 8 22:12:55 2015 From: jarod_v6 at libero.it (jarod_v6 at libero.it) Date: Mon, 8 Jun 2015 22:12:55 +0200 (CEST) Subject: [Tutor] R: Tutor Digest, Vol 136, Issue 19 Message-ID: <490197454.3819521433794375889.JavaMail.httpd@webmail-08.iol.local> Thanks for the help!! The data I put unfortunately was runcated: ENSG00000267199 11.8156750037 1.7442320912 0.5103558647 3.4176781572 0.0006315774 0.0122038731 ENSG00000267199 NA NA NA ENSG00000267206 27.9863824875 -1.7496803666 0.5026610268 -3.4808355401 0.0004998523 0.0102622293 ENSG00000267206 LCN6 P62502 158062 ENSG00000267249 9.3904402364 -1.3510262216 0.4923605689 -2.743977294 0.0060699736 0.056855688 ENSG00000267249 NA NA NA ENSG00000267270 8.3690069507 1.2036206884 0.4798752229 2.5081951119 0.012134964 0.0887668369 ENSG00000267270 NA ENSG00000267278 5.8613893946 -1.7315438788 0.5939508055 -2.9152984772 0.0035534852 0.0403281717 ENSG00000267278 NA NA NA ENSG00000267328 36.1538389415 -1.7645196111 0.4926869829 -3.5814212114 0.0003417302 0.007661808 ENSG00000267328 NA NA NA ENSG00000186575 252.0042869342 -1.6381747801 0.4198974515 -3.901368713 9.56503323694447E-005 0.003015761 ENSG00000186575 NF2 P35240 4771 ENSG00000186716 107.848675839 -0.8308190712 0.3206514872 -2.5910345165 0.0095687894 0.076412686 ENSG00000186716 BCR P11274 613 ENSG00000186792 47.1740786192 0.9880158388 0.3663380942 2.6970054561 0.0069966124 0.0623663902 ENSG00000186792 HYAL3 O43820 8372 ENSG00000186868 38.260745337 1.8554746045 0.568540138 3.263577152 0.0011001523 0.0179441693 ENSG00000186868 MAPT 4137 However I don't know but the code works after reboot ipython. I obtain only the symbol name The code are not writing in Italian. the letters are use without no meaning. From dyoo at hashcollision.org Mon Jun 8 22:24:12 2015 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 8 Jun 2015 13:24:12 -0700 Subject: [Tutor] R: Tutor Digest, Vol 136, Issue 19 In-Reply-To: <490197454.3819521433794375889.JavaMail.httpd@webmail-08.iol.local> References: <490197454.3819521433794375889.JavaMail.httpd@webmail-08.iol.local> Message-ID: On Mon, Jun 8, 2015 at 1:12 PM, jarod_v6--- via Tutor wrote: > Thanks for the help!! The data I put unfortunately was runcated: > ENSG00000267199 11.8156750037 1.7442320912 0.5103558647 3.4176781572 > 0.0006315774 0.0122038731 ENSG00000267199 NA NA NA > ENSG00000267206 27.9863824875 -1.7496803666 0.5026610268 -3.4808355401 > 0.0004998523 0.0102622293 ENSG00000267206 LCN6 P62502 158062 > ENSG00000267249 9.3904402364 -1.3510262216 0.4923605689 -2.743977294 > 0.0060699736 0.056855688 ENSG00000267249 NA NA NA > ENSG00000267270 8.3690069507 1.2036206884 0.4798752229 2.5081951119 > 0.012134964 0.0887668369 ENSG00000267270 NA > ENSG00000267278 5.8613893946 -1.7315438788 0.5939508055 -2.9152984772 > 0.0035534852 0.0403281717 ENSG00000267278 NA NA NA > ENSG00000267328 36.1538389415 -1.7645196111 0.4926869829 -3.5814212114 > 0.0003417302 0.007661808 ENSG00000267328 NA NA NA > ENSG00000186575 252.0042869342 -1.6381747801 0.4198974515 -3.901368713 > 9.56503323694447E-005 0.003015761 ENSG00000186575 NF2 P35240 4771 > ENSG00000186716 107.848675839 -0.8308190712 0.3206514872 -2.5910345165 > 0.0095687894 0.076412686 ENSG00000186716 BCR P11274 613 > ENSG00000186792 47.1740786192 0.9880158388 0.3663380942 2.6970054561 > 0.0069966124 0.0623663902 ENSG00000186792 HYAL3 O43820 8372 > ENSG00000186868 38.260745337 1.8554746045 0.568540138 3.263577152 0.0011001523 > 0.0179441693 ENSG00000186868 MAPT 4137 > > However I don't know but the code works after reboot ipython. > I obtain only the symbol name > The code are not writing in Italian. the letters are use without no meaning. I don't think we have sufficient information to help with this yet. Can you show us a code sample? You mention: > However I don't know but the code works after reboot ipython. What do you mean by "works"? Specifically: how does the good output differ from the bad output you're presenting here? That information would be really helpful, because then we can look for why there are differences. From sunil.techspk at gmail.com Tue Jun 9 10:09:01 2015 From: sunil.techspk at gmail.com (Sunil Tech) Date: Tue, 9 Jun 2015 13:39:01 +0530 Subject: [Tutor] Docstring In-Reply-To: References: Message-ID: Thanks Alan Gauld On Mon, Jun 8, 2015 at 9:27 PM, Alan Gauld wrote: > On 08/06/15 10:34, Sunil Tech wrote: > > what is the standard way of using docstrings? >> > > As Steven said there are several "standards". > > Yet another option is to use the format required > by doctest. For your example: > > def test(x): > """ > A dummy method > >>> test(5) > True > >>> test(-5) > False > """ > > Or whatever test cases 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 > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From rakeshsharma14 at hotmail.com Wed Jun 10 12:36:23 2015 From: rakeshsharma14 at hotmail.com (rakesh sharma) Date: Wed, 10 Jun 2015 16:06:23 +0530 Subject: [Tutor] (no subject) Message-ID: I have come across this syntax in python. Embedding for loop in []. How far can things be stretched using this []. l = [1, 2, 3, 4, 5] q = [i*2 for i in l] print qthanksrakesh From joel.goldstick at gmail.com Wed Jun 10 12:55:56 2015 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 10 Jun 2015 06:55:56 -0400 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: On Wed, Jun 10, 2015 at 6:36 AM, rakesh sharma wrote: > > I have come across this syntax in python. Embedding for loop in []. How far can things be stretched using this []. > l = [1, 2, 3, 4, 5] > q = [i*2 for i in l] > print qthanksrakesh This is called a list comprehension. They are a more concise way of writing various for loops. You can google to learn much more -- Joel Goldstick http://joelgoldstick.com From alan.gauld at btinternet.com Wed Jun 10 17:39:10 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 10 Jun 2015 16:39:10 +0100 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: On 10/06/15 11:36, rakesh sharma wrote: > > I have come across this syntax in python. Embedding for loop in []. How far can things be stretched using this []. > l = [1, 2, 3, 4, 5] > q = [i*2 for i in l] This is a list comprehension which is a specific form of the more generalised "generator expression": for item in iterable if And it is possible to have multiple loops and complex expressions and conditions. How far they can be taken is a good question. They can be taken much further than they should be, to the point where the code becomes both unreadable and untestable. Keep them relatively simple is the best advice. There is no shame in unwrapping them to something like: aList = [] for item in anIterable: if condition: aList.append(expression) If it is more maintainable and testable. You can always wrap them up again later if it is needed for performance reasons. -- 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 cmgcomsol at gmail.com Wed Jun 10 19:41:36 2015 From: cmgcomsol at gmail.com (Mirage Web Studio) Date: Wed, 10 Jun 2015 23:11:36 +0530 Subject: [Tutor] Generate Prime Numbers In-Reply-To: References: <55688590.8020104@gmail.com> <5569FE0E.1070401@gmail.com> Message-ID: <557876D0.6030701@gmail.com> On 2015-05-31 5:04 AM, Alan Gauld wrote: > On 30/05/15 19:14, George wrote: Excuse me please for replying late. I got lists to use the method and it is more efficient and faster. (Takes about 10 secs to process first 50 mil numbers) But now another problem i seem to notice that only 1 core of my amd Athlon X2 4core processor is being used. I suppose if all the four cores are simultaneously used then the programme might run even faster. Is there a way. Kindly guide me. Thank You. George --- This email has been checked for viruses by Avast antivirus software. https://www.avast.com/antivirus From lac at openend.se Wed Jun 10 21:08:15 2015 From: lac at openend.se (Laura Creighton) Date: Wed, 10 Jun 2015 21:08:15 +0200 Subject: [Tutor] Generate Prime Numbers In-Reply-To: Message from Mirage Web Studio of "Wed, 10 Jun 2015 23:11:36 +0530." <557876D0.6030701@gmail.com> References: <55688590.8020104@gmail.com> <5569FE0E.1070401@gmail.com> <557876D0.6030701@gmail.com> Message-ID: <201506101908.t5AJ8Fw7010590@fido.openend.se> In a message of Wed, 10 Jun 2015 23:11:36 +0530, Mirage Web Studio writes: > > > >On 2015-05-31 5:04 AM, Alan Gauld wrote: >> On 30/05/15 19:14, George wrote: > >Excuse me please for replying late. > >I got lists to use the method and it is more efficient and faster. >(Takes about 10 secs to process first 50 mil numbers) > >But now another problem i seem to notice that only 1 core of my amd >Athlon X2 4core processor is being used. I suppose if all the four >cores are simultaneously used then the programme might run even faster. >Is there a way. > >Kindly guide me. > >Thank You. > >George If you want, you can use the STM branch of the pypy interpreter. This is a Python without the global interpreter lock. One of the tests we did was, surprise, to calculate prime numbers. See the blog post here: http://morepypy.blogspot.se/2014/11/tornado-without-gil-on-pypy-stm.html Laura From alan.gauld at btinternet.com Thu Jun 11 01:03:08 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 11 Jun 2015 00:03:08 +0100 Subject: [Tutor] Generate Prime Numbers In-Reply-To: <557876D0.6030701@gmail.com> References: <55688590.8020104@gmail.com> <5569FE0E.1070401@gmail.com> <557876D0.6030701@gmail.com> Message-ID: On 10/06/15 18:41, Mirage Web Studio wrote: > But now another problem i seem to notice that only 1 core of my amd > Athlon X2 4core processor is being used. I suppose if all the four > cores are simultaneously used then the programme might run even faster. > Is there a way. One of the problems with the "standard" CPython implementation is that it only uses one CPU, even if you write threaded code. There are implementations that address that, but I've never used them so can't comment on whether they would help in your case. I'm also not sure how Jython or IronPython handle things, they might use their internal threading engines more effectively. -- 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 tudby001 at mymail.unisa.edu.au Thu Jun 11 09:19:31 2015 From: tudby001 at mymail.unisa.edu.au (Tudor, Bogdan - tudby001) Date: Thu, 11 Jun 2015 07:19:31 +0000 Subject: [Tutor] moving objects in only one direction at a time In-Reply-To: References: , Message-ID: Hi, Sorry if this sends twice, I had to change subject line. I am using python 3.4.3 on windows 7 64bit. I'm using John M. Zelle graphics module. Graphics module: http://mcsp.wartburg.edu/zelle/python/graphics/graphics/graphics.html I am trying to create user movable blocks that can only move in one direction at a time. The arrow keys are used to move left or right. Currently while moving left, pressing the right arrow key will change the blocks direction and vice versa. I'm trying to get the block to continue moving in only one direction determined by the arrow keys, i.e. pressing right should not move the blocks right if they already moving left. How can I fix my code to do this? I expected adding True/False variables (moveLEFT, moveRIGHT) would allow me to disable one key press while another is in action, unfortunately has not worked. I hope its OK that I attached files as they are long. --> blockgame.py import graphics import game_functions import time def handleKeys(event): global direction global moveLEFT global moveRIGHT print('Key pressed', event.keysym, event.keycode) if event.keysym == 'Left': direction = 'Left' moveLEFT = True moveRIGHT = False elif event.keysym == 'Right': direction = 'Right' moveLEFT = False moveRIGHT = True elif event.keysym == 'q': win.close() def game(): global direction global square global moveLEFT global moveRIGHT block = game_functions.GameBlock(WIN_WIDTH//2, WIN_HEIGHT//2, BLOCK_SIZE, BLOCK_SIZE, 'Red', None, None, 0) block.draw(win) square.append(block) block = game_functions.GameBlock(WIN_WIDTH//2, WIN_HEIGHT//2, BLOCK_SIZE, BLOCK_SIZE, 'Red', None, None, 0) block.draw(win) square.append(block) speed = 0.1 playing = True while playing: # Move squares for k in range(len(square)-1, 0, -1): moveX = square[k-1].getCentreX() - square[k].getCentreX() moveY = square[k-1].getCentreY() - square[k].getCentreY() square[k].move(moveX, moveY) # Update pos if moveLEFT == True and moveRIGHT == False: square[0].move(-20, 0) if moveRIGHT and moveLEFT == False: square[0].move(20, 0) time.sleep(speed) moveLEFT = False moveRIGHT = False WIN_WIDTH = 500 WIN_HEIGHT = 500 BLOCK_SIZE = 20 direction = "" square = [] win = graphics.GraphWin("Snake", WIN_WIDTH, WIN_HEIGHT) win.setBackground("white") win.bind_all('', handleKeys) game() win.mainloop() win.getMouse() win.close() --> game_functions.py import graphics class GameBlock(): def __init__(self, dx, dy, width, height, colour, imageName, blockType, points): self.centreX = dx self.centreY = dy self.width = width self.height = height self.colour = colour self.imageName = imageName self.blockType = blockType self.points = points self.scrollSpeed = 10 self.block = graphics.Rectangle(graphics.Point(self.centreX-self.width//2, self.centreY-self.height//2), graphics.Point(self.centreX+self.width//2, self.centreY+self.height//2)) self.block.setFill(colour) if not(imageName == None): self.image = graphics.Image(graphics.Point(dx,dy), imageName) else: self.image = None def getCentreX(self): return self.centreX def getCentreY(self): return self.centreY def move(self, dx, dy): self.centreX = self.centreX + dx self.centreY = self.centreY + dy self.block.move(dx,dy) if not(self.image == None): self.image.move(dx,dy) def draw(self, canvas): if self.image == None: self.block.draw(canvas) else: self.image.draw(canvas) __________________________ I will greatly appreciate any help! Kind Regards -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: blockgame.py URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: game_functions.py URL: From lac at openend.se Thu Jun 11 17:46:13 2015 From: lac at openend.se (Laura Creighton) Date: Thu, 11 Jun 2015 17:46:13 +0200 Subject: [Tutor] Generate Prime Numbers In-Reply-To: Message from Mirage Web Studio of "Thu, 11 Jun 2015 19:19:23 +0530." <557991E3.8040603@gmail.com> References: <55688590.8020104@gmail.com> <5569FE0E.1070401@gmail.com> <557876D0.6030701@gmail.com> <201506101908.t5AJ8Fw7010590@fido.openend.se><557991E3.8040603@gmail.com> Message-ID: <201506111546.t5BFkDDe010071@fido.openend.se> Alas, PyPy STM only works for 64 bit linux for now. You are catching the PyPy project at the edge of its 'bleeding edge research'. We think in 1 or 2 releases windows users should be able to get it too, and I will let you know when that happens. And no promises. These sorts of things have a habit of being 'a simple matter of this and that' on paper but actually much harder when it comes to writing code, so while it will happen, when is an open question. Sorry about that, Laura From cmgcomsol at gmail.com Thu Jun 11 15:49:23 2015 From: cmgcomsol at gmail.com (Mirage Web Studio) Date: Thu, 11 Jun 2015 19:19:23 +0530 Subject: [Tutor] Generate Prime Numbers In-Reply-To: <201506101908.t5AJ8Fw7010590@fido.openend.se> References: <55688590.8020104@gmail.com> <5569FE0E.1070401@gmail.com> <557876D0.6030701@gmail.com> <201506101908.t5AJ8Fw7010590@fido.openend.se> Message-ID: <557991E3.8040603@gmail.com> On 2015-06-11 12:38 AM, Laura Creighton wrote: > In a message of Wed, 10 Jun 2015 23:11:36 +0530, George writes: >> >> >> On 2015-05-31 5:04 AM, Alan Gauld wrote: >>> On 30/05/15 19:14, George wrote: >> Excuse me please for replying late. >> >> I got lists to use the method and it is more efficient and faster. >> (Takes about 10 secs to process first 50 mil numbers) >> >> But now another problem i seem to notice that only 1 core of my amd >> Athlon X2 4core processor is being used. I suppose if all the four >> cores are simultaneously used then the programme might run even faster. >> Is there a way. >> >> Kindly guide me. >> >> Thank You. >> >> George > If you want, you can use the STM branch of the pypy interpreter. This > is a Python without the global interpreter lock. One of the tests > we did was, surprise, to calculate prime numbers. > > See the blog post here: > http://morepypy.blogspot.se/2014/11/tornado-without-gil-on-pypy-stm.html > > Laura > Thank u, PYPY is indeed very fast and as expected is using all the cores. I think i have found what i was looking for. I saw that stm branch is only for linux. Windows binaries if available would be of great help. Thank u all for interest in replying. George. --- This email has been checked for viruses by Avast antivirus software. https://www.avast.com/antivirus From wumeid at hotmail.com Thu Jun 11 15:25:25 2015 From: wumeid at hotmail.com (Michelle Meiduo Wu) Date: Thu, 11 Jun 2015 09:25:25 -0400 Subject: [Tutor] Python&Pytest In-Reply-To: References: <55688590.8020104@gmail.com> ,<5569FE0E.1070401@gmail.com> , <557876D0.6030701@gmail.com>, Message-ID: Hi there, I'm looking for a language to write test scripts for our application. I read some document and found Pytest can be used to write simpler code compared with using unittest in Python. Does anybody know what's other pros and cons of using these two for writing test scripts? Thank you,Michelle From tudby001 at mymail.unisa.edu.au Thu Jun 11 11:22:20 2015 From: tudby001 at mymail.unisa.edu.au (Tudor, Bogdan - tudby001) Date: Thu, 11 Jun 2015 09:22:20 +0000 Subject: [Tutor] moving objects in only one direction at a time In-Reply-To: References: , , Message-ID: Hi, Sorry if this sends twice. I am using python 3.4.3 on windows 7 64bit. I'm using John M. Zelle graphics module. Graphics module: http://mcsp.wartburg.edu/zelle/python/graphics/graphics/graphics.html I am trying to create user movable blocks that can only move in one direction at a time. The arrow keys are used to move left or right. Currently while moving left, pressing the right arrow key will change the blocks direction and vice versa. I'm trying to get the block to continue moving in only one direction determined by the arrow keys, i.e. pressing right should not move the blocks right if they already moving left. How can I fix my code to do this? I expected adding True/False variables (moveLEFT, moveRIGHT) would allow me to disable one key press while another is in action, unfortunately has not worked. I hope its OK that I attached files as they are long. --> blockgame.py import graphics import game_functions import time def handleKeys(event): global direction global moveLEFT global moveRIGHT print('Key pressed', event.keysym, event.keycode) if event.keysym == 'Left': direction = 'Left' moveLEFT = True moveRIGHT = False elif event.keysym == 'Right': direction = 'Right' moveLEFT = False moveRIGHT = True elif event.keysym == 'q': win.close() def game(): global direction global square global moveLEFT global moveRIGHT block = game_functions.GameBlock(WIN_WIDTH//2, WIN_HEIGHT//2, BLOCK_SIZE, BLOCK_SIZE, 'Red', None, None, 0) block.draw(win) square.append(block) block = game_functions.GameBlock(WIN_WIDTH//2, WIN_HEIGHT//2, BLOCK_SIZE, BLOCK_SIZE, 'Red', None, None, 0) block.draw(win) square.append(block) speed = 0.1 playing = True while playing: # Move squares for k in range(len(square)-1, 0, -1): moveX = square[k-1].getCentreX() - square[k].getCentreX() moveY = square[k-1].getCentreY() - square[k].getCentreY() square[k].move(moveX, moveY) # Update pos if moveLEFT == True and moveRIGHT == False: square[0].move(-20, 0) if moveRIGHT and moveLEFT == False: square[0].move(20, 0) time.sleep(speed) moveLEFT = False moveRIGHT = False WIN_WIDTH = 500 WIN_HEIGHT = 500 BLOCK_SIZE = 20 direction = "" square = [] win = graphics.GraphWin("Snake", WIN_WIDTH, WIN_HEIGHT) win.setBackground("white") win.bind_all('', handleKeys) game() win.mainloop() win.getMouse() win.close() --> game_functions.py import graphics class GameBlock(): def __init__(self, dx, dy, width, height, colour, imageName, blockType, points): self.centreX = dx self.centreY = dy self.width = width self.height = height self.colour = colour self.imageName = imageName self.blockType = blockType self.points = points self.scrollSpeed = 10 self.block = graphics.Rectangle(graphics.Point(self.centreX-self.width//2, self.centreY-self.height//2), graphics.Point(self.centreX+self.width//2, self.centreY+self.height//2)) self.block.setFill(colour) if not(imageName == None): self.image = graphics.Image(graphics.Point(dx,dy), imageName) else: self.image = None def getCentreX(self): return self.centreX def getCentreY(self): return self.centreY def move(self, dx, dy): self.centreX = self.centreX + dx self.centreY = self.centreY + dy self.block.move(dx,dy) if not(self.image == None): self.image.move(dx,dy) def draw(self, canvas): if self.image == None: self.block.draw(canvas) else: self.image.draw(canvas) __________________________ I will greatly appreciate any help! Kind Regards From alan.gauld at btinternet.com Thu Jun 11 19:55:23 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 11 Jun 2015 18:55:23 +0100 Subject: [Tutor] Python&Pytest In-Reply-To: References: <55688590.8020104@gmail.com> , <5569FE0E.1070401@gmail.com> , <557876D0.6030701@gmail.com>, Message-ID: On 11/06/15 14:25, Michelle Meiduo Wu wrote: > Hi there, Hi, Please start a new thread for a new subject. Do not reply to an old thread. As it is, your query now appears buried in a discussion about prime numbers. > I'm looking for a language to write test scripts for our application. Can you elaborate? What language is the app written in? On what OS? What kind of testing do you want to do (performance, coverage, functionality? something else?) > I read some document and found Pytest can be used to write > simpler code compared with using unittest in Python. Yes, but PyTest (and unittest) are for testing units of Python code. So they really only apply if your application is written in Python. And in any case you should really have written all the unit tests long before completing your application. > Does anybody know what's other pros and cons We need to understand more about what it is you want to test. And what kinds of tests you want to write. -- 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 Jun 11 20:01:37 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 11 Jun 2015 19:01:37 +0100 Subject: [Tutor] moving objects in only one direction at a time In-Reply-To: References: , Message-ID: On 11/06/15 08:19, Tudor, Bogdan - tudby001 wrote: > Sorry if this sends twice, I had to change subject line. > I am using python 3.4.3 on windows 7 64bit. OK, But always start a new topic with a new message. By replying to an old post your message is now buried at the bottom of a very old thread about formatting strings. This makes it unlikely that people will find it easily. > I'm using John M. Zelle graphics module. > > Graphics module: > http://mcsp.wartburg.edu/zelle/python/graphics/graphics/graphics.html > > I am trying to create user movable blocks that can only move in one > direction at a time. The arrow keys are used to move left or right. > Currently while moving left, pressing the right arrow key will change > the blocks direction and vice versa. Do you really mean that once the block starts moving left it can *never* be reversed? That's a very unusual request. Normally there would either be the ability to reverse or stop the movement. > How can I fix my code to do this? > def handleKeys(event): > global direction > global moveLEFT > global moveRIGHT > print('Key pressed', event.keysym, event.keycode) > > if event.keysym == 'Left': > direction = 'Left' > moveLEFT = True > moveRIGHT = False > elif event.keysym == 'Right': > direction = 'Right' > moveLEFT = False > moveRIGHT = True Notice that you never check whether the block is moving, you always just set the flags, without question. To do what you want, you need to add an if test to first check if the flag is already set. If it's set the wrong way you might want to think about reporting an error message to the user? -- 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 dyoo at hashcollision.org Thu Jun 11 20:27:58 2015 From: dyoo at hashcollision.org (Danny Yoo) Date: Thu, 11 Jun 2015 11:27:58 -0700 Subject: [Tutor] moving objects in only one direction at a time In-Reply-To: References: Message-ID: In an event-driven game, you need to give control back to the event loop in order for the framework to pass events to your program. Your main function, however, doesn't do so: you've got a while loop that monopolizes control flow: def game(): # ... game initialization logic while playing: # ... loop logic time.sleep(speed) This gives no opportunity to process keyboard events, since the program is stuck within the while loop. To resolve this, you want to set up a timer which emits a "tick" event every so often. Essentially, if you're using a Tkinter-based framework, you're looking for the "after" method: http://effbot.org/tkinterbook/widget.htm#Tkinter.Widget.after-method where your program will look something like this: ################################# def game(): # ... game initialization logic gameLoop(); def gameLoop(): if playing: # ... loop logic win.after(speed, gameLoop) ################################# The gameLoop tells the framework to restart the game loop "after" some time. gameLoop() then returns, and gives control back to the event loop that was started with "win.mainloop()". From lac at openend.se Thu Jun 11 23:11:39 2015 From: lac at openend.se (Laura Creighton) Date: Thu, 11 Jun 2015 23:11:39 +0200 Subject: [Tutor] Python&Pytest In-Reply-To: Message from Michelle Meiduo Wu of "Thu, 11 Jun 2015 09:25:25 -0400." References: <55688590.8020104@gmail.com> , <5569FE0E.1070401@gmail.com> , <557876D0.6030701@gmail.com>, Message-ID: <201506112111.t5BLBd6A017581@fido.openend.se> In a message of Thu, 11 Jun 2015 09:25:25 -0400, Michelle Meiduo Wu writes: >Hi there, >I'm looking for a language to write test scripts for our application. I read some document and found Pytest can be used to write simpler code compared with using unittest in Python. Does anybody know what's other pros and cons of using these two for writing test scripts? >Thank you,Michelle It is very much a 'try it and see what you like' sort of thing. Laura From cs at zip.com.au Fri Jun 12 07:58:03 2015 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 12 Jun 2015 15:58:03 +1000 Subject: [Tutor] Python&Pytest In-Reply-To: References: Message-ID: <20150612055803.GA3778@cskk.homeip.net> On 11Jun2015 18:55, alan.gauld at btinternet.com wrote: >On 11/06/15 14:25, Michelle Meiduo Wu wrote: >>I read some document and found Pytest can be used to write >> simpler code compared with using unittest in Python. > >Yes, but PyTest (and unittest) are for testing units of Python >code. So they really only apply if your application is written >in Python. Though if you like the framework, you could write very thin Python wrappers calling something else, and test them. Might be more trouble thatn it is worth though. >And in any case you should really have written >all the unit tests long before completing your application. Ah, the S-word :-) Cheers, Cameron Simpson From fomcl at yahoo.com Fri Jun 12 10:18:27 2015 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Fri, 12 Jun 2015 08:18:27 +0000 (UTC) Subject: [Tutor] Python&Pytest In-Reply-To: <201506112111.t5BLBd6A017581@fido.openend.se> References: <201506112111.t5BLBd6A017581@fido.openend.se> Message-ID: <1713364802.774802.1434097107450.JavaMail.yahoo@mail.yahoo.com> >________________________________ > From: Laura Creighton >To: Michelle Meiduo Wu >Cc: lac at openend.se; "tutor at python.org" >Sent: Thursday, June 11, 2015 11:11 PM >Subject: Re: [Tutor] Python&Pytest > > >In a message of Thu, 11 Jun 2015 09:25:25 -0400, Michelle Meiduo Wu writes: >>Hi there, >>I'm looking for a language to write test scripts for our application. I read some document and found Pytest can be used to write simpler code compared with using unittest in Python. Does anybody know what's other pros and cons of using these two for writing test scripts? >>Thank you,Michelle > >It is very much a 'try it and see what you like' sort of thing. > Hmm, I think it is possible to give some pros and cons. I have no experience with PyTest. While I usually use unittest (just out of habit), I think nose is much easier and powerful. * Unittest Pros: part of the Standard library powerful, flexible Cons: need to declare a class to define one or more test cases (not so readable) no (easy) test runner * Doctest Pros: part of the Standard library testable documentation Cons: Should be used for (testable) documentation, and nothing else Basic use: easy. More advanced use: hard or impossible No good for Python 2 & 3 code. * Nose Pros: tests are readable; they are simply functions generator tests test runner for just about any other test module cons: not part of the Standard library all tests pass in Python optimized mode (-O or -OO) --> because asserts are used! * Pytest ??? * Dedicated test modules: numpy.testing, PyQt4.QtTest, etc. Use whenever possible? From lac at openend.se Fri Jun 12 12:48:24 2015 From: lac at openend.se (Laura Creighton) Date: Fri, 12 Jun 2015 12:48:24 +0200 Subject: [Tutor] Python&Pytest In-Reply-To: Message from Cameron Simpson of "Fri, 12 Jun 2015 15:58:03 +1000." <20150612055803.GA3778@cskk.homeip.net> References: <20150612055803.GA3778@cskk.homeip.net> Message-ID: <201506121048.t5CAmOew005836@fido.openend.se> In a message of Fri, 12 Jun 2015 15:58:03 +1000, Cameron Simpson writes: >On 11Jun2015 18:55, alan.gauld at btinternet.com wrote: >>On 11/06/15 14:25, Michelle Meiduo Wu wrote: >>>I read some document and found Pytest can be used to write >>> simpler code compared with using unittest in Python. >> >>Yes, but PyTest (and unittest) are for testing units of Python >>code. So they really only apply if your application is written >>in Python. Actually, there are many people using pytest to test code written in other languages. We wrote this: https://pypi.python.org/pypi/oejskit to test javascript inside browsers using pytest, for instance. There is a version for running ruby tests and haskell tests that I know about, and undoubtably many more that I do not. Laura From alan.gauld at btinternet.com Fri Jun 12 18:26:42 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 12 Jun 2015 17:26:42 +0100 Subject: [Tutor] Python&Pytest In-Reply-To: <201506121048.t5CAmOew005836@fido.openend.se> References: <20150612055803.GA3778@cskk.homeip.net> <201506121048.t5CAmOew005836@fido.openend.se> Message-ID: On 12/06/15 11:48, Laura Creighton wrote: >>> Yes, but PyTest (and unittest) are for testing units of Python >>> code. So they really only apply if your application is written >>> in Python. > > Actually, there are many people using pytest to test code written in > other languages. We wrote this: > https://pypi.python.org/pypi/oejskit I stand corrected but it still seems to me like its easier to test in the language in which you develop. And most languages have testing frameworks these days. And when there are large paradigm differences in the languages that's even more true. Testing JS (or even Haskell) in Python seems like a weird choice! -- 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 lac at openend.se Fri Jun 12 22:08:55 2015 From: lac at openend.se (Laura Creighton) Date: Fri, 12 Jun 2015 22:08:55 +0200 Subject: [Tutor] Python&Pytest In-Reply-To: Message from Alan Gauld of "Fri, 12 Jun 2015 17:26:42 +0100." References: <20150612055803.GA3778@cskk.homeip.net> <201506121048.t5CAmOew005836@fido.openend.se> Message-ID: <201506122008.t5CK8tSN024722@fido.openend.se> In a message of Fri, 12 Jun 2015 17:26:42 +0100, Alan Gauld writes: >I stand corrected but it still seems to me like its easier to >test in the language in which you develop. And most languages >have testing frameworks these days. Many languages have extremely poor testing frameworks. And when it came time to do testing of the javascript code of the web client of our python app, we found that there wasn't anything available for doing exactly that. >And when there are large paradigm differences in the languages >that's even more true. Testing JS (or even Haskell) in Python >seems like a weird choice! I don't see this at all. By this logic, we would have been better off writing a test framework in javascript to handle our javascript code. But our experience is that, whenever possible, you are always better off not using javascript and programming in another language. Plus the real challenge here was testing our code in the collection of browsers expected to run it. We found lots and lots and lots of javascript bugs. Py.test (as pytest was called at the time) was already happy to do practically all of the heavy lifting for us. Pick this up, throw it at something, get a result compare the result to what you are looking for -- all of that was handled. So all we had to do was write the stuff that actually went out and ran the things in the browser. It's not a lot of code. https://bitbucket.org/pedronis/js-infrastructure/src Laura >-- >Alan G >Author of the Learn to Program web site >http://www.alan-g.me.uk/ From wumeid at hotmail.com Fri Jun 12 23:51:55 2015 From: wumeid at hotmail.com (Michelle Meiduo Wu) Date: Fri, 12 Jun 2015 17:51:55 -0400 Subject: [Tutor] Python&Pytest In-Reply-To: <201506122008.t5CK8tSN024722@fido.openend.se> References: <20150612055803.GA3778@cskk.homeip.net>, <201506121048.t5CAmOew005836@fido.openend.se>, <201506122008.t5CK8tSN024722@fido.openend.se> Message-ID: Yes, I also found Py.test is a good testing framework for automation testing. Another one is Robot testing framework. It's also a testing framework based on Python Unittest framework. Hard to pick one to use:) Thank you,Michelle > To: alan.gauld at btinternet.com > From: lac at openend.se > Date: Fri, 12 Jun 2015 22:08:55 +0200 > Subject: Re: [Tutor] Python&Pytest > CC: lac at openend.se; tutor at python.org > > In a message of Fri, 12 Jun 2015 17:26:42 +0100, Alan Gauld writes: > >I stand corrected but it still seems to me like its easier to > >test in the language in which you develop. And most languages > >have testing frameworks these days. > > Many languages have extremely poor testing frameworks. And when it > came time to do testing of the javascript code of the web client > of our python app, we found that there wasn't anything available > for doing exactly that. > > >And when there are large paradigm differences in the languages > >that's even more true. Testing JS (or even Haskell) in Python > >seems like a weird choice! > > I don't see this at all. By this logic, we would have been better > off writing a test framework in javascript to handle our javascript > code. But our experience is that, whenever possible, you are always > better off not using javascript and programming in another language. > Plus the real challenge here was testing our code in the collection > of browsers expected to run it. We found lots and lots and lots > of javascript bugs. > > Py.test (as pytest was called at the time) was already happy to do > practically all of the heavy lifting for us. Pick this up, throw it > at something, get a result compare the result to what you are looking > for -- all of that was handled. So all we had to do was write the > stuff that actually went out and ran the things in the browser. > > It's not a lot of code. > https://bitbucket.org/pedronis/js-infrastructure/src > > Laura > > >-- > >Alan G > >Author of the Learn to Program web site > >http://www.alan-g.me.uk/ > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From lac at openend.se Sat Jun 13 01:04:26 2015 From: lac at openend.se (Laura Creighton) Date: Sat, 13 Jun 2015 01:04:26 +0200 Subject: [Tutor] Python&Pytest In-Reply-To: Message from Michelle Meiduo Wu of "Fri, 12 Jun 2015 17:51:55 -0400." References: <20150612055803.GA3778@cskk.homeip.net>, <201506121048.t5CAmOew005836@fido.openend.se>, <201506122008.t5CK8tSN024722@fido.openend.se> Message-ID: <201506122304.t5CN4QCH029069@fido.openend.se> In a message of Fri, 12 Jun 2015 17:51:55 -0400, Michelle Meiduo Wu writes: >Yes, I also found Py.test is a good testing framework for automation testing. >Another one is Robot testing framework. It's also a testing framework based on Python Unittest framework. >Hard to pick one to use:) pytest (formerly py.test) came out of the pypy project. We needed something rather more complicated to test our python code given that we could not 'make a new pypy' every time we needed to run our tests. (That took hours). So we built this thing. However, Michael Foord ported a whole lot of what we needed (but the standard python unittest module didn't have) back into unittest. And these days lots of pytest has been rewritten enough times that I am no longer familiar with the code. But at the time we needed to write oejskit, py.test was the place to do it, in part because if we needed any changes to py.test to accomodate what we wanted, we could just sit down and write that too. Getting changes into something that is in the python standard library is a lot harder -- the political process is often orders of magnitude harder than just having working code. But py.test was a much more swiftly changing codebase at that time, and hardly anybody used it, and if we changed things so that their tests broke, they mostly were also benefitting from the new functionality -- and you don't develop on the bleeding edge if you aren't in some way excited by such changes ... These days, pytest is very stable, doesn't change much, and has tons of satisfied users who would be very, very, very upset if we upset their applecarts. So that doesn't happen. But it makes decisions like yours harder. I personally find unittest to be so verbose that it makes writing tests unpleasant. But other people do not share my dislike of verboseness, so my advice, again, is to try both for a week. And then see how you feel about it. Note that if you decide you like pytest, it comes with a script that I wrote to convert standard library unittests to pytest tests, so you won't waste that work. I don't know of any scripts that go the other way, but they may exist. best of luck, Laura From abhijeet560 at yahoo.in Sat Jun 13 17:03:37 2015 From: abhijeet560 at yahoo.in (abhijeet560 at yahoo.in) Date: Sat, 13 Jun 2015 15:03:37 +0000 (UTC) Subject: [Tutor] about the gui development Message-ID: <275462503.1448308.1434207817797.JavaMail.yahoo@mail.yahoo.com> Hello,i wanted to know about the gui development ,from where to began developing the apps in python ..?Which IDE is best suitable for me?? From alan.gauld at btinternet.com Sat Jun 13 18:43:08 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 13 Jun 2015 17:43:08 +0100 Subject: [Tutor] about the gui development In-Reply-To: <275462503.1448308.1434207817797.JavaMail.yahoo@mail.yahoo.com> References: <275462503.1448308.1434207817797.JavaMail.yahoo@mail.yahoo.com> Message-ID: On 13/06/15 16:03, abhijeet560 at yahoo.in wrote: > Hello,i wanted to know about the gui development , > from where to began developing the apps in python The standard GUI toolkit that comes with Python is Tkinter, with Tix and ttk for some extra features. There are many tutorials both online and in Python text books on how to use Tkinter. There are several other GUI toolkits that you can install, such as: - WxPython (based on the Wxwidgets toolkit) - PyQt/Side based on the Qt toolkit - PyGTK based on GTK - Dabo - an app framework based on WxPython and targeted at desktop database apps. > ..?Which IDE is best suitable for me?? That's a very personal choice. Personally I prefer Linux/Vim, others prefer emacs. Still other Eclipse or Netbeans. For GUI work you might be looking fore a drag n drop GUI builder of which there are a few around, although I didn't find any of them that great to be honest. Try Glade, Boa Constructor and Dabo. -- 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 lac at openend.se Sat Jun 13 19:15:12 2015 From: lac at openend.se (Laura Creighton) Date: Sat, 13 Jun 2015 19:15:12 +0200 Subject: [Tutor] about the gui development In-Reply-To: Message from of "Sat, 13 Jun 2015 15:03:37 -0000." <275462503.1448308.1434207817797.JavaMail.yahoo@mail.yahoo.com> References: <275462503.1448308.1434207817797.JavaMail.yahoo@mail.yahoo.com> Message-ID: <201506131715.t5DHFC91021520@fido.openend.se> In a message of Sat, 13 Jun 2015 15:03:37 -0000, abhijeet560 at yahoo.in writes: >Hello,i wanted to know about the gui development ,from where to began developing the apps in python ..?Which IDE is best suitable for me?? >_______________________________________________ >Tutor maillist - Tutor at python.org >To unsubscribe or change subscription options: >https://mail.python.org/mailman/listinfo/tutor What IDE to use -- if any, as some people still prefer editors -- is a very personal choice. There really is nothing to do for it but try a few and see what you like. Python has lots. Something to keep in mind, if you want to develop in Python 3, and not Python 2, is that not every IDE supports Python 3. (though most of them do.) See: https://wiki.python.org/moin/IntegratedDevelopmentEnvironments As for Gui toolkits, well, we have a page for that too. https://wiki.python.org/moin/GuiProgramming And, again we have lots. Here, the choice is a little less personal, but very much based on what you are used to. This, of course doesn't help the completely new person who isn't used to anything yet. Something to consider is where you want this code to eventually run. If you need it to run on your phone or a tablet, then the choices are much more limited than if you want it to run on a desktop or laptop computer. The final thing to consider is, do you really want to do gui programming at all, or would you be happier developing something that runs in a browser? If that has appeal, well, you guessed it, we have lots of browser frameworks, as well. https://wiki.python.org/moin/WebFrameworks One final thing -- there is nothing like having a friend who already knows somehting you would like to learn handy when you go to learn something. So if you have some local friendly talent, ask them what they recommend. I think that tkinter, for instance, is easier to use than PyQt, but if you have local PyQt experts, (and don't have tkinter experts) I would go with PyQt witout any hesitation. Best of luck, Laura Creighton From johnf at jfcomputer.com Sat Jun 13 20:40:45 2015 From: johnf at jfcomputer.com (john) Date: Sat, 13 Jun 2015 11:40:45 -0700 Subject: [Tutor] about the gui development In-Reply-To: <201506131715.t5DHFC91021520@fido.openend.se> References: <275462503.1448308.1434207817797.JavaMail.yahoo@mail.yahoo.com> <201506131715.t5DHFC91021520@fido.openend.se> Message-ID: <557C792D.80302@jfcomputer.com> Interesting question - what will be the end platform. If you really want a python solution: Tablets. phones, desktops - Kivy (very promising) Tablets. phones, desktops - PyQt Desktops - wxPython, tk, Dabo (python 2.7 at the moment) All the other GUI frameworks either have a very small following or are dying (my opinion of course). If you are not concerned with what language is used: Consider all the web frameworks. Several of the web frameworks work on the desktops, and are browser friendly. Atom/electron (not sure about the name) but in general web frameworks (no matter which one) is all about browsers. Johnf On 06/13/2015 10:15 AM, Laura Creighton wrote: > The final thing to consider is, do you really want to do gui programming > at all, or would you be happier developing something that runs in a browser? > If that has appeal, well, you guessed it, we have lots of browser > frameworks, as well. From akleider at sonic.net Sun Jun 14 20:56:15 2015 From: akleider at sonic.net (Alex Kleider) Date: Sun, 14 Jun 2015 11:56:15 -0700 Subject: [Tutor] python 3.4 documentation Message-ID: I'm using python 3.4 on an ubuntu 14.4 LTS OS and frequently find myself 'off line'. I'd like to download the standard library documentation to have at hand on my hard drive. I tried prompt> wget -r https://docs.python.org/3/library/index.html but links appear to be broken. I'd be grateful for advice as to the way to do this. Thanks in advance. Alex From hgfernan at gmail.com Sun Jun 14 21:36:15 2015 From: hgfernan at gmail.com (Hilton Fernandes) Date: Sun, 14 Jun 2015 16:36:15 -0300 Subject: [Tutor] python 3.4 documentation In-Reply-To: References: Message-ID: Hello, Alex ! I believe that maybe in the page https://docs.python.org/3/download.html you will find what you're looking for. All the best, Hilton On Sun, Jun 14, 2015 at 3:56 PM, Alex Kleider wrote: > I'm using python 3.4 on an ubuntu 14.4 LTS OS and frequently find myself > 'off line'. > I'd like to download the standard library documentation to have at hand on > my hard drive. > I tried > prompt> wget -r https://docs.python.org/3/library/index.html > but links appear to be broken. > I'd be grateful for advice as to the way to do this. > Thanks in advance. > Alex > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From __peter__ at web.de Sun Jun 14 21:39:27 2015 From: __peter__ at web.de (Peter Otten) Date: Sun, 14 Jun 2015 21:39:27 +0200 Subject: [Tutor] python 3.4 documentation References: Message-ID: Alex Kleider wrote: > I'm using python 3.4 on an ubuntu 14.4 LTS OS and frequently find myself > 'off line'. > I'd like to download the standard library documentation to have at hand > on my hard drive. > I tried > prompt> wget -r https://docs.python.org/3/library/index.html > but links appear to be broken. > I'd be grateful for advice as to the way to do this. > Thanks in advance. Go here https://docs.python.org/3/download.html and download an archived version with e. g. $ wget https://docs.python.org/3/archives/python-3.4.3-docs-html.tar.bz2 or use $ sudo apt-get install python3-doc to install the documentation that comes with Ubuntu. From lac at openend.se Sun Jun 14 23:52:45 2015 From: lac at openend.se (Laura Creighton) Date: Sun, 14 Jun 2015 23:52:45 +0200 Subject: [Tutor] python 3.4 documentation In-Reply-To: Message from Alex Kleider of "Sun, 14 Jun 2015 11:56:15 -0700." References: Message-ID: <201506142152.t5ELqj76028073@fido.openend.se> This is working for me https://docs.python.org/3.3/download.html Where do you find the broken link? That needs fixing. Laura From akleider at sonic.net Mon Jun 15 00:50:38 2015 From: akleider at sonic.net (Alex Kleider) Date: Sun, 14 Jun 2015 15:50:38 -0700 Subject: [Tutor] python 3.4 documentation In-Reply-To: References: Message-ID: <345ae25fab61f4986641f749205e4258@sonic.net> On 2015-06-14 12:36, Hilton Fernandes wrote: > Hello, Alex ! > > I believe that maybe in the page > https://docs.python.org/3/download.html Thank you Hilton, Laura and Peter for pointing me in the right direction. Being 'off line' will no longer be such a hardship. From lac at openend.se Mon Jun 15 02:13:04 2015 From: lac at openend.se (Laura Creighton) Date: Mon, 15 Jun 2015 02:13:04 +0200 Subject: [Tutor] python 3.4 documentation In-Reply-To: Message from Alex Kleider of "Sun, 14 Jun 2015 15:50:38 -0700." <345ae25fab61f4986641f749205e4258@sonic.net> References: <345ae25fab61f4986641f749205e4258@sonic.net> Message-ID: <201506150013.t5F0D4uM031328@fido.openend.se> In a message of Sun, 14 Jun 2015 15:50:38 -0700, Alex Kleider writes: >On 2015-06-14 12:36, Hilton Fernandes wrote: >> Hello, Alex ! >> >> I believe that maybe in the page >> https://docs.python.org/3/download.html > >Thank you Hilton, Laura and Peter for pointing me in the right >direction. >Being 'off line' will no longer be such a hardship. You are most welcome, but I want to go fix this for the next person who comes along. Where did you find the bad link? Or, if you just assumed that the one you tried would work, what can we do to keep the next person from assuming the same thing? Laura From akleider at sonic.net Mon Jun 15 04:59:00 2015 From: akleider at sonic.net (Alex Kleider) Date: Sun, 14 Jun 2015 19:59:00 -0700 Subject: [Tutor] python 3.4 documentation In-Reply-To: <201506150013.t5F0D4uM031328@fido.openend.se> References: <345ae25fab61f4986641f749205e4258@sonic.net> <201506150013.t5F0D4uM031328@fido.openend.se> Message-ID: On 2015-06-14 17:13, Laura Creighton wrote: > In a message of Sun, 14 Jun 2015 15:50:38 -0700, Alex Kleider writes: >> On 2015-06-14 12:36, Hilton Fernandes wrote: >>> Hello, Alex ! >>> >>> I believe that maybe in the page >>> https://docs.python.org/3/download.html >> >> Thank you Hilton, Laura and Peter for pointing me in the right >> direction. >> Being 'off line' will no longer be such a hardship. > > You are most welcome, but I want to go fix this for the next person > who comes along. Where did you find the bad link? Or, if you just > assumed that the one you tried would work, what can we do to keep the > next person from assuming the same thing? > > Laura Here's the command I initially used: prompt> wget -r https://docs.python.org/3/library/index.html The directory that resulted seemed to have everything but when I tried to use links, none worked. I have since deleted the above and downloaded (and 'untared') as follows: prompt> tar -xvjf python-3.4.3-docs-html.tar.bz2 All is now well. I could repeat the (wget) process and give you more detailed information if that would be helpful. (Let me know.) Alex From steve at pearwood.info Mon Jun 15 05:46:08 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 15 Jun 2015 13:46:08 +1000 Subject: [Tutor] python 3.4 documentation In-Reply-To: <201506150013.t5F0D4uM031328@fido.openend.se> References: <201506150013.t5F0D4uM031328@fido.openend.se> Message-ID: <20150615034608.GA20701@ando.pearwood.info> On Mon, Jun 15, 2015 at 02:13:04AM +0200, Laura Creighton wrote: > In a message of Sun, 14 Jun 2015 15:50:38 -0700, Alex Kleider writes: > >On 2015-06-14 12:36, Hilton Fernandes wrote: > >> Hello, Alex ! > >> > >> I believe that maybe in the page > >> https://docs.python.org/3/download.html > > > >Thank you Hilton, Laura and Peter for pointing me in the right > >direction. > >Being 'off line' will no longer be such a hardship. > > You are most welcome, but I want to go fix this for the next person > who comes along. Where did you find the bad link? Or, if you just > assumed that the one you tried would work, what can we do to keep the > next person from assuming the same thing? I think that what Alex means is that after downloading the docs via wget, the links were broken in his local copy. I'm not sure if that's to be expected or not. If the web pages are static, then you should be able to download with wget and have it work locally, but perhaps not if the webserver is doing something funny, or if Alex got the wget command wrong. -- Steve From steve at pearwood.info Mon Jun 15 05:49:44 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 15 Jun 2015 13:49:44 +1000 Subject: [Tutor] python 3.4 documentation In-Reply-To: References: Message-ID: <20150615034944.GC20701@ando.pearwood.info> On Sun, Jun 14, 2015 at 11:56:15AM -0700, Alex Kleider wrote: > I'm using python 3.4 on an ubuntu 14.4 LTS OS and frequently find myself > 'off line'. The Python interactive interpreter comes with a powerful interactive help system. At the Python prompt, you can enter: help() help("keyword") # e.g. "raise" help(any_object) to get help and documentation. -- Steve From adeadmarshal at gmail.com Mon Jun 15 09:11:37 2015 From: adeadmarshal at gmail.com (Ali Moradi) Date: Mon, 15 Jun 2015 11:41:37 +0430 Subject: [Tutor] How to make clickable listbox from database by Tkinter Message-ID: hi, i use python 2. how can i add a listbox under the entry and button widgets? i want to use database to fill the listbox, both fields in the database (English and Esperanto) listbox should be like this (words are beside eachother: *English* *Esperanto* water akvo father patro and so on... it's a dictionary app. i want to make the items in the list searchable, and when the user types and clicks on the button, it shows the word. files are attached. thanks a bunch, i'm a beginner in python! :) From alan.gauld at btinternet.com Mon Jun 15 10:03:09 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 15 Jun 2015 09:03:09 +0100 Subject: [Tutor] How to make clickable listbox from database by Tkinter In-Reply-To: References: Message-ID: On 15/06/15 08:11, Ali Moradi wrote: > how can i add a listbox under the entry and button widgets? Can you clarify that sentence? What do you mean by "under"? Do you want the list box to be located on the same form as two widgets but underneath? Or do you want the listbox to appear when you press the button? If its the first then it will be down to using the correct layout manager (pack, grid, place etc) in conjunction with one or more Frame containers. If its the second the jn you will need to say where the listbox should appear: in a dialog or on the existing form. > i want to use database to fill the listbox, both fields in the database > (English and Esperanto) What kind of database? You can attach Python to most databases but there are differences depending on the exact database you use. Is it SQL or a flat file database? > listbox should be like this (words are beside each other: > > *English* *Esperanto* > water akvo > father patro > > and so on... That's probably just a string formatting task. > i want to make the items in the list searchable, and when the user types > and clicks on the button, it shows the word. You must be more specific. We can't read your mind. If the user clicks on the button it should show which word? I assume you mean if the user enters a word in the entry widget and then presses the button then the list box should arrange its contents such that the user word and its pair are both visible? And maybe highlighted too? I'm guessing that the word entered can be in either English or Esperanto? So if the user enters 'water' it will show and highlight the line: "water akvo" And if the user enters the word 'patro' it will show and highlight the line: "father patro" Is that what you mean? > files are attached. This is a text based mailing list, your attachments have disappeared in transit (at least for me). Please send the files as text embedded in your mail. (Please be sure to use plain text email for this as HTML will mess up the formatting). If the files are long, say >100 lines put them on a pastebin type site and send a link. -- 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 lac at openend.se Mon Jun 15 12:34:22 2015 From: lac at openend.se (Laura Creighton) Date: Mon, 15 Jun 2015 12:34:22 +0200 Subject: [Tutor] python 3.4 documentation In-Reply-To: Message from Alex Kleider of "Sun, 14 Jun 2015 19:59:00 -0700." References: <345ae25fab61f4986641f749205e4258@sonic.net> <201506150013.t5F0D4uM031328@fido.openend.se> Message-ID: <201506151034.t5FAYMB7013141@fido.openend.se> In a message of Sun, 14 Jun 2015 19:59:00 -0700, Alex Kleider writes: >On 2015-06-14 17:13, Laura Creighton wrote: >> In a message of Sun, 14 Jun 2015 15:50:38 -0700, Alex Kleider writes: >>> On 2015-06-14 12:36, Hilton Fernandes wrote: >>>> Hello, Alex ! >>>> >>>> I believe that maybe in the page >>>> https://docs.python.org/3/download.html >>> >>> Thank you Hilton, Laura and Peter for pointing me in the right >>> direction. >>> Being 'off line' will no longer be such a hardship. >> >> You are most welcome, but I want to go fix this for the next person >> who comes along. Where did you find the bad link? Or, if you just >> assumed that the one you tried would work, what can we do to keep the >> next person from assuming the same thing? >> >> Laura > >Here's the command I initially used: >prompt> wget -r https://docs.python.org/3/library/index.html > >The directory that resulted seemed to have everything but when I tried >to use links, none worked. >I have since deleted the above and downloaded (and 'untared') as >follows: >prompt> tar -xvjf python-3.4.3-docs-html.tar.bz2 >All is now well. > >I could repeat the (wget) process and give you more detailed information >if that would be helpful. >(Let me know.) >Alex Yes please. Laura From adeadmarshal at gmail.com Mon Jun 15 12:38:02 2015 From: adeadmarshal at gmail.com (Ali Moradi) Date: Mon, 15 Jun 2015 15:08:02 +0430 Subject: [Tutor] Tutor Digest, Vol 136, Issue 27 In-Reply-To: References: Message-ID: let me put it this way: the listbox should be on the same frame under the entry widget and the whole list should be visible, when the user types the word in Entry widger and clicks on search button, the listbox narrows down to that word only and now just (for example: water akvo) are visible. do you know what i mean? i'm not native english speaker so maybe i can't explain it :( the code and my database is in the file uploaded (the database is sqlite3 [i made it in ubuntu linux with SQLiteBrowser program]): http://qfs.mobi/f2361208 https://drive.google.com/file/d/0Bwe9iYyAhRzgT3hudnAxUkVzTTA/view?usp=sharing On Mon, Jun 15, 2015 at 2:30 PM, 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: python 3.4 documentation (Steven D'Aprano) > 2. How to make clickable listbox from database by Tkinter > (Ali Moradi) > 3. Re: How to make clickable listbox from database by Tkinter > (Alan Gauld) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Mon, 15 Jun 2015 13:49:44 +1000 > From: Steven D'Aprano > To: tutor at python.org > Subject: Re: [Tutor] python 3.4 documentation > Message-ID: <20150615034944.GC20701 at ando.pearwood.info> > Content-Type: text/plain; charset=us-ascii > > On Sun, Jun 14, 2015 at 11:56:15AM -0700, Alex Kleider wrote: > > I'm using python 3.4 on an ubuntu 14.4 LTS OS and frequently find myself > > 'off line'. > > The Python interactive interpreter comes with a powerful interactive > help system. At the Python prompt, you can enter: > > help() > > help("keyword") # e.g. "raise" > > help(any_object) > > > to get help and documentation. > > > -- > Steve > > > ------------------------------ > > Message: 2 > Date: Mon, 15 Jun 2015 11:41:37 +0430 > From: Ali Moradi > To: tutor at python.org > Subject: [Tutor] How to make clickable listbox from database by > Tkinter > Message-ID: > GtEMz+dsL2fghNWfcpX3V83LA at mail.gmail.com> > Content-Type: text/plain; charset=UTF-8 > > hi, i use python 2. > > how can i add a listbox under the entry and button widgets? > > i want to use database to fill the listbox, both fields in the database > (English and Esperanto) > > listbox should be like this (words are beside eachother: > > *English* *Esperanto* > water akvo > father patro > > and so on... > > it's a dictionary app. > > i want to make the items in the list searchable, and when the user types > and clicks on the button, it shows the word. > > files are attached. > > thanks a bunch, i'm a beginner in python! :) > > > ------------------------------ > > Message: 3 > Date: Mon, 15 Jun 2015 09:03:09 +0100 > From: Alan Gauld > To: tutor at python.org > Subject: Re: [Tutor] How to make clickable listbox from database by > Tkinter > Message-ID: > Content-Type: text/plain; charset=windows-1252; format=flowed > > On 15/06/15 08:11, Ali Moradi wrote: > > > how can i add a listbox under the entry and button widgets? > > Can you clarify that sentence? What do you mean by "under"? > Do you want the list box to be located on the same form as > two widgets but underneath? Or do you want the listbox > to appear when you press the button? > > If its the first then it will be down to using the > correct layout manager (pack, grid, place etc) in > conjunction with one or more Frame containers. > > If its the second the jn you will need to say where > the listbox should appear: in a dialog or on the > existing form. > > > i want to use database to fill the listbox, both fields in the database > > (English and Esperanto) > > What kind of database? You can attach Python to most databases > but there are differences depending on the exact database > you use. Is it SQL or a flat file database? > > > listbox should be like this (words are beside each other: > > > > *English* *Esperanto* > > water akvo > > father patro > > > > and so on... > > That's probably just a string formatting task. > > > i want to make the items in the list searchable, and when the user types > > and clicks on the button, it shows the word. > > You must be more specific. We can't read your mind. > If the user clicks on the button it should show which word? > > I assume you mean if the user enters a word in the entry > widget and then presses the button then the list box should > arrange its contents such that the user word and its pair > are both visible? And maybe highlighted too? > > I'm guessing that the word entered can be in either English > or Esperanto? So if the user enters 'water' it will show > and highlight the line: > "water akvo" > And if the user enters the word 'patro' it will show > and highlight the line: > "father patro" > > Is that what you mean? > > > files are attached. > > This is a text based mailing list, your attachments have > disappeared in transit (at least for me). Please send the files > as text embedded in your mail. (Please be sure to use plain > text email for this as HTML will mess up the formatting). > If the files are long, say >100 lines put them on a pastebin > type site and send a link. > > > -- > 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 136, Issue 27 > ************************************** > From adeadmarshal at gmail.com Mon Jun 15 15:41:50 2015 From: adeadmarshal at gmail.com (Ali Moradi) Date: Mon, 15 Jun 2015 18:11:50 +0430 Subject: [Tutor] Clickable listbox in Tkinter python 2 Message-ID: let me put it this way: the listbox should be on the same frame under the entry widget and the whole list should be visible, when the user types the word in Entry widger and clicks on search button, the listbox narrows down to that word only and now just (for example: water akvo) are visible. do you know what i mean? i'm not native english speaker so maybe i can't explain it :( the code and my database is in the file uploaded (the database is sqlite3 [i made it in ubuntu linux with SQLiteBrowser program]): http://qfs.mobi/f2361208 https://drive.google.com/file/d/0Bwe9iYyAhRzgT3hudnAxUkVzTTA/view?usp=sharing From David.Aldrich at EMEA.NEC.COM Mon Jun 15 13:03:27 2015 From: David.Aldrich at EMEA.NEC.COM (David Aldrich) Date: Mon, 15 Jun 2015 11:03:27 +0000 Subject: [Tutor] How to import a dictionary from another module? Message-ID: <41302A7145AC054FA7A96CFD03835A0A0B982283@EX10MBX02.EU.NEC.COM> Hi I have defined a dictionary in a module: mydir.py: REG_LOOKUP = { 'REG_1' : some_value1, 'REG_2' : some_value2, } How would I import that dictionary from my main() function (which lives in a different module) please? Best regards David From lac at openend.se Mon Jun 15 16:58:54 2015 From: lac at openend.se (Laura Creighton) Date: Mon, 15 Jun 2015 16:58:54 +0200 Subject: [Tutor] Tutor Digest, Vol 136, Issue 27 In-Reply-To: Message from Ali Moradi of "Mon, 15 Jun 2015 15:08:02 +0430." References: Message-ID: <201506151458.t5FEwsmd019660@fido.openend.se> This doesn't quite do what you want but should give you some ideas as to how to proceed. https://mail.python.org/pipermail/tkinter-discuss/2012-January/003041.html Laura From breamoreboy at yahoo.co.uk Mon Jun 15 17:07:34 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 15 Jun 2015 16:07:34 +0100 Subject: [Tutor] How to import a dictionary from another module? In-Reply-To: <41302A7145AC054FA7A96CFD03835A0A0B982283@EX10MBX02.EU.NEC.COM> References: <41302A7145AC054FA7A96CFD03835A0A0B982283@EX10MBX02.EU.NEC.COM> Message-ID: On 15/06/2015 12:03, David Aldrich wrote: > Hi > > I have defined a dictionary in a module: > > mydir.py: > > REG_LOOKUP = { > 'REG_1' : some_value1, > 'REG_2' : some_value2, > } > > How would I import that dictionary from my main() function (which lives in a different module) please? > > Best regards > > David > import othermodule ... othermodule.REG_LOOKUP{whatever} OR from othermodule import REG_LOOKUP ... REG_LOOKUP{whatever} You can also use from othermodule import * but this is frowned upon as it pollutes your namespace, potentially giving all sorts of weird and wonderful situations. I never use it. -- 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 Mon Jun 15 17:57:05 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 15 Jun 2015 16:57:05 +0100 Subject: [Tutor] Clickable listbox in Tkinter python 2 In-Reply-To: References: Message-ID: On 15/06/15 14:41, Ali Moradi wrote: > the listbox should be on the same frame under the entry widget and the > whole list should be visible, when the user types the word in Entry widger > and clicks on search button, the listbox narrows down to that word only and > now just (for example: water akvo) are visible. do you know what i mean? > i'm not native english speaker so maybe i can't explain it :( OK I think I've got it. You might want to make the list scrollable since there will probably be more entries than can fit in a single widget at one time. As to making the list shrink down to a single entry, that will be your job, it is not a standard feature. Essentially you will need to select all the pairs initially from SQLite and then select only the matching pair after a search. If you don't know how to do database searches from Python ask about that in a separate thread. As to the layout something like(for Python 3): import tkinter as tk words = ['a','list','of','strings'] def search(): target = eSearch.get() if target in words: tList.delete(0.0,tk.END) tList.insert(0.0,target) top = tk.Tk() eSearch = tk.Entry(top) eSearch.pack() tList = tk.Text() tList.insert(0.0, '\n'.join(words)) tList.pack() bSearch = tk.Button(top, text='Search', command=search) bSearch.pack() top.mainloop() is as simple as it gets. You can modify the sizes by using the width/height widget options of course. You can be much more sophisticated but that should get you started. > http://qfs.mobi/f2361208 > > https://drive.google.com/file/d/0Bwe9iYyAhRzgT3hudnAxUkVzTTA/view?usp=sharing Neither of those show me code, they seem to want me to download something. Since I never download from untrusted sources I can't see the code. Try pasting it somewhere like http://www.pastebin.com -- 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.Aldrich at EMEA.NEC.COM Mon Jun 15 16:49:39 2015 From: David.Aldrich at EMEA.NEC.COM (David Aldrich) Date: Mon, 15 Jun 2015 14:49:39 +0000 Subject: [Tutor] How to import a dictionary from another module? In-Reply-To: <41302A7145AC054FA7A96CFD03835A0A0B982283@EX10MBX02.EU.NEC.COM> References: <41302A7145AC054FA7A96CFD03835A0A0B982283@EX10MBX02.EU.NEC.COM> Message-ID: <41302A7145AC054FA7A96CFD03835A0A0B98248A@EX10MBX02.EU.NEC.COM> Hi I have a solution for this now. Best regards David > -----Original Message----- > From: Tutor [mailto:tutor-bounces+david.aldrich=eu.nec.com at python.org] > On Behalf Of David Aldrich > Sent: 15 June 2015 12:03 > To: tutor at python.org > Subject: [Tutor] How to import a dictionary from another module? > > Hi > > I have defined a dictionary in a module: > > mydir.py: > > REG_LOOKUP = { > 'REG_1' : some_value1, > 'REG_2' : some_value2, > } > > How would I import that dictionary from my main() function (which lives in a > different module) please? > > Best regards > > David > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > > > Click > https://www.mailcontrol.com/sr/Q2tIWP1gKVLGX2PQPOmvUlvAwUAcTfZne > qTtIw9m3Q8SQ0yRarxngdZVWY3fkqP66uKlINFphbKNI5tH4SJ!Mg== to > report this email as spam. From akleider at sonic.net Tue Jun 16 04:59:05 2015 From: akleider at sonic.net (Alex Kleider) Date: Mon, 15 Jun 2015 19:59:05 -0700 Subject: [Tutor] python 3.4 documentation In-Reply-To: <20150615034944.GC20701@ando.pearwood.info> References: <20150615034944.GC20701@ando.pearwood.info> Message-ID: <34e7d5d0bb2a5238f1475a4069ba10eb@sonic.net> On 2015-06-14 20:49, Steven D'Aprano wrote: > The Python interactive interpreter comes with a powerful interactive > help system. At the Python prompt, you can enter: > > help() > > help("keyword") # e.g. "raise" > > help(any_object) > > > to get help and documentation. Thank you for this tip. I sort of was aware of it but had no idea of how much help was there. I certainly had no idea that modules were documented as well: alex at t61p:~$ python3 Python 3.4.0 (default, Apr 11 2014, 13:05:18) [GCC 4.8.2] on linux Type "help", "copyright", "credits" or "license" for more information. >>> help('key words') no Python documentation found for 'key words' >>> help('keywords') Here is a list of the Python keywords. Enter any keyword to get more help. False def if raise None del import return True elif in try and else is while as except lambda with assert finally nonlocal yield break for not class from or continue global pass >>> import csv >>> help('csv') ...and documentation of the modules appears in the pager! From ben+python at benfinney.id.au Tue Jun 16 05:09:28 2015 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 16 Jun 2015 13:09:28 +1000 Subject: [Tutor] python 3.4 documentation References: <20150615034944.GC20701@ando.pearwood.info> <34e7d5d0bb2a5238f1475a4069ba10eb@sonic.net> Message-ID: <85k2v4tklz.fsf@benfinney.id.au> Alex Kleider writes: > >>> import csv > >>> help('csv') > ...and documentation of the modules appears in the pager! Yes. This is positive reinforcement for writing meaningful, standardised docstrings for every code object (module, class, function): the docstring is automatically available for browsing at the interactive prompt, in the context of the object itself. The flip side is: the documentation available there is only as good as the documentation that has been written as a docstring for that object. Encourage authors of libraries you use to maintain and improve their docstrings :-) -- \ ?It's my belief we developed language because of our deep inner | `\ need to complain.? ?Jane Wagner, via Lily Tomlin | _o__) | Ben Finney From adeadmarshal at gmail.com Tue Jun 16 14:47:36 2015 From: adeadmarshal at gmail.com (Ali Moradi) Date: Tue, 16 Jun 2015 17:17:36 +0430 Subject: [Tutor] clickable listbox from sqlite database. Message-ID: Hi, you got what i mean thanks, your code (http://pastebin.com/VbaVKJgj) was so good. now i want to do two more things. i want to fill the listbox from my database which contains of one table (Words) and two fields (English) and (Esperanto), how can i do that? i want the program to be the same just the words loaded from my sqlite database. and second thing: i want to search the word when user hits "Enter" on keyboard, so user doesn't have to click on search button all the time! thanks a bunch. code: http://pastebin.com/VbaVKJgj From anubhav1691 at gmail.com Tue Jun 16 17:45:01 2015 From: anubhav1691 at gmail.com (Anubhav Yadav) Date: Tue, 16 Jun 2015 21:15:01 +0530 Subject: [Tutor] Help understanding list comprehensions Message-ID: I have a doubt. I had a list like this [['Varun', 19.0], ['Kakunami', 19.0], ['Harsh', 20.0], ['Beria', 20.0], ['Vikas', 21.0]] I am using a for loop to del the rows with the lowest value like this: for row in marks: if row[1] == lowest: marks.remove(row) But after running this loop, I get the following: [['Kakunami', 19.0], ['Harsh', 20.0], ['Beria', 20.0], ['Vikas', 21.0]] If I print row for every iteration one row is missed in the iteration. Here is the output. ['Varun', 19.0] ['Harsh', 20.0] ['Beria', 20.0] ['Vikas', 21.0] If I use list comprehensions, I get the right output. I just want to understand what is happening. Can anyone help me out here? This if from an hackerrank assignment. From stephanie.quiles001 at albright.edu Tue Jun 16 18:45:06 2015 From: stephanie.quiles001 at albright.edu (Stephanie Quiles) Date: Tue, 16 Jun 2015 12:45:06 -0400 Subject: [Tutor] create class Pet Message-ID: Hello, Having trouble figuring out why this program is not running. could someone please take a look and see where I am going wrong? Here is the error message i am getting : /Library/Frameworks/Python.framework/Versions/3.4/bin/python3.4 /Users/stephaniequiles/PycharmProjects/untitled3/pets.py Traceback (most recent call last): File "/Users/stephaniequiles/PycharmProjects/untitled3/pets.py", line 2, in def main(get_name=name): NameError: name 'name' is not defined Process finished with exit code 1 Thanks !!!! Code is below: # __author__ = 'stephaniequiles' # write a class named Pet should include __name, __animal_type, __age class Pet: # pet class should have an __init__ method that creates these attributes. def __init__(self, name, animal_type, age): self.__name = 'name' self.__animal_type = 'animal_type' self.__age = 'age' def set_name(self, name): self.__name = 'name' def set_type(self, animal_type): self.__animal_type = animal_type def set_age(self, age): self.__age = age def get_name(self): return self.__name def get_animal_type(self): return self.__animal_type def get_age(self): return self.__age # create methods, set_name , set_animal_type, set_age, get_name, get_animal_type # get_age # write a program that creates an object of the class and prompts the use to enter # name, type, age of their pet. # data should be stored as objects attributes. # use objects accessor methods to retrieve the pet's name, type and age # display data on screen # __author__ = 'stephaniequiles' def main(): name = input('what is the name of the pet?: ') animal_type = ('Please enter a type of pet: ') age = int(input('Enter age of pet: ')) self.get_name(name, animal_type, age) print('This will be saved to file.') print('Here is a the data you entered: ') print('Pet Name: ', pet.get_name) print('Animal Type:', pet.get_animal_type) print('Age: ', pet.get_age) main() From alan.gauld at btinternet.com Tue Jun 16 20:10:21 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 16 Jun 2015 19:10:21 +0100 Subject: [Tutor] create class Pet In-Reply-To: References: Message-ID: On 16/06/15 17:45, Stephanie Quiles wrote: > File "/Users/stephaniequiles/PycharmProjects/untitled3/pets.py", line 2, in > def main(get_name=name): > NameError: name 'name' is not defined There is an inconsistency here. The code you have shown does not match the error. The error says the def main statememt looks like def main(get_name=name): and is on line 2 of pets.py. But your def main is near the end of the file and has no get_name parameter. Either you are running the wrong file or you have changed it. Until the error matches the code there is little else we can do. > # __author__ = 'stephaniequiles' > > # write a class named Pet should include __name, __animal_type, __age > > class Pet: > # pet class should have an __init__ method that creates these attributes. > def __init__(self, name, animal_type, age): > self.__name = 'name' > self.__animal_type = 'animal_type' > self.__age = 'age' > > def set_name(self, name): > self.__name = 'name' > > def set_type(self, animal_type): > self.__animal_type = animal_type > > def set_age(self, age): > self.__age = age > > def get_name(self): > return self.__name > > def get_animal_type(self): > return self.__animal_type > > def get_age(self): > return self.__age > > # create methods, set_name , set_animal_type, set_age, get_name, get_animal_type > # get_age > > # write a program that creates an object of the class and prompts the use to enter > # name, type, age of their pet. > > # data should be stored as objects attributes. > # use objects accessor methods to retrieve the pet's name, type and age > # display data on screen > > # __author__ = 'stephaniequiles' > def main(): > name = input('what is the name of the pet?: ') > animal_type = ('Please enter a type of pet: ') > age = int(input('Enter age of pet: ')) > self.get_name(name, animal_type, age) > print('This will be saved to file.') > print('Here is a the data you entered: ') > print('Pet Name: ', pet.get_name) > print('Animal Type:', pet.get_animal_type) > print('Age: ', pet.get_age) > > > main() > > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- 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 Jun 16 20:17:37 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 16 Jun 2015 19:17:37 +0100 Subject: [Tutor] Help understanding list comprehensions In-Reply-To: References: Message-ID: On 16/06/15 16:45, Anubhav Yadav wrote: > I have a doubt. So have I. I can't se your code so I don't know what's happening. Don't make us guess, show us the code. > > I had a list like this > > [['Varun', 19.0], ['Kakunami', 19.0], ['Harsh', 20.0], ['Beria', 20.0], > ['Vikas', 21.0]] But its not assigned to anything? Or did you really define it by assigning it to a variable - marks maybe? If so show us the code. > I am using a for loop to del the rows with the lowest value like this: > > for row in marks: > if row[1] == lowest: > marks.remove(row) What is 'lowest'? You don;t define it anywhere so you should get an error. Or maybe you do but you haven't shown us? > But after running this loop, I get the following: > > [['Kakunami', 19.0], ['Harsh', 20.0], ['Beria', 20.0], ['Vikas', 21.0]] So it deleted Varun. I'm guessing but what happened next was that the list counter now pointed at index 1, but with Varun gone that is now Harsh, so it never tests Kakunami. Removing elements from the thing you are iterating over is like cutting off the tree branch you are standing on - a bad idea. Either take a copy of the list or use a while loop... > If I print row for every iteration one row is missed in the iteration. Here > is the output. > > ['Varun', 19.0] > ['Harsh', 20.0] > ['Beria', 20.0] > ['Vikas', 21.0] Which is very odd because its a different set from the previous 'result' above. But maybe if you showed us the code we could understand it. > If I use list comprehensions, I get the right output. I just want to > understand what is happening. Can anyone help me out here? How do you use the list comprehension(s)? Shjow us the code and we might see why there is a difference. Don't make us guess. -- 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 Jun 16 20:36:20 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 16 Jun 2015 19:36:20 +0100 Subject: [Tutor] clickable listbox from sqlite database. In-Reply-To: References: Message-ID: On 16/06/15 13:47, Ali Moradi wrote: > i want to fill the listbox from my database which contains of one table > (Words) and two fields (English) and (Esperanto), how can i do that? i want > the program to be the same just the words loaded from my sqlite database. Do you know SQL? And if so do you know how to call SQL from Python? If the answer to either is no then can I suggest you read my database topic in my tutorial, then come back here and ask again if it still doesn't make sense. > and second thing: i want to search the word when user hits "Enter" on > keyboard, so user doesn't have to click on search button all the time! You need the Tkinter bind() function. It connects events to functions. Using my code it will look something like: eSearch = tk.Entry(top) eSearch.pack() eSearch.bind('', lambda e: search()) If you don't understand the lambda bit you could do it this way instead... modify search to be: def search(event=None): target = eSearch.get() if target in words: tList.delete(0.0,tk.END) tList.insert(0.0,target) And change the bind above to be: eSearch.bind('', search) Or just go and research lambda :-) -- 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 turtle at 64.hu Tue Jun 16 19:44:42 2015 From: turtle at 64.hu (=?UTF-8?B?VsOhbGFzIFDDqXRlcg==?=) Date: Tue, 16 Jun 2015 19:44:42 +0200 Subject: [Tutor] Help understanding list comprehensions In-Reply-To: References: Message-ID: What is the exact meaning of "marks" and "lowest" in your script? Where are they defined?0 From breamoreboy at yahoo.co.uk Tue Jun 16 21:49:08 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 16 Jun 2015 20:49:08 +0100 Subject: [Tutor] create class Pet In-Reply-To: References: Message-ID: On 16/06/2015 17:45, Stephanie Quiles wrote: > Hello, Having trouble figuring out why this program is not running. could someone please take a look and see where I am going wrong? Here is the error message i am getting : /Library/Frameworks/Python.framework/Versions/3.4/bin/python3.4 /Users/stephaniequiles/PycharmProjects/untitled3/pets.py > Traceback (most recent call last): > File "/Users/stephaniequiles/PycharmProjects/untitled3/pets.py", line 2, in > def main(get_name=name): > NameError: name 'name' is not defined > > Process finished with exit code 1 > > Thanks !!!! > > Code is below: > > > # __author__ = 'stephaniequiles' > > # write a class named Pet should include __name, __animal_type, __age > > class Pet: > # pet class should have an __init__ method that creates these attributes. > def __init__(self, name, animal_type, age): > self.__name = 'name' > self.__animal_type = 'animal_type' > self.__age = 'age' > > def set_name(self, name): > self.__name = 'name' Further to Alan's answer the above methods are wrong. You're setting all the instance variables to strings instead of the actual variable names. Get rid of the single quotes. -- 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 Wed Jun 17 01:00:55 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 17 Jun 2015 00:00:55 +0100 Subject: [Tutor] Help understanding list comprehensions In-Reply-To: References: Message-ID: <5580AAA7.1050704@btinternet.com> On 16/06/15 20:39, Anubhav Yadav wrote: > I am sorry I didn't posted my code. I had solved this question long > back on hackerrank, and I couldn't figure out why this behaviour was > seen in this problem, so I had posted this question on their > discussion forum. Couldn't get a good answer so I decided to post > here. Luckily I found the revision history of my submission there > where I could find the earlier code which was giving this error. > > Here is the code. > > marks = [['Varun', 19.0], ['Kakunami', 19.0], ['Harsh', 20.0], > ['Beria', 20.0], ['Vikas', 21.0]] > marks = sorted(marks, key=lambda score:score[1]) > lowest = marks[0][1] > > for row in marks: > if row[1] == lowest: > marks.remove(row) > I already explained why this messes up, don;t mutate the thing you are iterating over. > second_lowest = marks[0][1] This doesn't work because the loop didn't work. > sh = [] > for row in marks: > if second_lowest == row[1]: > sh.append(row) > This could be a comprehension if you wanted sh = [ row for row in marks if second_lowest == row[1] ] But you haven't shown where you printed the 'output' that was wrong, nor have you shown the comprehensions which 'worked'. As it is you need to fix the first for loop before anything else can work as you want it to. -- 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 anubhav1691 at gmail.com Tue Jun 16 21:39:13 2015 From: anubhav1691 at gmail.com (Anubhav Yadav) Date: Wed, 17 Jun 2015 01:09:13 +0530 Subject: [Tutor] Help understanding list comprehensions In-Reply-To: References: Message-ID: I am sorry I didn't posted my code. I had solved this question long back on hackerrank, and I couldn't figure out why this behaviour was seen in this problem, so I had posted this question on their discussion forum. Couldn't get a good answer so I decided to post here. Luckily I found the revision history of my submission there where I could find the earlier code which was giving this error. Here is the code. marks = [['Varun', 19.0], ['Kakunami', 19.0], ['Harsh', 20.0], ['Beria', 20.0], ['Vikas', 21.0]] marks = sorted(marks, key=lambda score:score[1]) lowest = marks[0][1] for row in marks: if row[1] == lowest: marks.remove(row) second_lowest = marks[0][1] sh = [] for row in marks: if second_lowest == row[1]: sh.append(row) for row in sorted(sh): print row[0] From stephanie.quiles001 at albright.edu Tue Jun 16 22:15:28 2015 From: stephanie.quiles001 at albright.edu (Stephanie Quiles) Date: Tue, 16 Jun 2015 16:15:28 -0400 Subject: [Tutor] create class Pet In-Reply-To: References: Message-ID: <2A8FF6BB-B9A6-40D9-B5B7-2F3EED0B32A9@albright.edu> > sorry this is the correct error. it allows me to enter name and age but then i get the message: /Library/Frameworks/Python.framework/Versions/3.4/bin/python3.4 /Users/stephaniequiles/PycharmProjects/untitled3/pets.py what is the name of the pet?: riley Please enter a type of pet: cat Enter age of pet: 11 Traceback (most recent call last): File "/Users/stephaniequiles/PycharmProjects/untitled3/pets.py", line 15, in main() File "/Users/stephaniequiles/PycharmProjects/untitled3/pets.py", line 7, in main pet.get_name(name, animal_type, age) AttributeError: 'module' object has no attribute 'get_name' Process finished with exit code 1 class Pet: # pet class should have an __init__ method that creates these attributes. def __init__(self, name, animal_type, age): self.__name = "name" self.__animal_type = "animal_type" self.__age = "age" def set_name(self, name): self.__name = "name" def set_type(self, animal_type): self.__animal_type = animal_type def set_age(self, age): self.__age = age def get_name(self): return self.__name def get_animal_type(self): return self.__animal_type def get_age(self): return self.__age # create methods, set_name , set_animal_type, set_age, get_name, get_animal_type # get_age # write a program that creates an object of the class and prompts the use to enter # name, type, age of their pet. # data should be stored as objects attributes. # use objects accessor methods to retrieve the pet's name, type and age # display data on screen # __author__ = 'stephaniequiles' import pet def main(): name = input("what is the name of the pet?: ") animal_type = input("Please enter a type of pet: ") age = input("Enter age of pet: ") pet.get_name(name, animal_type, age) print("This will be saved to file.") print("Here is a the data you entered: ") print("Pet Name: ", pet.get_name) print("Animal Type:", pet.get_animal_type) print("Age: ", pet.get_age) main() > On Jun 16, 2015, at 3:49 PM, Mark Lawrence wrote: > > On 16/06/2015 17:45, Stephanie Quiles wrote: >> Hello, Having trouble figuring out why this program is not running. could someone please take a look and see where I am going wrong? Here is the error message i am getting : /Library/Frameworks/Python.framework/Versions/3.4/bin/python3.4 /Users/stephaniequiles/PycharmProjects/untitled3/pets.py >> Traceback (most recent call last): >> File "/Users/stephaniequiles/PycharmProjects/untitled3/pets.py", line 2, in >> def main(get_name=name): >> NameError: name 'name' is not defined >> >> Process finished with exit code 1 >> >> Thanks !!!! >> >> Code is below: >> >> >> # __author__ = 'stephaniequiles' >> >> # write a class named Pet should include __name, __animal_type, __age >> >> class Pet: >> # pet class should have an __init__ method that creates these attributes. >> def __init__(self, name, animal_type, age): >> self.__name = 'name' >> self.__animal_type = 'animal_type' >> self.__age = 'age' >> >> def set_name(self, name): >> self.__name = 'name' > > Further to Alan's answer the above methods are wrong. You're setting all the instance variables to strings instead of the actual variable names. Get rid of the single quotes. > > -- > My fellow Pythonistas, ask not what our language can do for you, ask > what you can do for our language. > > Mark Lawrence > > _______________________________________________ > 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 Jun 17 09:40:40 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 17 Jun 2015 08:40:40 +0100 Subject: [Tutor] create class Pet In-Reply-To: <2A8FF6BB-B9A6-40D9-B5B7-2F3EED0B32A9@albright.edu> References: <2A8FF6BB-B9A6-40D9-B5B7-2F3EED0B32A9@albright.edu> Message-ID: On 16/06/15 21:15, Stephanie Quiles wrote: >> sorry this is the correct error. > File "/Users/stephaniequiles/PycharmProjects/untitled3/pets.py", line 7, in main > pet.get_name(name, animal_type, age) > AttributeError: 'module' object has no attribute 'get_name' There are several errors in this line, all of which suggest you don't really understand what you are doing with functions, # classes and objects. You need to re-read your tutorial material more closely. 1) Starting with the reported error. You called pet.get_name(...) pet is the name of your file so Python sees that as a module. But get_name is a method of your Pet class. The class name is captalized and case matters in Python. 'Pet' is not the same as 'pet' That's why it says there is no such module attribute as get_name. 2) The method call has 3 arguments: name, type and age. But your method definition has no attributes (apart from the obligatory self). When you call a function (or method) you must only include the arguments that the function definition expects. So your call to get_name() would have failed even if you had not misspelled pet. 3) get_name() returns a string value - the __name of the pet. You call get_name() but do not use or store the result so it is thrown away. I suspect you meant to print the result so you should have written something like: print ( my_pet.getname() ) 4) get_name() is a method of the class Pet. That means you should call it as an attribute of an object which is an instance of Pet. That is, you must create an instance of Pet before you try to use any of its methods. You did not create any instances. Interestingly, your __init__() method does take the 3 parameters that you tried to pass to get_name(). This means that you could have replaced the get_name() call with my_pet = Pet(name, animal_type, age) Now that we have dealt with that line lets move on to the rest of your main function... You have several lines like: print("Pet Name: ", pet.get_name) The problem here is that you are passing the method name into the print function. You are not *calling* the method. Also you are using the module name (pet) to access get_name, but it needs to be an instance of Pet - see above. To do all that you must use abn instance and put parentheses after the method name, so it should look like: print("Pet Name: ", my_pet.get_name() ) The final set of errors have already been highlighted by Mark. Namely where you set attribute values in the class methods you are creating strings instead of using the variables. ie you are writing def set_name(self, name): self.__name = "name" where it should be def set_name(self, name): self.__name = name with no quote signs. If you make all those changes I think it should work. However, given the number and nature of the errors, I cannot help but think you need to go back and re-read your tutorial material. Details are very important in programming and you seem to still be confused about naming, function definitions and calling and the relationship between classes and objects/instances. > > Process finished with exit code 1 > > class Pet: > # pet class should have an __init__ method that creates these attributes. > def __init__(self, name, animal_type, age): > self.__name = "name" > self.__animal_type = "animal_type" > self.__age = "age" > > def set_name(self, name): > self.__name = "name" > > def set_type(self, animal_type): > self.__animal_type = animal_type > > def set_age(self, age): > self.__age = age > > def get_name(self): > return self.__name > > def get_animal_type(self): > return self.__animal_type > > def get_age(self): > return self.__age > > # create methods, set_name , set_animal_type, set_age, get_name, get_animal_type > # get_age > > # write a program that creates an object of the class and prompts the use to enter > # name, type, age of their pet. > > # data should be stored as objects attributes. > # use objects accessor methods to retrieve the pet's name, type and age > # display data on screen > > # __author__ = 'stephaniequiles' > import pet > def main(): > name = input("what is the name of the pet?: ") > animal_type = input("Please enter a type of pet: ") > age = input("Enter age of pet: ") > pet.get_name(name, animal_type, age) > print("This will be saved to file.") > print("Here is a the data you entered: ") > print("Pet Name: ", pet.get_name) > print("Animal Type:", pet.get_animal_type) > print("Age: ", pet.get_age) > > > main() -- 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 oliver at ollymd.co.uk Wed Jun 17 03:05:49 2015 From: oliver at ollymd.co.uk (Oliver Mercer-Deadman) Date: Wed, 17 Jun 2015 02:05:49 +0100 Subject: [Tutor] Variables in email addresses In-Reply-To: References: Message-ID: Hi I am a complete newbie but am hoping to learn some python for a particular project. Before I hurl myself in I would like to know if a key element is going to be possible. I will need to be able to use a variable as the username in an email address. E.G. username = Input("Enter Something: ") Then later when sending email with SMTP to_addr = 'username at mycompany.com' I realise that it is probably not correct, I am only in the foothills, but in principal can it be done? Thanks, Ozzy From turtle at 64.hu Wed Jun 17 06:18:19 2015 From: turtle at 64.hu (=?UTF-8?B?VsOhbGFzIFDDqXRlcg==?=) Date: Wed, 17 Jun 2015 06:18:19 +0200 Subject: [Tutor] Help understanding list comprehensions In-Reply-To: References: Message-ID: Either the subject is misleading or you misunderstand something. Im am sorry to tell you the great truth, but there was no list comprehension in your code at all, just a list. Comprehension is what Alan wrote for you, that is the next step in studying Python, when you already understand lists and loops well. From anubhav1691 at gmail.com Wed Jun 17 10:58:54 2015 From: anubhav1691 at gmail.com (Anubhav Yadav) Date: Wed, 17 Jun 2015 14:28:54 +0530 Subject: [Tutor] Help understanding list comprehensions In-Reply-To: References: Message-ID: Either the subject is misleading or you misunderstand something. Im am sorry to tell you the great truth, but there was no list comprehension in your code at all, just a list. Comprehension is what Alan wrote for you, that is the next step in studying Python, when you already understand lists and loops well. I understand that my title was a little misleading, and I apologise for the same. Here is code that worked: marks = [] for i in range(int(input())): name = raw_input() score = float(raw_input()) marks.append([name, score]) marks = sorted(marks, key=lambda score:score[1]) lowest = marks[0][1] marks = [ x for x in marks if x[1] != lowest] second_lowest = marks[0][1] lowest = sorted([x for x in marks if x[1]==second_lowest]) for row in lowest: print row[0] And it worked because I was using list comprehensions for removing the element from the list. It didn't worked in the for loop before. I wanted to ask why it didn't worked in for loop but worked in list comprehension. From v.kajen at yahoo.com Wed Jun 17 09:52:46 2015 From: v.kajen at yahoo.com (Velummaylum Kajenthiran) Date: Wed, 17 Jun 2015 07:52:46 +0000 (UTC) Subject: [Tutor] Dynamic linking vs Static linking of libraries in python Message-ID: <339104092.306992.1434527566683.JavaMail.yahoo@mail.yahoo.com> Dear Sir/MadamI know the difference between static and dynamic linking in C or C++. But what does it mean this in Python? Since it's just an interpreter, and only having one style of import mechanism of modules, how this make sense?If I freeze my python application with PyInstaller, Is it a kind of dynamic linking? Because, users can replace that library by themselves in order to run my application with different versions of libraries.What would be the meaning for this, if I freeze this as one file exe? In this case, users can not replace the dlls in order to run my app with different versions of PySide libraries.Actually my problems is, I'm using PySide library (with LGPL v2.1) to develop python GUI application. Library says, I should dynamically link to library to obey their legal terms (same as Qt). In this case, how do I link PySide dynamically? From lac at openend.se Wed Jun 17 13:04:39 2015 From: lac at openend.se (Laura Creighton) Date: Wed, 17 Jun 2015 13:04:39 +0200 Subject: [Tutor] Variables in email addresses In-Reply-To: Message from Oliver Mercer-Deadman of "Wed, 17 Jun 2015 02:05:49 +0100." References: Message-ID: <201506171104.t5HB4dxm017590@fido.openend.se> In a message of Wed, 17 Jun 2015 02:05:49 +0100, Oliver Mercer-Deadman writes: >Hi I am a complete newbie but am hoping to learn some python for a >particular project. Before I hurl myself in I would like to know if a key >element is going to be possible. > >I will need to be able to use a variable as the username in an email >address. E.G. > >username = Input("Enter Something: ") > >Then later when sending email with SMTP >to_addr = 'username at mycompany.com' > >I realise that it is probably not correct, I am only in the foothills, but >in principal can it be done? > >Thanks, >Ozzy You can do this. Works great. Note, you will want to be using the smtplib that is part of the Python standard library and not write all of the code for talking to SMTP yourself. Somebody else has already done this for you. Interesting tutorial here: http://pymotw.com/2/smtplib/ But be warned, this uses Python 2 syntax, not Python 3. Laura From lac at openend.se Wed Jun 17 13:28:38 2015 From: lac at openend.se (Laura Creighton) Date: Wed, 17 Jun 2015 13:28:38 +0200 Subject: [Tutor] Help understanding list comprehensions In-Reply-To: Message from Anubhav Yadav of "Wed, 17 Jun 2015 14:28:54 +0530." References: Message-ID: <201506171128.t5HBScJt018184@fido.openend.se> In a message of Wed, 17 Jun 2015 14:28:54 +0530, Anubhav Yadav writes: >Either the subject is misleading or you misunderstand something. Im am >sorry to tell you the great truth, but there was no list comprehension in >your code at all, just a list. Comprehension is what Alan wrote for you, >that is the next step in studying Python, when you already understand lists >and loops well. > > >I understand that my title was a little misleading, and I apologise for the >same. Here is code that worked: > >marks = [] >for i in range(int(input())): > name = raw_input() > score = float(raw_input()) > marks.append([name, score]) >marks = sorted(marks, key=lambda score:score[1]) >lowest = marks[0][1] >marks = [ x for x in marks if x[1] != lowest] >second_lowest = marks[0][1] >lowest = sorted([x for x in marks if x[1]==second_lowest]) >for row in lowest: > print row[0] >And it worked because I was using list comprehensions for removing the >element from the list. It didn't worked in the for loop before. I wanted to >ask why it didn't worked in for loop but worked in list comprehension. You have this problem. Type "help", "copyright", "credits" or "license" for more information. >>> mylist = [1,2,3] >>> for i in mylist: ... print i ... mylist.remove(i) ... 1 3 >>> mylist [2] -------- you didn't want to skip over 2. -------- So do this instead. >>> from copy import copy >>> mylist=[1,2,3] >>> mylist_copy=copy(mylist) >>> for i in mylist_copy: ... print i ... mylist.remove(i) ... 1 2 3 >>> mylist [] >>> mylist_copy [1, 2, 3] ------------ Much better. :) This goes to show that you shouldn't delete items out of a list you are interating over, unless you want the weird output you got above. But even if you did -- it will confuse the heck out of the next person to read your code, which may be you in six months time, so even then it might be better to rewrite the thing. Make a copy of the list instead. Now, python gives you lots of ways to make copies. One way is to use the copy command, as I did. This has the advantage that everybody knows exactly what it is that you did. It has the disadvantage that people have to type 'from copy import copy' and some people -- I am not one of them -- find it too much typing. So they write it as: >>> mylist=[1,2,3] >>> mylist_copy=mylist[:] >>> mylist [1, 2, 3] >>> mylist_copy [1, 2, 3] and since this way of doing things is so very well known, you mostly don't confuse people by copying that way. And, as you may have found out in code not here, you can use a list comprehension to construct a whole new list, so again you wouldn't have the problem of deleting items out of a list you are iterating over, because it is a different list. But you are mistaken when you write: >And it worked because I was using list comprehensions for removing the >element from the list. It didn't worked in the for loop before. I wanted to >ask why it didn't worked in for loop but worked in list comprehension. (at least with respect to that code). In the code you posted you didn't remove anything from the list at all. Laura From lac at openend.se Wed Jun 17 14:18:59 2015 From: lac at openend.se (Laura Creighton) Date: Wed, 17 Jun 2015 14:18:59 +0200 Subject: [Tutor] Dynamic linking vs Static linking of libraries in python In-Reply-To: Message from Velummaylum Kajenthiran via Tutor of "Wed, 17 Jun 2015 07:52:46 -0000." <339104092.306992.1434527566683.JavaMail.yahoo@mail.yahoo.com> References: <339104092.306992.1434527566683.JavaMail.yahoo@mail.yahoo.com> Message-ID: <201506171218.t5HCIxCp019450@fido.openend.se> In a message of Wed, 17 Jun 2015 07:52:46 -0000, Velummaylum Kajenthiran via Tu tor writes: Dear Sir/MadamI know the difference between static and dynamic linking in C or C++. But what does it mean this in Python? Since it's just an interpreter, and only having one style of import mechanism of modules, how this make sense?If I freeze my python application with PyInstaller, Is it a kind of dynamic linking? Because, users can replace that library by themselves in order to run my application with different versions of libraries.What would be the meaning for this, if I freeze this as one file exe? In this case, users can not replace the dlls in order to run my app with different versions of PySide libraries.Actually my problems is, I'm using PySide library (with LGPL v2.1) to develop python GUI application. Library says, I should dynamically link to library to obey their legal terms (same as Qt). In this case, how do I link PySide dynamically? >_______________________________________________ >Tutor maillist - Tutor at python.org >To unsubscribe or change subscription options: >https://mail.python.org/mailman/listinfo/tutor You need to ask this question here: http://lists.qt-project.org/mailman/listinfo/pyside because all that matters is what the pyside people think. And, should you ever get into legal trouble, and have to go to court, what you need is evidence that this didn't violate the Pyside license agreement according to the Pyside people. What we on the tutor mailing list think will not count. Our company uses PyQt for lots of our commercial apps -- all the ones that aren't web based. About 12 years ago we asked that very question in paper mail to Trolltech (who owned QT at the time). We got the answer 'If you use PyInstaller you will be fine with us. Don't use py2exe.' Somewhere in a fireproof safe at work with 'documents we could not stand to lose even if the building burned down' we have that piece of paper. By all means do not get into discussing whether PyInstaller does or does not make dynamic or static links. This is an engineering question, and most engineers would say 'static', but that is irrelevant to your problem. Your problem is not an engineering one, but a legal one. Legal arguments work better when they have something to do with the truth, but _That is Not a Requirement_. Should you ever be unfortunate enough to be sued, and enemy lawyers come by demanding stuff, the argument that 'I have the truth on my side' will be greeted with gales of laughter. 'Of course you do', they will agree. 'But all that matters is that we can win this one in court. And here is the list of 5 of your competitors who have had to pay up when they lost the lawsuit even though they had the truth on their side too.' So, go get permission from the place that it really matters. What engineers think isn't worth the price of a cup of coffee. I suggest you get it, on paper, in writing by requesting such a thing from Digia (who are the latest in the long list of people who own QT) http://www.digia.com/ unless the Pyside mailing list steers you to some place else. Because the thing that stops lawyers, or at least slows them down, is not truth but documents signed by other lawyers saying that what you want to do is ok. Laura From joel.goldstick at gmail.com Wed Jun 17 14:42:53 2015 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 17 Jun 2015 08:42:53 -0400 Subject: [Tutor] Variables in email addresses In-Reply-To: <201506171104.t5HB4dxm017590@fido.openend.se> References: <201506171104.t5HB4dxm017590@fido.openend.se> Message-ID: On Wed, Jun 17, 2015 at 7:04 AM, Laura Creighton wrote: > In a message of Wed, 17 Jun 2015 02:05:49 +0100, Oliver Mercer-Deadman writes: >>Hi I am a complete newbie but am hoping to learn some python for a >>particular project. Before I hurl myself in I would like to know if a key >>element is going to be possible. >> >>I will need to be able to use a variable as the username in an email >>address. E.G. >> >>username = Input("Enter Something: ") >> >>Then later when sending email with SMTP >>to_addr = 'username at mycompany.com' >> >>I realise that it is probably not correct, I am only in the foothills, but >>in principal can it be done? If the user input value is just the name, then you need to concatinate with the part starting with the @. Like this: to_addr = username + '@mycompany.com' >> >>Thanks, >>Ozzy > > You can do this. Works great. Note, you will want to be using the > smtplib that is part of the Python standard library and not write > all of the code for talking to SMTP yourself. Somebody else has > already done this for you. > > Interesting tutorial here: > http://pymotw.com/2/smtplib/ > But be warned, this uses Python 2 syntax, not Python 3. > > Laura > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor -- Joel Goldstick http://joelgoldstick.com From steve at pearwood.info Wed Jun 17 15:55:18 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 17 Jun 2015 23:55:18 +1000 Subject: [Tutor] Dynamic linking vs Static linking of libraries in python In-Reply-To: <339104092.306992.1434527566683.JavaMail.yahoo@mail.yahoo.com> References: <339104092.306992.1434527566683.JavaMail.yahoo@mail.yahoo.com> Message-ID: <20150617135517.GE20701@ando.pearwood.info> On Wed, Jun 17, 2015 at 07:52:46AM +0000, Velummaylum Kajenthiran via Tutor wrote: > Dear Sir/MadamI know the difference between static and dynamic linking > in C or C++. But what does it mean this in Python? Nothing. It isn't relevant to pure Python code. All Python code is dynamically linked in the C sense. The *Python interpreter* itself may be a C application, and like any other C application it might use static or dynamic linking to its own libraries. > Since it's just an > interpreter, and only having one style of import mechanism of modules, > how this make sense? It doesn't. Python module imports are always dynamic. > If I freeze my python application with > PyInstaller, Is it a kind of dynamic linking? Because, users can > replace that library by themselves in order to run my application with > different versions of libraries.What would be the meaning for this, if > I freeze this as one file exe? PyInstaller makes a copy of the Python interpreter and all the modules you use, places those copies into a single directory, and wraps that directory into a stand-alone executable file. http://pythonhosted.org/PyInstaller/#id11 As far as your Python app is concerned, nothing has changed. It just runs under a Python interpreter, and sees the same modules as before. The only difference is that it is a copy of the interpreter, and a copy of those modules. > In this case, users can not replace the > dlls in order to run my app with different versions of PySide > libraries.Actually my problems is, I'm using PySide library (with LGPL > v2.1) to develop python GUI application. Library says, I should > dynamically link to library to obey their legal terms (same as Qt). In > this case, how do I link PySide dynamically? You should probably ask on a PySide forum, but as far as I can tell you don't have to do anything special with your Python code. If you are using C or C++ code and linking to the PySide libraries, then you have to link dynamically in the C/C++ compiler. But I'm not an expert. You really ought to ask on a PySide forum. -- Steve From alan.gauld at btinternet.com Wed Jun 17 17:22:13 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 17 Jun 2015 16:22:13 +0100 Subject: [Tutor] Help understanding list comprehensions In-Reply-To: References: Message-ID: On 17/06/15 09:58, Anubhav Yadav wrote: > I understand that my title was a little misleading, and I apologise for the > same. Here is code that worked: > > marks = [] > for i in range(int(input())): Don't use input(). Use raw_input() instead. You almost never want input() in python 2. > name = raw_input() > score = float(raw_input()) > marks.append([name, score]) > marks = sorted(marks, key=lambda score:score[1]) > lowest = marks[0][1] > marks = [ x for x in marks if x[1] != lowest] This creates a brand new list. It eventually overwrites the original marks list with the new list. But it never modifies the original marks, it reassigns the new list to the old variable. > second_lowest = marks[0][1] > lowest = sorted([x for x in marks if x[1]==second_lowest]) > for row in lowest: > print row[0] > > And it worked because I was using list comprehensions for removing the > element from the list. It didn't worked in the for loop before. I wanted to > ask why it didn't worked in for loop but worked in list comprehension. Because the comprehension creates a new list from the old. You were modifying the original list as you traversed it, thus breaking your own for loop. -- 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.Aldrich at EMEA.NEC.COM Wed Jun 17 14:49:38 2015 From: David.Aldrich at EMEA.NEC.COM (David Aldrich) Date: Wed, 17 Jun 2015 12:49:38 +0000 Subject: [Tutor] How to return a list in an exception object? Message-ID: <41302A7145AC054FA7A96CFD03835A0A0B98337D@EX10MBX02.EU.NEC.COM> Hi I have a function that compares a set of files with a reference set of files. All files are compared and then, if any differences were found, an exception is raised: class Error(Exception): pass def check_results(file_list): if isDifferent: raise Error('One or more result files differ from the reference result files') I would like to pass back to the caller a list of the files that failed. How would I include that list in the exception object? Best regards David From __peter__ at web.de Wed Jun 17 18:26:46 2015 From: __peter__ at web.de (Peter Otten) Date: Wed, 17 Jun 2015 18:26:46 +0200 Subject: [Tutor] How to return a list in an exception object? References: <41302A7145AC054FA7A96CFD03835A0A0B98337D@EX10MBX02.EU.NEC.COM> Message-ID: David Aldrich wrote: > Hi > > I have a function that compares a set of files with a reference set of > files. All files are compared and then, if any differences were found, an > exception is raised: > > class Error(Exception): pass > > def check_results(file_list): > > > > if isDifferent: > raise Error('One or more result files differ from the reference > result files') > > I would like to pass back to the caller a list of the files that failed. > How would I include that list in the exception object? While you can pass them as just another argument >>> class UnexpectedFileContents(Exception): ... pass ... >>> try: ... raise UnexpectedFileContents("Some files differ from the reference", ["foo.txt", "bar.py", "baz.rst"]) ... except UnexpectedFileContents as err: ... print(err) ... print("The problematic files are") ... print("\n".join(err.args[1])) ... ('Some files differ from the reference', ['foo.txt', 'bar.py', 'baz.rst']) The problematic files are foo.txt bar.py baz.rst it's probably a good idea to put in a bit more work: >>> class UnexpectedFileContents(Exception): ... def __init__(self, message, files): ... super().__init__(message) ... self.files = files ... >>> try: ... raise UnexpectedFileContents("Some files differ from the reference", ["foo.txt", "bar.py", "baz.rst"]) ... except UnexpectedFileContents as err: ... print(err) ... print("The problematic files are") ... print("\n".join(err.files)) ... Some files differ from the reference The problematic files are foo.txt bar.py baz.rst If you like you can add defaults and adapt the __str__() method: >>> class UnexpectedFileContents(Exception): ... def __init__(self, message="Some files differ from the reference", files=None): ... self.message = message ... self.files = files ... def __str__(self): ... s = self.message ... if self.files is not None: ... s = s + ": " + ", ".join(self.files) ... return s ... >>> try: raise UnexpectedFileContents(files=["foo.txt", "bar.py", "baz.rst"]) ... except UnexpectedFileContents as err: print(err) ... Some files differ from the reference: foo.txt, bar.py, baz.rst From martin at linux-ip.net Wed Jun 17 18:22:21 2015 From: martin at linux-ip.net (Martin A. Brown) Date: Wed, 17 Jun 2015 09:22:21 -0700 Subject: [Tutor] How to return a list in an exception object? In-Reply-To: <41302A7145AC054FA7A96CFD03835A0A0B98337D@EX10MBX02.EU.NEC.COM> References: <41302A7145AC054FA7A96CFD03835A0A0B98337D@EX10MBX02.EU.NEC.COM> Message-ID: Greetings David, > I have a function that compares a set of files with a reference > set of files. All files are compared and then, if any differences > were found, an exception is raised: If you had been trying to compare files, I would have suggested examining difflib, but it sounds like you are more interested in set math on the elements of your file sets. See a suggestion below for how to make sets work for you. > class Error(Exception): pass > > def check_results(file_list): > > > > if isDifferent: > raise Error('One or more result files differ from the reference result files') > > I would like to pass back to the caller a list of the files that > failed. How would I include that list in the exception object? While often, there is only text in the arguments supplied to Exception, you can stuff whatever you like in the args. The first argument to Exception [0] should always be a human-readable string (text). Here are two examples, the first supplying a list in the arguments: raise Exception("A hummingbird stole my boiled turnips.", range(4)) # -- import os raise Exception("Where is my sock-eating goat?", dict(os.environ)) Now, back to the question of comparing file sets. When you have two sets that you want to compare, there are many different ways to look at the differences. I like computing once the full set of differences between sets and then working with the results. When comparing two sets for what is missing, or what is extra, you end up with three different output sets for any given set called A (your reference set, let's say) and set called B (the subject of the test). same: There's a set of elements present in both A and B. only_a: There's a set of elements present only in A. only_b: There's a set of elements present only in B. In this case, you are particularly interested in the 'only_a' set. These are the files (in your problem) which are in your reference set, but not the other set/list. But, don't forget that there are files in B that may not be in A! Depending on what you are doing with this file set, you may be undertaking extra work, or risking loss. [I imagine a file deleter or file archiver which handles extra files.] This may be more than you needed or wanted for solving your problem. I couldn't help having contributed my thoughts, though, because....I have made this very mistake, myself. Anyway, here's a function to show you what I mean. def differing(a, b): a = set(a) b = set(b) same = a.intersection(b) a_only = a.difference(b) b_only = b.difference(a) return same, a_only, b_only # -- and now to use it import random a = random.sample(range(17), 10) b = random.sample(range(17), 10) same, a_only, b_only = differing(a, b) If you wanted to make sure that there were no extra files, you could: assert 0 == len(b_only) Anyway, there are many ways to use the above, if you like it. I wish you exceptional luck, -Martin [0] https://docs.python.org/2/library/difflib.html [1] https://docs.python.org/3/library/exceptions.html#Exception -- Martin A. Brown http://linux-ip.net/ From alan.gauld at btinternet.com Wed Jun 17 20:35:18 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 17 Jun 2015 19:35:18 +0100 Subject: [Tutor] How to return a list in an exception object? In-Reply-To: <41302A7145AC054FA7A96CFD03835A0A0B98337D@EX10MBX02.EU.NEC.COM> References: <41302A7145AC054FA7A96CFD03835A0A0B98337D@EX10MBX02.EU.NEC.COM> Message-ID: On 17/06/15 13:49, David Aldrich wrote: > I have a function that compares a set of files with a reference set of files. > All files are compared and then, if any differences were found, an exception > is raised: That's a pretty horrible way to deal with things. Exceptions should be used for exceptional circumstances not as a way of passing data around for a perfectly predictable circumstance. Why not just pass back the list and if its empty you know it succeeded. And since an empty list if False in a boolean sense you can even use it like: if check_results(): ... when you don't care about the result content. > class Error(Exception): pass > > def check_results(file_list): > > > > if isDifferent: > raise Error('One or more result files differ from the reference result files') Is there any reason why you want to use an exception? Is there an API that require it or something? Its certainly possible to do it, but its a pretty horrible idiom. Functions should return any data as a return value not tucked inside an exception. Valid exceptions would be things like incompatible file types (being asked to compare data values to jpegs or mp3s for example) or, just possibly, mismatching file sets (different numbers say). -- 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 Thu Jun 18 00:00:31 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 18 Jun 2015 08:00:31 +1000 Subject: [Tutor] How to return a list in an exception object? In-Reply-To: <41302A7145AC054FA7A96CFD03835A0A0B98337D@EX10MBX02.EU.NEC.COM> References: <41302A7145AC054FA7A96CFD03835A0A0B98337D@EX10MBX02.EU.NEC.COM> Message-ID: <20150617220031.GF20701@ando.pearwood.info> On Wed, Jun 17, 2015 at 12:49:38PM +0000, David Aldrich wrote: > Hi > > I have a function that compares a set of files with a reference set of > files. All files are compared and then, if any differences were > found, an exception is raised: [...] > I would like to pass back to the caller a list of the files that > failed. How would I include that list in the exception object? Others have already answered your question, but I'm completely with Alan on this one: don't do this. Have your function return a list of differences. If there are no differences, return an empty list. The caller then decides what to do: diffs = checkfiles() if diffs: for fname in diffs: print("file name %s is different" % fname) repair_file(fname) else: raise NoDifferencesError( "expected some differences, but didn't find any" ) -- Steve From stephanie.quiles001 at albright.edu Wed Jun 17 21:43:55 2015 From: stephanie.quiles001 at albright.edu (Stephanie Quiles) Date: Wed, 17 Jun 2015 15:43:55 -0400 Subject: [Tutor] create class Pet In-Reply-To: References: <2A8FF6BB-B9A6-40D9-B5B7-2F3EED0B32A9@albright.edu> Message-ID: You are right I don't understand functions very well still. This prompts the next question is there a book or online resource that you suggest I look at? Right now I am using a text book provides by the instructor called Starting Out With Python 3rd ed. Anything you can suggest I reference would be appreciated. I will review the code when I get home. Thanks Stephanie Quiles Sent from my iPhone > On Jun 17, 2015, at 3:40 AM, Alan Gauld wrote: > > On 16/06/15 21:15, Stephanie Quiles wrote: >>> sorry this is the correct error. > > >> File "/Users/stephaniequiles/PycharmProjects/untitled3/pets.py", line 7, in main >> pet.get_name(name, animal_type, age) >> AttributeError: 'module' object has no attribute 'get_name' > > There are several errors in this line, all of which suggest > you don't really understand what you are doing with functions, # > classes and objects. You need to re-read your tutorial material > more closely. > > 1) Starting with the reported error. > You called > > pet.get_name(...) > > pet is the name of your file so Python sees that as a module. > But get_name is a method of your Pet class. The class name is > captalized and case matters in Python. 'Pet' is not the > same as 'pet' That's why it says there is no such module > attribute as get_name. > > 2) The method call has 3 arguments: name, type and age. > But your method definition has no attributes (apart > from the obligatory self). When you call a function > (or method) you must only include the arguments that > the function definition expects. So your call to > get_name() would have failed even if you had not > misspelled pet. > > 3) get_name() returns a string value - the __name of the pet. > You call get_name() but do not use or store the result so > it is thrown away. I suspect you meant to print the result > so you should have written something like: > print ( my_pet.getname() ) > > 4) get_name() is a method of the class Pet. That means > you should call it as an attribute of an object which > is an instance of Pet. That is, you must create an > instance of Pet before you try to use any of its methods. > You did not create any instances. Interestingly, your > __init__() method does take the 3 parameters that > you tried to pass to get_name(). This means that > you could have replaced the get_name() call with > > my_pet = Pet(name, animal_type, age) > > Now that we have dealt with that line lets move on > to the rest of your main function... > > You have several lines like: > > print("Pet Name: ", pet.get_name) > > The problem here is that you are passing the method name > into the print function. You are not *calling* the method. > Also you are using the module name (pet) to access get_name, > but it needs to be an instance of Pet - see above. > > To do all that you must use abn instance and put parentheses > after the method name, so it should look like: > > print("Pet Name: ", my_pet.get_name() ) > > The final set of errors have already been highlighted by Mark. > Namely where you set attribute values in the class methods > you are creating strings instead of using the variables. > ie you are writing > > def set_name(self, name): > self.__name = "name" > > where it should be > > def set_name(self, name): > self.__name = name > > with no quote signs. > > If you make all those changes I think it should work. > However, given the number and nature of the errors, I cannot > help but think you need to go back and re-read your > tutorial material. Details are very important in programming > and you seem to still be confused about naming, function definitions and calling and the relationship between classes and objects/instances. > >> >> Process finished with exit code 1 >> >> class Pet: >> # pet class should have an __init__ method that creates these attributes. >> def __init__(self, name, animal_type, age): >> self.__name = "name" >> self.__animal_type = "animal_type" >> self.__age = "age" >> >> def set_name(self, name): >> self.__name = "name" >> >> def set_type(self, animal_type): >> self.__animal_type = animal_type >> >> def set_age(self, age): >> self.__age = age >> >> def get_name(self): >> return self.__name >> >> def get_animal_type(self): >> return self.__animal_type >> >> def get_age(self): >> return self.__age >> >> # create methods, set_name , set_animal_type, set_age, get_name, get_animal_type >> # get_age >> >> # write a program that creates an object of the class and prompts the use to enter >> # name, type, age of their pet. >> >> # data should be stored as objects attributes. >> # use objects accessor methods to retrieve the pet's name, type and age >> # display data on screen >> >> # __author__ = 'stephaniequiles' >> import pet >> def main(): >> name = input("what is the name of the pet?: ") >> animal_type = input("Please enter a type of pet: ") >> age = input("Enter age of pet: ") >> pet.get_name(name, animal_type, age) >> print("This will be saved to file.") >> print("Here is a the data you entered: ") >> print("Pet Name: ", pet.get_name) >> print("Animal Type:", pet.get_animal_type) >> print("Age: ", pet.get_age) >> >> >> main() > > -- > 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 alan.gauld at btinternet.com Thu Jun 18 01:16:23 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 18 Jun 2015 00:16:23 +0100 Subject: [Tutor] create class Pet In-Reply-To: References: <2A8FF6BB-B9A6-40D9-B5B7-2F3EED0B32A9@albright.edu> Message-ID: On 17/06/15 20:43, Stephanie Quiles wrote: > You are right I don't understand functions very well still. This prompts the next question is there a book or online resource that you suggest I look at? Right now I am using a text book provides by the instructor called Starting Out With Python 3rd ed. > Anything you can suggest I reference would be appreciated. I will review the code when I get home. I'm obviously biased, but you could try mine(see .sig) There are topics on "functions and modules" and "OOP" -- 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 anubhav1691 at gmail.com Thu Jun 18 06:40:05 2015 From: anubhav1691 at gmail.com (Anubhav Yadav) Date: Thu, 18 Jun 2015 04:40:05 +0000 Subject: [Tutor] Help understanding list comprehensions In-Reply-To: References: Message-ID: So I need to create a copy of the list before trying to iterate through the list. Thanks a lot everyone for their answers. Cheers. From alan.gauld at btinternet.com Thu Jun 18 10:20:44 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 18 Jun 2015 09:20:44 +0100 Subject: [Tutor] Help understanding list comprehensions In-Reply-To: References: Message-ID: On 18/06/15 05:40, Anubhav Yadav wrote: > So I need to create a copy of the list before trying to iterate through the > list. Only if you are going to change it. The problem you had was that you were removing items from the thing you were iterating over. As a result the other items effectively moved up one place to fill the gap resulting in you stepping over some items without processing them. Similarly problems can ensue if you insert new items into a list while iterating over it. You may wind up processing some items twice while not processing the new items you added. It's just a bad idea to modify the structure of the thing you are iterating over. So, if you intend modifying the list structure make a copy. Otherwise you can iterate over the original list (or dictionary, or whatever) without problems. -- 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.Aldrich at EMEA.NEC.COM Thu Jun 18 12:31:55 2015 From: David.Aldrich at EMEA.NEC.COM (David Aldrich) Date: Thu, 18 Jun 2015 10:31:55 +0000 Subject: [Tutor] How to return a list in an exception object? In-Reply-To: <20150617220031.GF20701@ando.pearwood.info> References: <41302A7145AC054FA7A96CFD03835A0A0B98337D@EX10MBX02.EU.NEC.COM> <20150617220031.GF20701@ando.pearwood.info> Message-ID: <41302A7145AC054FA7A96CFD03835A0A0B983ADB@EX10MBX02.EU.NEC.COM> Thanks very much for all the answers to my question. I have taken the advice to return a list of differing files, rather than raise an exception. I do have a follow-up question: I have a list of paths that contain files I want to check. paths = [pathA, pathB] then I check the files in each path and get a list of files that differ in some way: for path in paths differing_files_list = compare_files(path) I would like to store the differing_files_list with the associated path so that, after doing all comparisons, I can print the all differing files, sorted by path: for path in paths for file in differing_files_list print(path + file) How would I do that association? I guess I need a two-dimensional list but I don't know how to build it. Best regards David From alan.gauld at btinternet.com Thu Jun 18 13:46:50 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 18 Jun 2015 12:46:50 +0100 Subject: [Tutor] How to return a list in an exception object? In-Reply-To: <41302A7145AC054FA7A96CFD03835A0A0B983ADB@EX10MBX02.EU.NEC.COM> References: <41302A7145AC054FA7A96CFD03835A0A0B98337D@EX10MBX02.EU.NEC.COM> <20150617220031.GF20701@ando.pearwood.info> <41302A7145AC054FA7A96CFD03835A0A0B983ADB@EX10MBX02.EU.NEC.COM> Message-ID: On 18/06/15 11:31, David Aldrich wrote: > I have a list of paths that contain files I want to check. > > paths = [pathA, pathB] > > then I check the files in each path and get a list of files that differ in some way: > > for path in paths > differing_files_list = compare_files(path) > > I would like to store the differing_files_list with the associated path So do just that. There is a data structure called an associative array or, in Python terms a dictionary. If you make the path the key you can associate the list of bad files with it. paths = {pathA:[], pathB:[].....} # initialize with empty lists for path in paths: paths[path] = compare_files(path) > so that, after doing all comparisons, I can print the all differing files, sorted by path: > > for path in paths > for file in differing_files_list > print(path + file) becomes: for path in paths: for file in paths[path]: print(path+file) # you might want to use os.path.join() here 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 adeadmarshal at gmail.com Thu Jun 18 16:13:56 2015 From: adeadmarshal at gmail.com (Ali Moradi) Date: Thu, 18 Jun 2015 18:43:56 +0430 Subject: [Tutor] clickable listbox with Tkinter (python2) Message-ID: Hi, i studied your book that u said before. now i came up with this code, which i can't now show my words in the list box! ? http://pastebin.com/GpWc8Pnw now, i've got a better idea! , i can use two lists like this code ( http://pastebin.com/sJj39UjA), just the items should be loaded from my database. like when i click water for example in the first list, the word akvo in the second list appears. now what is the method for filling the listbox from sqlite ? please modify the code for me becuz i'm beginner. From alan.gauld at btinternet.com Thu Jun 18 19:16:56 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 18 Jun 2015 18:16:56 +0100 Subject: [Tutor] clickable listbox with Tkinter (python2) In-Reply-To: References: Message-ID: On 18/06/15 15:13, Ali Moradi wrote: > now i came up with this code, which i can't now show my words in the list > box! ? > root = Tk() > l = Listbox(root, height=10) > s = Scrollbar(root, orient=VERTICAL) > l.configure(yscrollcommand=s.set) > l.pack() > root.mainloop() I'd leave out the scrollbar for the moment. Keep it as simple as possible then add features once the simple bits are working. The more features you add the more there is to go wrong and you're never quite sure which bit is faulty. If you only add new features after the rest work then you know the new bit is what is broken. > #-------------------------------- > db = sqlite.connect('/home/deadmarshal/Desktop/Tkinter') That's probably a bad name for your database file. It should probably be called something like word_dictionary.db... Its also usually best to keep databases in a folder rather than on your desktop but that's just to avoid mess on your screen! > cur = db.cursor() > cur.execute('Select * from vortoj') > for row in cur: > print(row) This section has nothing to do with the GUI. But does it work? Are you seeing the rows printed on the console? You can store the rows in a variable using the cur.fetchall() function. You can then convert them into strings for display (via print or in the GUI). You should get a list of tuples so you can build a list of strings with something like: rows = cur.fetchall() display_rows = [] for row in rows: display_rows.append(str(row[0] + ' ' + str(row[1]) ) which can be shortened using a list comprehension to: display_rows = [str(row[0] + ' ' + str(row[1]) for row in rows] You can then insert these strings into your GUI as I did in my original example. > now, i've got a better idea! Get the first idea working as its easier. Then you can add the extras. -- 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 lac at openend.se Fri Jun 19 00:20:57 2015 From: lac at openend.se (Laura Creighton) Date: Fri, 19 Jun 2015 00:20:57 +0200 Subject: [Tutor] Help understanding list comprehensions In-Reply-To: Message from Anubhav Yadav of "Thu, 18 Jun 2015 04:40:05 -0000." References: Message-ID: <201506182220.t5IMKvAb010849@fido.openend.se> In a message of Thu, 18 Jun 2015 04:40:05 -0000, Anubhav Yadav writes: >So I need to create a copy of the list before trying to iterate through the >list. >Thanks a lot everyone for their answers. Er, I think you understand, but what you need to do is to make a copy of the list, and _interate through the copy_ if you want to remove things from your list. If you aren't modifying the list in the loop/function/method/whatever then you don't need a copy. I think you already got it, but "what you said" != "what you meant". :) Laura From ahlusar.ahluwalia at gmail.com Fri Jun 19 03:44:43 2015 From: ahlusar.ahluwalia at gmail.com (Saran Ahluwalia) Date: Thu, 18 Jun 2015 21:44:43 -0400 Subject: [Tutor] Attacking this problem (2 parts):JSON object to CSV file Message-ID: Good Evening, I have a conundrum regarding JSON objects and converting them to CSV: *Context* - I am converting XML files to a JSON object (please see snippet below) and then finally producing a CSV file. Here is a an example JSON object: "PAC": { "Account": [{ "PC": "0", "CMC": "0", "WC": "0", "DLA": "0", "CN": null, "FC": { "Int32": ["0", "0", "0", "0", "0"] }, "F": { "Description": null, "Code": "0" } In general, when I convert any of the files from JSON to CSV, I have been successful when using the following: import csv import json import sys def hook(obj): return obj def flatten(obj): for k, v in obj: if isinstance(v, list): yield from flatten(v) else: yield k, v if __name__ == "__main__": with open("somefileneame.json") as f: data = json.load(f, object_pairs_hook=hook) pairs = list(flatten(data)) writer = csv.writer(sys.stdout) header = writer.writerow([k for k, v in pairs]) row = writer.writerow([v for k, v in pairs]) #writer.writerows for any other iterable object However with the example JSON object (above) i receive the following error when applying this function: ValueError: too many values to unpack Here are some more samples. 1. "FC": {"Int32": ["0","0","0","0","0","0"]} 2. "PBA": {"Double": ["0","0","0","0","0","0","0","0"]} 3. "PBDD": { "DateTime": ["1/1/0001 12:00:00 AM", "1/1/0001 12:00:00 AM", "1/1/0001 12:00:00 AM", "1/1/0001 12:00:00 AM", "1/1/0001 12:00:00 AM", "1/1/0001 12:00:00 AM", "1/1/0001 12:00:00 AM", "1/1/0001 12:00:00 AM"] }, In the above example, I would like to remove the keys *Int32*, *Double *and *DateTime*. I am wondering if there is a function or methodology that would allow me to remove such nested keys and reassign the new keys to the outer key (in this case above *FC, PBA *and *PBDD*) as column headers in a CSV and concatenate all of the values within the list (as corresponding fields). Also, here is how I strategized my XML to CSV conversion (if this is of any use): import xml.etree.cElementTree as ElementTree from xml.etree.ElementTree import XMLParser import json import csv import tokenize import token try: from collections import OrderedDict import json except ImportError: from ordereddict import OrderedDict import simplejson as json import itertools import six import string from csvkit import CSVKitWriter class XmlListConfig(list): def __init__(self, aList): for element in aList: if element: # treat like dict if len(element) == 1 or element[0].tag != element[1].tag: self.append(XmlDictConfig(element)) # treat like list elif element[0].tag == element[1].tag: self.append(XmlListConfig(element)) elif element.text: text = element.text.strip() if text: self.append(text) class XmlDictConfig(dict): ''' Example usage: >>> tree = ElementTree.parse('your_file.xml') >>> root = tree.getroot() >>> xmldict = XmlDictConfig(root) Or, if you want to use an XML string: >>> root = ElementTree.XML(xml_string) >>> xmldict = XmlDictConfig(root) And then use xmldict for what it is..a dictionary. ''' def __init__(self, parent_element): if parent_element.items(): self.update(dict(parent_element.items())) for element in parent_element: if element: # treat like dict - we assume that if the first two tags # in a series are different, then they are all different. if len(element) == 1 or element[0].tag != element[1].tag: aDict = XmlDictConfig(element) # treat like list - we assume that if the first two tags # in a series are the same, then the rest are the same. else: # here, we put the list in dictionary; the key is the # tag name the list elements all share in common, and # the value is the list itself aDict = {element[0].tag: XmlListConfig(element)} # if the tag has attributes, add those to the dict if element.items(): aDict.update(dict(element.items())) self.update({element.tag: aDict}) # this assumes that if you've got an attribute in a tag, # you won't be having any text. This may or may not be a # good idea -- time will tell. It works for the way we are # currently doing XML configuration files... elif element.items(): self.update({element.tag: dict(element.items())}) # finally, if there are no child tags and no attributes, extract # the text else: self.update({element.tag: element.text}) def main(): #Lines 88-89stantiate the class Elementree #and applies the method to recursively traverse from the root node #XmlDictConfig is instantiated in line 90 with open('C:\\Users\\wynsa2\\Desktop\\Python Folder\\PCSU\\Trial2_PCSU\\2-Response.xml', 'r', encoding='utf-8') as f: xml_string = f.read() xml_string= xml_string.replace('�', '') root = ElementTree.XML(xml_string) xmldict = XmlDictConfig(root) json_str = json.dumps(xmldict, sort_keys=True, indent=4, separators=(',', ': ')) newly_formatted_data = json.loads(json_str) #encode into JSON with open('data2.json', 'w') as f: #writing JSON file json.dump(newly_formatted_data, f) I hope that I was clear in my description. Thank you all for your help. Sincerely, Saran From pughpl at me.com Fri Jun 19 03:28:14 2015 From: pughpl at me.com (Phillip Pugh) Date: Thu, 18 Jun 2015 20:28:14 -0500 Subject: [Tutor] Deleting a Row From Excel Message-ID: I receive several Excel documents each week. I need to delete the first row from each document (multi tabs per document). I don't see a method in the openpyxl library (using Python 3.4). am I missing something? Is there a way to delete a row from Excel. Thanks Phillip From alan.gauld at btinternet.com Fri Jun 19 11:44:07 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 19 Jun 2015 10:44:07 +0100 Subject: [Tutor] Deleting a Row From Excel In-Reply-To: References: Message-ID: On 19/06/15 02:28, Phillip Pugh wrote: > I need to delete the first row from each document (multi tabs per document). Do you mean you need to delete the first row from each tab? Or the first row from the first tab? > I don't see a method in the openpyxl library (using Python 3.4). > am I missing something? Is there a way to delete a row from Excel. Usual caveat: This list is for the Python language and its standard library. openpyxl is not part of the standard library so you may get a better response on a dedicated support forum. That having been said it is certainly possible to delete rows from excel using the standard COM methods. You can access COM via the ctypes module in the standard library or, rather more easily, using PyWin32. The MSDN web site has documentation on the COM object/methods and sample code in VB that can translate to PyWin32 fairly easily. I have no idea whether openpyxl has an operation to do it, but it sounds like it should have. Try asking on their support forum. http://groups.google.com/group/openpyxl-users -- 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 Jun 19 11:49:16 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 19 Jun 2015 10:49:16 +0100 Subject: [Tutor] Attacking this problem (2 parts):JSON object to CSV file In-Reply-To: References: Message-ID: On 19/06/15 02:44, Saran Ahluwalia wrote: > However with the example JSON object (above) i receive the following error > when applying this function: > > ValueError: too many values to unpack > Please always include the full error trace not just the final line. Also, since this is quite an advanced question for a beginners list, you might want to consider asking on the main Python list too. However, I suspect we do have enough JSON users here to give you some 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 __peter__ at web.de Fri Jun 19 12:35:28 2015 From: __peter__ at web.de (Peter Otten) Date: Fri, 19 Jun 2015 12:35:28 +0200 Subject: [Tutor] Attacking this problem (2 parts):JSON object to CSV file References: Message-ID: Alan Gauld wrote: > On 19/06/15 02:44, Saran Ahluwalia wrote: > >> However with the example JSON object (above) i receive the following >> error when applying this function: >> >> ValueError: too many values to unpack >> > > Please always include the full error trace not just the final line. > > Also, since this is quite an advanced question for a beginners > list, you might want to consider asking on the main Python list too. > However, I suspect we do have enough JSON users here to give > you some help. There are already many threads on the main list, all started by Saran, with little progress. I provided the csv/json snippet in his post, but the goal posts are moving and I could not obtain a clear description of the problem. In short: he ate up my goodwill. From abhijeet560 at yahoo.in Sun Jun 21 18:19:43 2015 From: abhijeet560 at yahoo.in (abhijeet560 at yahoo.in) Date: Sun, 21 Jun 2015 16:19:43 +0000 (UTC) Subject: [Tutor] Attacking this problem (2 parts):JSON object to CSV file In-Reply-To: References: Message-ID: <1997077900.1676221.1434903583662.JavaMail.yahoo@mail.yahoo.com> hello, can you guys give me some ?advice regarding web development using python languageIs wordpress is easier to create a website or python framework(django or flask)?If then how to create a website User interface i.e of good elegant looking UI?? On Friday, 19 June 2015 4:06 PM, Peter Otten <__peter__ at web.de> wrote: Alan Gauld wrote: > On 19/06/15 02:44, Saran Ahluwalia wrote: > >> However with the example JSON object (above) i receive the following >> error when applying this function: >> >> ValueError: too many values to unpack >> > > Please always include the full error trace not just the final line. > > Also, since this is quite an advanced question for a beginners > list, you might want to consider asking on the main Python list too. > However, I suspect we do have enough JSON users here to give > you some help. There are already many threads on the main list, all started by Saran, with little progress. I provided the csv/json snippet in his post, but the goal posts are moving and I could not obtain a clear description of the problem. In short: he ate up my goodwill. _______________________________________________ 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 Sun Jun 21 19:06:10 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 21 Jun 2015 18:06:10 +0100 Subject: [Tutor] Attacking this problem (2 parts):JSON object to CSV file In-Reply-To: <1997077900.1676221.1434903583662.JavaMail.yahoo@mail.yahoo.com> References: <1997077900.1676221.1434903583662.JavaMail.yahoo@mail.yahoo.com> Message-ID: On 21/06/15 17:19, abhijeet560 at yahoo.in wrote: > hello, can you guys give me some advice regarding web development using python > languageIs wordpress is easier to create a website or python framework If you just want a standard web site with static content or a small amount of feedback/blogging type activity Wordpress is easier. If you want to do something outside of Wordpress' normal style and behaviour then a Python Framework might be worth considering. But it all depends on how much you need to customize things. > If then how to create a website User interface i.e of good elegant looking UI?? That's entirely down to your HTML/Javascript skills, and good taste. Python can't really help you 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 lac at openend.se Sun Jun 21 19:32:43 2015 From: lac at openend.se (Laura Creighton) Date: Sun, 21 Jun 2015 19:32:43 +0200 Subject: [Tutor] web development question In-Reply-To: Message from Alan Gauld of "Sun, 21 Jun 2015 18:06:10 +0100." References: <1997077900.1676221.1434903583662.JavaMail.yahoo@mail.yahoo.com> Message-ID: <201506211732.t5LHWhP6010974@fido.openend.se> If you don't know javascript, and want to code your website in python, you might consider using web2py http://www.web2py.com/ With web2py a whole lot of things happen automatically for you more or less 'by magic'. Whether you consider this a really great thing because you didn't want to have to learn all the low level details or a really terrible thing because you want absolute control over the low level details depends on you. Laura From alan.gauld at btinternet.com Sun Jun 21 21:09:54 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 21 Jun 2015 20:09:54 +0100 Subject: [Tutor] web development question In-Reply-To: <201506211732.t5LHWhP6010974@fido.openend.se> References: <1997077900.1676221.1434903583662.JavaMail.yahoo@mail.yahoo.com> <201506211732.t5LHWhP6010974@fido.openend.se> Message-ID: On 21/06/15 18:32, Laura Creighton wrote: > If you don't know javascript, and want to code your website in > python, you might consider using web2py > > http://www.web2py.com/ New one on me, looks interesting having viewed the first 4 videos. But not sure how it helps with the UI or Javascript? Its still just Python on the server? Very similar to Flask but with a nice web based IDE. But the UI (View) is still HTML/Javascript - and indeed web2py includes JQuery as a standard toolset. -- 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 lac at openend.se Sun Jun 21 21:50:42 2015 From: lac at openend.se (Laura Creighton) Date: Sun, 21 Jun 2015 21:50:42 +0200 Subject: [Tutor] web development question In-Reply-To: Message from Alan Gauld of "Sun, 21 Jun 2015 20:09:54 +0100." References: <1997077900.1676221.1434903583662.JavaMail.yahoo@mail.yahoo.com> <201506211732.t5LHWhP6010974@fido.openend.se> Message-ID: <201506211950.t5LJogcX013982@fido.openend.se> In a message of Sun, 21 Jun 2015 20:09:54 +0100, Alan Gauld writes: >On 21/06/15 18:32, Laura Creighton wrote: >> If you don't know javascript, and want to code your website in >> python, you might consider using web2py >> >> http://www.web2py.com/ > > >New one on me, looks interesting having viewed the first 4 videos. > >But not sure how it helps with the UI or Javascript? >Its still just Python on the server? Very similar to Flask >but with a nice web based IDE. >But the UI (View) is still HTML/Javascript > - and indeed web2py includes JQuery as a standard toolset. Maybe I am wrong, but I thought you could write in nothing but Python and HTML. I am going to start playing with web2py tomorrow, so I will find out how wrong I was. Laura From alan.gauld at btinternet.com Sun Jun 21 22:41:02 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 21 Jun 2015 21:41:02 +0100 Subject: [Tutor] web development question In-Reply-To: <201506211950.t5LJogcX013982@fido.openend.se> References: <1997077900.1676221.1434903583662.JavaMail.yahoo@mail.yahoo.com> <201506211732.t5LHWhP6010974@fido.openend.se> <201506211950.t5LJogcX013982@fido.openend.se> Message-ID: <5587215E.9070404@btinternet.com> On 21/06/15 20:50, Laura Creighton wrote: > > Its still just Python on the server? Very similar to Flask > > but with a nice web based IDE. > > But the UI (View) is still HTML/Javascript > > Maybe I am wrong, but I thought you could write in nothing but > Python and HTML. I am going to start playing with web2py tomorrow, > so I will find out how wrong I was. Like most Python web frameworks the server side is all Python but the Views(UI ) are in HTML which includes any Javascript you care to write. Web2py doesn't care about that it just sends it to the browser which interprets it as usual. So to write a modern-style web app with responsive UI you still need to wite it in HTML/Javascript using a combination of HTML5 and JQuery for the UI interactions/validations. The connection between the web2py server side bits (in the controllers) is the use of {{...}} markers within the HTML. Anything inside the double curlies gets translated to HTML by web2py, inserted into the View html and the View then gets and sent out along with the boilerplate in the layout (html) file. -- 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 jdv12 at case.edu Sun Jun 21 22:04:39 2015 From: jdv12 at case.edu (Joshua Valdez) Date: Sun, 21 Jun 2015 16:04:39 -0400 Subject: [Tutor] python and Beautiful soup question Message-ID: I'm having trouble making this script work to scrape information from a series of Wikipedia articles. What I'm trying to do is iterate over a series of wiki URLs and pull out the page links on a wiki portal category (e.g. https://en.wikipedia.org/wiki/Category:Electronic_design). I know that all the wiki pages I'm going through have a page links section. However when I try to iterate through them I get this error message: Traceback (most recent call last): File "./wiki_parent.py", line 37, in cleaned = pages.get_text()AttributeError: 'NoneType' object has no attribute 'get_text' Why do I get this error? The file I'm reading in the first part looks like this: 1 Category:Abrahamic_mythology2 Category:Abstraction3 Category:Academic_disciplines4 Category:Activism5 Category:Activists6 Category:Actors7 Category:Aerobics8 Category:Aerospace_engineering9 Category:Aesthetics and it is stored in a the port_ID dict like so: {1: 'Category:Abrahamic_mythology', 2: 'Category:Abstraction', 3: 'Category:Academic_disciplines', 4: 'Category:Activism', 5: 'Category:Activists', 6: 'Category:Actors', 7: 'Category:Aerobics', 8: 'Category:Aerospace_engineering', 9: 'Category:Aesthetics', 10: 'Category:Agnosticism', 11: 'Category:Agriculture'...} The desired output is: parent_num, page_ID, page_num I realize the code is a little hackish but I'm just trying to get this working: #!/usr/bin/env pythonimport os,re,nltkfrom bs4 import BeautifulSoupfrom urllib import urlopen url = "https://en.wikipedia.org/wiki/"+'Category:Furniture' rootdir = '/Users/joshuavaldez/Desktop/L1/en.wikipedia.org/wiki' reg = re.compile('[\w]+:[\w]+') number=1 port_ID = {}for root,dirs,files in os.walk(rootdir): for file in files: if reg.match(file): port_ID[number]=file number+=1 test_file = open('test_file.csv', 'w') for key, value in port_ID.iteritems(): url = "https://en.wikipedia.org/wiki/"+str(value) raw = urlopen(url).read() soup=BeautifulSoup(raw) pages = soup.find("div" , { "id" : "mw-pages" }) cleaned = pages.get_text() cleaned = cleaned.encode('utf-8') pages = cleaned.split('\n') pages = pages[4:-2] test = test = port_ID.items()[0] page_ID = 1 for item in pages: test_file.write('%s %s %s\n' % (test[0],item,page_ID)) page_ID+=1 page_ID = 1 Hi I posted this on stackoverflow and didn't really get any help so I though I would ask here to see if someone could help! Thanks! *Joshua Valdez* *Computational Linguist : Cognitive Scientist * (440)-231-0479 jdv12 at case.edu | jdv2 at uw.edu | joshv at armsandanchors.com From breamoreboy at yahoo.co.uk Mon Jun 22 00:55:34 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 21 Jun 2015 23:55:34 +0100 Subject: [Tutor] python and Beautiful soup question In-Reply-To: References: Message-ID: On 21/06/2015 21:04, Joshua Valdez wrote: > I'm having trouble making this script work to scrape information from a > series of Wikipedia articles. > > What I'm trying to do is iterate over a series of wiki URLs and pull out > the page links on a wiki portal category (e.g. > https://en.wikipedia.org/wiki/Category:Electronic_design). > > I know that all the wiki pages I'm going through have a page links section. > However when I try to iterate through them I get this error message: > > Traceback (most recent call last): > File "./wiki_parent.py", line 37, in > cleaned = pages.get_text()AttributeError: 'NoneType' object has no > attribute 'get_text' Presumably because this line > pages = soup.find("div" , { "id" : "mw-pages" }) doesn't find anything, pages is set to None and hence the attribute error on the next line. I'm suspicious of { "id" : "mw-pages" } as it's a Python dict comprehension with one entry of key "id" and value "mw-pages". -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From akleider at sonic.net Mon Jun 22 03:41:54 2015 From: akleider at sonic.net (Alex Kleider) Date: Sun, 21 Jun 2015 18:41:54 -0700 Subject: [Tutor] python and Beautiful soup question In-Reply-To: References: Message-ID: <2c9434aa0c6824950742935264251329@sonic.net> On 2015-06-21 15:55, Mark Lawrence wrote: > On 21/06/2015 21:04, Joshua Valdez wrote: >> I'm having trouble making this script work to scrape information from >> a >> series of Wikipedia articles. >> >> What I'm trying to do is iterate over a series of wiki URLs and pull >> out >> the page links on a wiki portal category (e.g. >> https://en.wikipedia.org/wiki/Category:Electronic_design). >> >> I know that all the wiki pages I'm going through have a page links >> section. >> However when I try to iterate through them I get this error message: >> >> Traceback (most recent call last): >> File "./wiki_parent.py", line 37, in >> cleaned = pages.get_text()AttributeError: 'NoneType' object has >> no >> attribute 'get_text' > > Presumably because this line > >> pages = soup.find("div" , { "id" : "mw-pages" }) > > doesn't find anything, pages is set to None and hence the attribute > error on the next line. I'm suspicious of { "id" : "mw-pages" } as > it's a Python dict comprehension with one entry of key "id" and value > "mw-pages". Why do you refer to { "id" : "mw-pages" } as a dict comprehension? Is that what a simple dict declaration is? From timomlists at gmail.com Mon Jun 22 12:11:30 2015 From: timomlists at gmail.com (Timo) Date: Mon, 22 Jun 2015 12:11:30 +0200 Subject: [Tutor] python and Beautiful soup question In-Reply-To: References: Message-ID: <5587DF52.3070503@gmail.com> Op 21-06-15 om 22:04 schreef Joshua Valdez: > I'm having trouble making this script work to scrape information from a > series of Wikipedia articles. > > What I'm trying to do is iterate over a series of wiki URLs and pull out > the page links on a wiki portal category (e.g. > https://en.wikipedia.org/wiki/Category:Electronic_design). Instead of scraping the webpage, I'd have a look at the API. This might give much better and more reliable results than to rely on parsing HTML. https://www.mediawiki.org/wiki/API:Main_page You can try out the huge amount of different options (with small descriptions) on the sandbox page: https://en.wikipedia.org/wiki/Special:ApiSandbox Timo > > > > > *Joshua Valdez* > *Computational Linguist : Cognitive Scientist > * > > (440)-231-0479 > jdv12 at case.edu | jdv2 at uw.edu | joshv at armsandanchors.com > > _______________________________________________ > 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 Mon Jun 22 15:39:07 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 22 Jun 2015 14:39:07 +0100 Subject: [Tutor] python and Beautiful soup question In-Reply-To: <2c9434aa0c6824950742935264251329@sonic.net> References: <2c9434aa0c6824950742935264251329@sonic.net> Message-ID: On 22/06/2015 02:41, Alex Kleider wrote: > On 2015-06-21 15:55, Mark Lawrence wrote: >> On 21/06/2015 21:04, Joshua Valdez wrote: >>> I'm having trouble making this script work to scrape information from a >>> series of Wikipedia articles. >>> >>> What I'm trying to do is iterate over a series of wiki URLs and pull out >>> the page links on a wiki portal category (e.g. >>> https://en.wikipedia.org/wiki/Category:Electronic_design). >>> >>> I know that all the wiki pages I'm going through have a page links >>> section. >>> However when I try to iterate through them I get this error message: >>> >>> Traceback (most recent call last): >>> File "./wiki_parent.py", line 37, in >>> cleaned = pages.get_text()AttributeError: 'NoneType' object has no >>> attribute 'get_text' >> >> Presumably because this line >> >>> pages = soup.find("div" , { "id" : "mw-pages" }) >> >> doesn't find anything, pages is set to None and hence the attribute >> error on the next line. I'm suspicious of { "id" : "mw-pages" } as >> it's a Python dict comprehension with one entry of key "id" and value >> "mw-pages". > > Why do you refer to { "id" : "mw-pages" } as a dict comprehension? > Is that what a simple dict declaration is? > No, I'm simply wrong, it's just a plain dict. Please don't ask, as I've no idea how it got into my head :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From steve at pearwood.info Tue Jun 23 02:44:35 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 23 Jun 2015 10:44:35 +1000 Subject: [Tutor] python and Beautiful soup question In-Reply-To: <5587DF52.3070503@gmail.com> References: <5587DF52.3070503@gmail.com> Message-ID: <20150623004434.GM20701@ando.pearwood.info> On Mon, Jun 22, 2015 at 12:11:30PM +0200, Timo wrote: > Op 21-06-15 om 22:04 schreef Joshua Valdez: > >I'm having trouble making this script work to scrape information from a > >series of Wikipedia articles. > > > >What I'm trying to do is iterate over a series of wiki URLs and pull out > >the page links on a wiki portal category (e.g. > >https://en.wikipedia.org/wiki/Category:Electronic_design). > Instead of scraping the webpage, I'd have a look at the API. This might > give much better and more reliable results than to rely on parsing HTML. > > https://www.mediawiki.org/wiki/API:Main_page Seconded, thirded and fourthed! Please don't scrape wikipedia. It is hard enough for them to deal with bandwidth requirements and remain responsive for browsers without badly-written bots trying to suck down pieces of the site. Use the API. Not only is it the polite thing to do, but it protects you too: Wikipedia is entitled to block your bot if they think it is not following the rules. > You can try out the huge amount of different options (with small > descriptions) on the sandbox page: > > https://en.wikipedia.org/wiki/Special:ApiSandbox -- Steve From manaswini.kat.gupta at hp.com Tue Jun 23 19:13:51 2015 From: manaswini.kat.gupta at hp.com (Gupta, Manaswini Kat) Date: Tue, 23 Jun 2015 17:13:51 +0000 Subject: [Tutor] FW: query Message-ID: From: Gupta, Manaswini Kat Sent: Tuesday, June 23, 2015 10:42 PM To: 'tutor-owner at python.org' Subject: FW: query From: Gupta, Manaswini Kat Sent: Tuesday, June 23, 2015 10:40 PM To: 'tutor-owner at python.org' Subject: query Hi, I need to fetch the records of count(*)>3 can you please tell me the logic in python Thanks&Regards, Manaswini Gupta From emile at fenx.com Tue Jun 23 19:57:30 2015 From: emile at fenx.com (Emile van Sebille) Date: Tue, 23 Jun 2015 10:57:30 -0700 Subject: [Tutor] FW: query In-Reply-To: References: Message-ID: You're more likely to get an appropriate response if you review http://catb.org/~esr/faqs/smart-questions.html and then ask. Emile On 6/23/2015 10:13 AM, Gupta, Manaswini Kat wrote: > > > From: Gupta, Manaswini Kat > Sent: Tuesday, June 23, 2015 10:42 PM > To: 'tutor-owner at python.org' > Subject: FW: query > > > > From: Gupta, Manaswini Kat > Sent: Tuesday, June 23, 2015 10:40 PM > To: 'tutor-owner at python.org' > Subject: query > > Hi, > I need to fetch the records of count(*)>3 can you please tell me the logic in python > > Thanks&Regards, > Manaswini Gupta > _______________________________________________ > 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 Jun 23 20:01:58 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 23 Jun 2015 19:01:58 +0100 Subject: [Tutor] FW: query In-Reply-To: References: Message-ID: On 23/06/15 18:13, Gupta, Manaswini Kat wrote: > I need to fetch the records of count(*)>3 can you please tell me the logic in python Sorry, but that's not very clear. What do you mean? It looks like a bit of SQL so, are you asking how to execute that SQL from within Python? If so on what database? Or are you trying to convert SQL logic into pure Python code? If so that depends on how you are storing your records. Are they in a list, a dictionary, a flat file? Also count(*)>3 is a boolean expression so it will return True or False and no records. What do you mean by fetching the records? Which records? You probably need to show us an example of your data and the results you want. Maybe show us the full SQL query you are trying to execute or emulate. -- 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 abhijeet560 at yahoo.in Wed Jun 24 14:58:53 2015 From: abhijeet560 at yahoo.in (abhijeet560 at yahoo.in) Date: Wed, 24 Jun 2015 12:58:53 +0000 (UTC) Subject: [Tutor] FW: query In-Reply-To: References: Message-ID: <143508438.352948.1435150733301.JavaMail.yahoo@mail.yahoo.com> Hey guys can anybody tell me what's wrong with this code: The code is below?Actually the point is that when we put "34h4" type of value it's an valueerror but here no handling is been performed by the python ??? while 1:? ? number=int(input("Enter the number which u want to check for odd and even :"))? ? try :? ? ? ? if number%2==0:? ? ? ? ? ? print("The number",number ," is Even")? ? ? ? else:? ? ? ? ? ? print("The number ",number ," is Odd")? ? ? ? ??? ? except ?ValueError:? ? ? ? print("Invalid Input") On Tuesday, 23 June 2015 11:32 PM, Alan Gauld wrote: On 23/06/15 18:13, Gupta, Manaswini Kat wrote: > I need to fetch the records of count(*)>3 can you please tell me the logic in python Sorry, but that's not very clear. What do you mean? It looks like a bit of SQL so, are you asking how to execute that SQL from within Python? If so on what database? Or are you trying to convert SQL logic into pure Python code? If so that depends on how you are storing your records. Are they in a list, a dictionary, a flat file? Also count(*)>3 is a boolean expression so it will return True or False and no records. What do you mean by fetching the records? Which records? You probably need to show us an example of your data and the results you want. Maybe show us the full SQL query you are trying to execute or emulate. -- 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 emile at fenx.com Wed Jun 24 18:15:05 2015 From: emile at fenx.com (Emile van Sebille) Date: Wed, 24 Jun 2015 09:15:05 -0700 Subject: [Tutor] FW: query In-Reply-To: <143508438.352948.1435150733301.JavaMail.yahoo@mail.yahoo.com> References: <143508438.352948.1435150733301.JavaMail.yahoo@mail.yahoo.com> Message-ID: On 6/24/2015 5:58 AM, abhijeet560 at yahoo.in wrote: > Hey guys can anybody tell me what's wrong with this code: The code is below? > Actually the point is that when we put "34h4" type of value it's an valueerror > but here no handling is been performed by the python ??? > while 1: > number=int(input("Enter the number which u want to check for odd and even :")) You're probably seeing the error here, which is outside your try/except block, hence the except not working as you expect. > try : Emile From alan.gauld at btinternet.com Wed Jun 24 18:27:36 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 24 Jun 2015 17:27:36 +0100 Subject: [Tutor] FW: query In-Reply-To: <143508438.352948.1435150733301.JavaMail.yahoo@mail.yahoo.com> References: <143508438.352948.1435150733301.JavaMail.yahoo@mail.yahoo.com> Message-ID: On 24/06/15 13:58, abhijeet560 at yahoo.in wrote: > Hey guys can anybody tell me what's wrong with this code: The code is below? Please in future 1) start a new thread with a new post, do not hijack somebody else's query. It messes up the archive and threaded mail/newsreaders 2) Use plain text for posting code, your post is all messed up by the mail system so we can't see the code clearly. It is all on one line... > Actually the point is that when we put "34h4" type of value > it's an valueerror but here no handling is been performed The handling only happens if it occurs inside a try block. It looks as if your type conversion (int(...)) happens outside the try block. The error is raised by the type conversion. > while 1: number=int(input("Enter the number which u want to check for odd and even :")) try : if number%2==0: print("The number",number ," is Even") else: print("The number ",number ," is Odd") except ValueError: print("Invalid Input") Finally, handling an error by simply printing a bland error message is usually not a good idea. You effectively hide a lot of valuable debugging information. You would be better to just let Python print out its usual, much more helpful, error message. (The exception is where it's the top level of an end-user program where the Python trace might scare the users. But that should only be after you have thoroughly debugged it and handled most of the likely problem scenarios, and hopefully logged the error data into a logfile or sent it as an email to your support desk.) -- 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 nimmy021 at yahoo.com Wed Jun 24 21:25:46 2015 From: nimmy021 at yahoo.com (Nirav Patel) Date: Wed, 24 Jun 2015 19:25:46 +0000 (UTC) Subject: [Tutor] Python Help Message-ID: <2115053443.612381.1435173946430.JavaMail.yahoo@mail.yahoo.com> Hi, my name is Nirav.? I have a question about my code. I am a student at a university that does research using a program called VisIt. We use VisIt to help our learning in computational fluid dynamics and using the information, we study the turbulence of scramjets.? One simple thing I am trying to do is using python to call a command that processes all the files that exist within the directory by having visit access the files.? I have started to code below, but every time the code is executed, I get an error that says, "u-name command not found" along with an error that says, "VisIt is not supported by platform." I know my information is hard to follow or comprehend, but I really need to find a way to get this code working.? Thank you in advance! import osos.environ["PATH"]= '/Applications/VisIt.app/Contents/Resources/bin/'files = os.listdir('/Users/niravpatel/Desktop/Visit /plotfiles')print filesfor file in files:? ? if '.py' in file:? ? ? ? import subprocess? ? ? ? subprocess.call(['visit', '-nowin', '-cli'])? ? ? ?? From alan.gauld at btinternet.com Thu Jun 25 02:54:15 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 25 Jun 2015 01:54:15 +0100 Subject: [Tutor] Python Help In-Reply-To: <2115053443.612381.1435173946430.JavaMail.yahoo@mail.yahoo.com> References: <2115053443.612381.1435173946430.JavaMail.yahoo@mail.yahoo.com> Message-ID: On 24/06/15 20:25, Nirav Patel via Tutor wrote: > ... research using a program called VisIt. > One simple thing I am trying to do is using python > to call a command that processes all the files that > exist within the directory by having visit access the files. > I have started to code below, but every time the code > is executed, I get an error that says, > "u-name command not found" > along with an error that says, > "VisIt is not supported by platform." Can you post the actual print out from your console in full? Also can you tell us what 'platform' you are using - OS, and VisIT and Python versions > import osos.environ["PATH"]= '/Applications/VisIt.app/Contents/Resources/bin/'files = os.listdir('/Users/niravpatel/Desktop/Visit /plotfiles')print filesfor file in files: if '.py' in file: import subprocess subprocess.call(['visit', '-nowin', '-cli']) Please post code in plain text, this is all in one line making it very hard to read. I'll try to unscramble it... > import os > os.environ["PATH"]= '/Applications/VisIt.app/Contents/Resources/bin/' > files = os.listdir('/Users/niravpatel/Desktop/Visit /plotfiles') > print files Looks like Python v2? I'm not sure why you are setting the PATH environment variable unless VisIT reads it? If so you do realize that setting it like this will wipe out all the existing entries? Finally is there supposed to be a space in the last folder name? > for file in files: > if '.py' in file: You are looping over the python files? Is that really what you want? > import subprocess Its usual to put all imports at the top of the file in one place. Not necessary but conventional. > subprocess.call(['visit', '-nowin', '-cli']) You are not specifying any input files/paths to visit so you just repeat the same command over and over. Do the commands PATH='/Applications/VisIt.app/Contents/Resources/bin/' visit -nowin -cli work at the command line? Or do you get different error messages? -- 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 wombingsac at gmail.com Thu Jun 25 05:59:19 2015 From: wombingsac at gmail.com (Whom Isac) Date: Thu, 25 Jun 2015 13:59:19 +1000 Subject: [Tutor] FW: query In-Reply-To: References: <143508438.352948.1435150733301.JavaMail.yahoo@mail.yahoo.com> Message-ID: *def *odd_or_even(): X=input("Enter the number which you want to check for odd and even: ") number=int(X) print("The number %s is ODD."%(number) *if *number%2!=0 *else *"The number %s is EVEN."%(number)) On Thu, Jun 25, 2015 at 1:53 PM, Whom Isac wrote: > Hi, Abhijeet560 at yahoo.in: > there is four or five ways to do your question as I had done one for you > before. As you could tell there are also a shorter version to do this, > using list comprehension method. I would recommend you to use codeacademy > if you are not sure. Here is a quickest way for the ODD/EVEN list > comprehension. Both works the same way too. > > > def odd_or_even(): > X=input("Enter the number which you want to check for odd and even: ") > number=int(X) > print("The %s is ODD"%(number)if number%2!=0 else "The %s is EVEN"%(number)) > > > On Thu, Jun 25, 2015 at 1:47 PM, Whom Isac wrote: > >> Yes, I agree with Alan Gauld. >> >> For Gupta's case: >> >> if you wanted to get your point across you should mention your intention >> and could have posted any error message along with your code. Because, your >> question is vague and if the original script of the code had been posted, >> that would have been a huge help. >> >> And, for Abhijeet560 at yahoo.in: >> >> Is that any section of the function?? If it is then please, repost your >> question with full definition of the function and please read python's rule >> to indentation, maybe that's where the error is. However, as you said your >> function execute normally, therefore I am assuming you misunderstood how >> while loops works. Note for you: I don't think there would be any exception >> raise for ValueError in your code so try: and except: method would not be >> necessary.. >> >> For a simple odd and even finder I would try to do this: >> >> """ODD or EVEN Finder: """ >> >> def odd_or_even(): >> X=input("Enter the number which you want to check for odd and even: ") >> number=int(X) >> while True: >> if number%2==0: >> print("The number ", number, " is Even.") >> #number +=1 >> else: >> print("The number ",number, " is Odd") >> break >> pass >> >> >> >> >> On Thu, Jun 25, 2015 at 2:27 AM, Alan Gauld >> wrote: >> >>> On 24/06/15 13:58, abhijeet560 at yahoo.in wrote: >>> >>>> Hey guys can anybody tell me what's wrong with this code: The code is >>>> below? >>>> >>> >>> Please in future >>> 1) start a new thread with a new post, do not hijack somebody else's >>> query. It messes up the archive and threaded mail/newsreaders >>> >>> 2) Use plain text for posting code, your post is all messed up by the >>> mail system so we can't see the code clearly. It is all on one line... >>> >>> Actually the point is that when we put "34h4" type of value >>>> >>> > it's an valueerror but here no handling is been performed >>> >>> The handling only happens if it occurs inside a try block. It looks as >>> if your type conversion (int(...)) happens outside the try block. >>> The error is raised by the type conversion. >>> >>> while 1: number=int(input("Enter the number which u want to check >>>> for odd and even :")) try : if number%2==0: print("The >>>> number",number ," is Even") else: print("The number >>>> ",number ," is Odd") except ValueError: print("Invalid >>>> Input") >>>> >>> >>> Finally, handling an error by simply printing a bland error message >>> is usually not a good idea. You effectively hide a lot of valuable >>> debugging information. You would be better to just let Python print >>> out its usual, much more helpful, error message. >>> >>> (The exception is where it's the top level of an end-user program >>> where the Python trace might scare the users. But that should only >>> be after you have thoroughly debugged it and handled most of the >>> likely problem scenarios, and hopefully logged the error data >>> into a logfile or sent it as an email to your support desk.) >>> >>> >>> -- >>> 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 wombingsac at gmail.com Thu Jun 25 06:06:43 2015 From: wombingsac at gmail.com (Whom Isac) Date: Thu, 25 Jun 2015 14:06:43 +1000 Subject: [Tutor] FW: query In-Reply-To: References: <143508438.352948.1435150733301.JavaMail.yahoo@mail.yahoo.com> Message-ID: For abhijeet560 at yahoo.in: I had posted few solution to your question before but unfortunately they were sent to Alan Gauld mail because I am not used to the tutor at python.org mail system. Here is the code that will work: ""ODD/EVEN finder:""" def odd_or_even(): X=input("Enter the number which you want to check for odd and even: ") try: number=int(X) print("The number %s is ODD."%(number)if number%2!=0 else "The number %s is EVEN."%(number)) except ValueError: print("Invalid input") On Thu, Jun 25, 2015 at 1:59 PM, Whom Isac wrote: > *def *odd_or_even(): > X=input("Enter the number which you want to check for odd and even: ") > number=int(X) > print("The number %s is ODD."%(number) *if *number%2!=0 *else *"The > number %s is EVEN."%(number)) > > On Thu, Jun 25, 2015 at 1:53 PM, Whom Isac wrote: > >> Hi, Abhijeet560 at yahoo.in: >> there is four or five ways to do your question as I had done one for you >> before. As you could tell there are also a shorter version to do this, >> using list comprehension method. I would recommend you to use codeacademy >> if you are not sure. Here is a quickest way for the ODD/EVEN list >> comprehension. Both works the same way too. >> >> >> def odd_or_even(): >> X=input("Enter the number which you want to check for odd and even: ") >> number=int(X) >> print("The %s is ODD"%(number)if number%2!=0 else "The %s is EVEN"%(number)) >> >> >> On Thu, Jun 25, 2015 at 1:47 PM, Whom Isac wrote: >> >>> Yes, I agree with Alan Gauld. >>> >>> For Gupta's case: >>> >>> if you wanted to get your point across you should mention your >>> intention and could have posted any error message along with your code. >>> Because, your question is vague and if the original script of the code had >>> been posted, that would have been a huge help. >>> >>> And, for Abhijeet560 at yahoo.in: >>> >>> Is that any section of the function?? If it is then please, repost your >>> question with full definition of the function and please read python's rule >>> to indentation, maybe that's where the error is. However, as you said your >>> function execute normally, therefore I am assuming you misunderstood how >>> while loops works. Note for you: I don't think there would be any exception >>> raise for ValueError in your code so try: and except: method would not be >>> necessary.. >>> >>> For a simple odd and even finder I would try to do this: >>> >>> """ODD or EVEN Finder: """ >>> >>> def odd_or_even(): >>> X=input("Enter the number which you want to check for odd and even: ") >>> number=int(X) >>> while True: >>> if number%2==0: >>> print("The number ", number, " is Even.") >>> #number +=1 >>> else: >>> print("The number ",number, " is Odd") >>> break >>> pass >>> >>> >>> >>> >>> On Thu, Jun 25, 2015 at 2:27 AM, Alan Gauld >>> wrote: >>> >>>> On 24/06/15 13:58, abhijeet560 at yahoo.in wrote: >>>> >>>>> Hey guys can anybody tell me what's wrong with this code: The code is >>>>> below? >>>>> >>>> >>>> Please in future >>>> 1) start a new thread with a new post, do not hijack somebody else's >>>> query. It messes up the archive and threaded mail/newsreaders >>>> >>>> 2) Use plain text for posting code, your post is all messed up by the >>>> mail system so we can't see the code clearly. It is all on one line... >>>> >>>> Actually the point is that when we put "34h4" type of value >>>>> >>>> > it's an valueerror but here no handling is been performed >>>> >>>> The handling only happens if it occurs inside a try block. It looks as >>>> if your type conversion (int(...)) happens outside the try block. >>>> The error is raised by the type conversion. >>>> >>>> while 1: number=int(input("Enter the number which u want to check >>>>> for odd and even :")) try : if number%2==0: print("The >>>>> number",number ," is Even") else: print("The number >>>>> ",number ," is Odd") except ValueError: print("Invalid >>>>> Input") >>>>> >>>> >>>> Finally, handling an error by simply printing a bland error message >>>> is usually not a good idea. You effectively hide a lot of valuable >>>> debugging information. You would be better to just let Python print >>>> out its usual, much more helpful, error message. >>>> >>>> (The exception is where it's the top level of an end-user program >>>> where the Python trace might scare the users. But that should only >>>> be after you have thoroughly debugged it and handled most of the >>>> likely problem scenarios, and hopefully logged the error data >>>> into a logfile or sent it as an email to your support desk.) >>>> >>>> >>>> -- >>>> 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 wombingsac at gmail.com Thu Jun 25 06:08:09 2015 From: wombingsac at gmail.com (Whom Isac) Date: Thu, 25 Jun 2015 14:08:09 +1000 Subject: [Tutor] FW: query In-Reply-To: References: <143508438.352948.1435150733301.JavaMail.yahoo@mail.yahoo.com> Message-ID: Sorry, the interpreter uses colour which is why some code is missing. Here is the text version of my code: def odd_or_even(): X=input("Enter the number which you want to check for odd and even: ") try: number=int(X) print("The number %s is ODD."%(number)if number%2!=0 else "The number %s is EVEN."%(number)) except ValueError: print("Invalid input") On Thu, Jun 25, 2015 at 2:06 PM, Whom Isac wrote: > For abhijeet560 at yahoo.in: > I had posted few solution to your question before but unfortunately they > were sent to Alan Gauld mail because I am not used to the tutor at python.org > mail system. > Here is the code that will work: > ""ODD/EVEN finder:""" > > > def odd_or_even(): > X=input("Enter the number which you want to check for odd and even: ") > try: > number=int(X) > print("The number %s is ODD."%(number)if number%2!=0 else "The number %s is EVEN."%(number)) > except ValueError: > print("Invalid input") > > > On Thu, Jun 25, 2015 at 1:59 PM, Whom Isac wrote: > >> *def *odd_or_even(): >> X=input("Enter the number which you want to check for odd and even: ") >> number=int(X) >> print("The number %s is ODD."%(number) *if *number%2!=0 *else *"The >> number %s is EVEN."%(number)) >> >> On Thu, Jun 25, 2015 at 1:53 PM, Whom Isac wrote: >> >>> Hi, Abhijeet560 at yahoo.in: >>> there is four or five ways to do your question as I had done one for you >>> before. As you could tell there are also a shorter version to do this, >>> using list comprehension method. I would recommend you to use codeacademy >>> if you are not sure. Here is a quickest way for the ODD/EVEN list >>> comprehension. Both works the same way too. >>> >>> >>> def odd_or_even(): >>> X=input("Enter the number which you want to check for odd and even: ") >>> number=int(X) >>> print("The %s is ODD"%(number)if number%2!=0 else "The %s is EVEN"%(number)) >>> >>> >>> On Thu, Jun 25, 2015 at 1:47 PM, Whom Isac wrote: >>> >>>> Yes, I agree with Alan Gauld. >>>> >>>> For Gupta's case: >>>> >>>> if you wanted to get your point across you should mention your >>>> intention and could have posted any error message along with your code. >>>> Because, your question is vague and if the original script of the code had >>>> been posted, that would have been a huge help. >>>> >>>> And, for Abhijeet560 at yahoo.in: >>>> >>>> Is that any section of the function?? If it is then please, repost your >>>> question with full definition of the function and please read python's rule >>>> to indentation, maybe that's where the error is. However, as you said your >>>> function execute normally, therefore I am assuming you misunderstood how >>>> while loops works. Note for you: I don't think there would be any exception >>>> raise for ValueError in your code so try: and except: method would not be >>>> necessary.. >>>> >>>> For a simple odd and even finder I would try to do this: >>>> >>>> """ODD or EVEN Finder: """ >>>> >>>> def odd_or_even(): >>>> X=input("Enter the number which you want to check for odd and even: ") >>>> number=int(X) >>>> while True: >>>> if number%2==0: >>>> print("The number ", number, " is Even.") >>>> #number +=1 >>>> else: >>>> print("The number ",number, " is Odd") >>>> break >>>> pass >>>> >>>> >>>> >>>> >>>> On Thu, Jun 25, 2015 at 2:27 AM, Alan Gauld >>>> wrote: >>>> >>>>> On 24/06/15 13:58, abhijeet560 at yahoo.in wrote: >>>>> >>>>>> Hey guys can anybody tell me what's wrong with this code: The code is >>>>>> below? >>>>>> >>>>> >>>>> Please in future >>>>> 1) start a new thread with a new post, do not hijack somebody else's >>>>> query. It messes up the archive and threaded mail/newsreaders >>>>> >>>>> 2) Use plain text for posting code, your post is all messed up by the >>>>> mail system so we can't see the code clearly. It is all on one line... >>>>> >>>>> Actually the point is that when we put "34h4" type of value >>>>>> >>>>> > it's an valueerror but here no handling is been performed >>>>> >>>>> The handling only happens if it occurs inside a try block. It looks as >>>>> if your type conversion (int(...)) happens outside the try block. >>>>> The error is raised by the type conversion. >>>>> >>>>> while 1: number=int(input("Enter the number which u want to check >>>>>> for odd and even :")) try : if number%2==0: print("The >>>>>> number",number ," is Even") else: print("The number >>>>>> ",number ," is Odd") except ValueError: print("Invalid >>>>>> Input") >>>>>> >>>>> >>>>> Finally, handling an error by simply printing a bland error message >>>>> is usually not a good idea. You effectively hide a lot of valuable >>>>> debugging information. You would be better to just let Python print >>>>> out its usual, much more helpful, error message. >>>>> >>>>> (The exception is where it's the top level of an end-user program >>>>> where the Python trace might scare the users. But that should only >>>>> be after you have thoroughly debugged it and handled most of the >>>>> likely problem scenarios, and hopefully logged the error data >>>>> into a logfile or sent it as an email to your support desk.) >>>>> >>>>> >>>>> -- >>>>> 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 ahlusar.ahluwalia at gmail.com Thu Jun 25 20:42:16 2015 From: ahlusar.ahluwalia at gmail.com (Saran Ahluwalia) Date: Thu, 25 Jun 2015 14:42:16 -0400 Subject: [Tutor] Newbie to Python: enumerate XML tags (keys that will become headers) along with text (values) and write to CSV in one row (as opposed to "stacked" values with one header) Message-ID: My question can be found here: http://stackoverflow.com/questions/31058100/enumerate-column-headers-in-csv-that-belong-to-the-same-tag-key-in-python Here is an additional sample sample of the XML that I am working with: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1/1/0001 12:00:00 AM 1/1/0001 12:00:00 AM 1/1/0001 12:00:00 AM 1/1/0001 12:00:00 AM 1/1/0001 12:00:00 AM 1/1/0001 12:00:00 AM 1/1/0001 12:00:00 AM 1/1/0001 12:00:00 AM False False False False False 0 -- From alan.gauld at btinternet.com Fri Jun 26 00:51:16 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 25 Jun 2015 23:51:16 +0100 Subject: [Tutor] Newbie to Python: enumerate XML tags (keys that will become headers) along with text (values) and write to CSV in one row (as opposed to "stacked" values with one header) In-Reply-To: References: Message-ID: On 25/06/15 19:42, Saran Ahluwalia wrote: > My question can be found here: > > http://stackoverflow.com/questions/31058100/enumerate-column-headers-in-csv-that-belong-to-the-same-tag-key-in-python It would have been helpful to post the question here rather than just a link. However, having read it, I'm still not sure what you want to do? It seems your input file (the XML one?) has multiple ObjectGuid tags? And you want to write them out to a CSV file with a number appended (objectGuid_1, ObjectGuid_2 etc) Is that right? If so what exactly is the issue - it seems simple enough (given your obvious coding experience) to store a counter and create a new string each time you find a GUID tag? But I still don't understand how these tags relate to the rest of the data in the file? Are you only extracting the GUID and want one row per file? Or are you extracting multiple data structures and creating a row for each? In which case are the multiple GUID embedded in each data structure? I'm really not sure what you are trying to do. > Here is an additional sample sample of the XML that I am working with: I have no idea how that is supposed to help? It doesn't have any ObjectGUID tags that I can see? It is essentially meaningless data (to us). > > > > 0 > 0 > 0 > 0 > 0 > 0 > 0 > 0 > 0 > 0 > 0 > 0 > 0 > 0 > 0 > 0 > 0 > 0 > 0 > 0 > 0 > 0 > 0 > 0 > 0 > > > 0 > 0 > 0 > 0 > 0 > 0 > > > 0 > 0 > 0 > 0 > 0 > 0 > 0 > 0 > > > 1/1/0001 12:00:00 AM > 1/1/0001 12:00:00 AM > 1/1/0001 12:00:00 AM > 1/1/0001 12:00:00 AM > 1/1/0001 12:00:00 AM > 1/1/0001 12:00:00 AM > 1/1/0001 12:00:00 AM > 1/1/0001 12:00:00 AM > > > > > False > False > False > False > False > 0 > > > > > -- -- 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 breamoreboy at yahoo.co.uk Fri Jun 26 02:36:02 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 26 Jun 2015 01:36:02 +0100 Subject: [Tutor] Newbie to Python: enumerate XML tags (keys that will become headers) along with text (values) and write to CSV in one row (as opposed to "stacked" values with one header) In-Reply-To: References: Message-ID: On 25/06/2015 23:51, Alan Gauld wrote: > On 25/06/15 19:42, Saran Ahluwalia wrote: >> My question can be found here: >> >> http://stackoverflow.com/questions/31058100/enumerate-column-headers-in-csv-that-belong-to-the-same-tag-key-in-python >> > > It would have been helpful to post the question here rather than just a > link. > > However, having read it, I'm still not sure what you want to do? > It seems your input file (the XML one?) has multiple ObjectGuid tags? > And you want to write them out to a CSV file with a number appended > (objectGuid_1, ObjectGuid_2 etc) Is that right? If so what exactly is > the issue - it seems simple enough (given your obvious coding > experience) to store a counter and create a new string each time you > find a GUID tag? > > But I still don't understand how these tags relate to the rest of the > data in the file? Are you only extracting the GUID and want one row per > file? Or are you extracting multiple data structures and creating a row > for each? In which case are the multiple GUID embedded in each data > structure? I'm really not sure what you are trying to do. > >> Here is an additional sample sample of the XML that I am working with: > > I have no idea how that is supposed to help? It doesn't have any > ObjectGUID tags that I can see? It is essentially meaningless > data (to us). > I wouldn't be inclined to put too much into this, it's already been asked on the main mailing list and appears to be a follow up to an earlier thread. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From steve at pearwood.info Fri Jun 26 17:23:20 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 27 Jun 2015 01:23:20 +1000 Subject: [Tutor] Newbie to Python: enumerate XML tags (keys that will become headers) along with text (values) and write to CSV in one row (as opposed to "stacked" values with one header) In-Reply-To: References: Message-ID: <20150626152319.GV20701@ando.pearwood.info> On Thu, Jun 25, 2015 at 02:42:16PM -0400, Saran Ahluwalia wrote: > My question can be found here: > > http://stackoverflow.com/questions/31058100/enumerate-column-headers-in-csv-that-belong-to-the-same-tag-key-in-python You might think you are saving time in not typing the question twice, but you're not. You're just limiting the number of people who might answer your question, which means it will take you even longer to get the answer. The 30 seconds that you save by not writing the question here might cost you hours or days to get an answer. I'm reading your question via email, and it is inconvenient for me to switch to a browser and go read the question on another site, copy the question, paste it back into an email, manually edit that to quote it (add > to the beginning of each line), and then respond. If I really cared about your question, if it was a topic that interested me greatly, I might do it. But I don't like dealing with XML and I think CSV is boring, so I won't. Other tutors might be browsing their email from a network that blocks Stackoverflow, so they cannot see the question at all. -- Steve From nymcity at yahoo.com Sun Jun 28 21:32:40 2015 From: nymcity at yahoo.com (Nym City) Date: Sun, 28 Jun 2015 19:32:40 +0000 (UTC) Subject: [Tutor] Loop not iterating Message-ID: <173732399.1437176.1435519960841.JavaMail.yahoo@mail.yahoo.com> Hello, I am working on my second program and its a two part progam that I want to design However, i am not sure what silly mistake I am making on the first part: Here is my code: | 2 3 4 5 6 7 | import csv domains = open('top500domains.csv') domainsReader = csv.reader(domains) domainLists = list(domainsReader) for domain in domainLists: something = ("www." + str(domain)) print(something) | My program reads in a CSV file that has 500 list of domains. However, when I save the output of my loop to the variable name "something" - and later print "something" it contains only 1 entry from my csv file. On the other hand, instead of saving of loop output to the variable "something" - if I just print, I get all 500 entries displayed. Please advise. Thanks! https://bpaste.net/show/3664abce17b7 ??Thank you. From street.sweeper at mailworks.org Sat Jun 27 02:03:48 2015 From: street.sweeper at mailworks.org (street.sweeper at mailworks.org) Date: Fri, 26 Jun 2015 20:03:48 -0400 Subject: [Tutor] removing nodes using ElementTree Message-ID: <1435363428.3645868.308926073.37C151F0@webmail.messagingengine.com> Hello all, I'm trying to merge and filter some xml. This is working well, but I'm getting one node that's not in my list to include. Python version is 3.4.0. The goal is to merge multiple xml files and then write a new one based on whether or not is in an include list. In the mock data below, the 3 xml files have a total of 8 nodes, and I have 4 values in my list. The output is correctly formed xml, but it includes 5 nodes; the 4 in the list, plus 89012 from input1.xml. It runs without error. I've used used type() to compare rec.find('part').find('pid').text and the items in the list, they're strings. When the first for loop is done, xmlet has 8 rec nodes. Is there a problem in the iteration in the second for? Any other recommendations also welcome. Thanks! The code itself was cobbled together from two sources, http://stackoverflow.com/questions/9004135/merge-multiple-xml-files-from-command-line/11315257#11315257 and http://bryson3gps.wordpress.com/tag/elementtree/ Here's the code and data: #!/usr/bin/env python3 import os, glob from xml.etree import ElementTree as ET xmls = glob.glob('input*.xml') ilf = os.path.join(os.path.expanduser('~'),'include_list.txt') xo = os.path.join(os.path.expanduser('~'),'mergedSortedOutput.xml') il = [x.strip() for x in open(ilf)] xmlet = None for xml in xmls: d = ET.parse(xml).getroot() for rec in d.iter('inv'): if xmlet is None: xmlet = d else: xmlet.extend(rec) for rec in xmlet: if rec.find('part').find('pid').text not in il: xmlet.remove(rec) ET.ElementTree(xmlet).write(xo) quit() include_list.txt 12345 34567 56789 67890 input1.xml 67890 67890t 67890d 78901 78901t 78901d 89012 89012t 89012d input2.xml 45678 45678t 45678d 56789 56789t 56789d input3.xml 12345 12345t 12345d 23456 23456t 23456d 34567 34567t 34567d mergedSortedOutput.xml: 67890 67890t 67890d 89012 89012t 89012d 12345 12345t 12345d 34567 34567t 34567d 56789 56789t 56789d From alan.gauld at btinternet.com Mon Jun 29 01:56:17 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 29 Jun 2015 00:56:17 +0100 Subject: [Tutor] Loop not iterating In-Reply-To: <173732399.1437176.1435519960841.JavaMail.yahoo@mail.yahoo.com> References: <173732399.1437176.1435519960841.JavaMail.yahoo@mail.yahoo.com> Message-ID: On 28/06/15 20:32, Nym City via Tutor wrote: > import csv > domains = open('top500domains.csv') > domainsReader = csv.reader(domains) > domainLists = list(domainsReader) > for domain in domainLists: > something = ("www." + str(domain)) You overwrite something each time round the loop. > print(something) And because this is outside the loop it will only ever print the last item. But since you have only stored one item thats OK... > My program reads in a CSV file that has 500 list of domains. However, > when I save the output of my loop to the variable name "something" Ypu are saving each item into something but then next time round you throw away the old one and replace it wotyh the next. You should create a list and store it there. But you already have that list, its called domainLists. I'm not sure what you think you are achieving here? > - and later print "something" it contains only 1 entry from my csv file. Because the print is outside the loop and only prints the value of something after the loop completes. That will be the last entry. > On the other hand, instead of saving of loop output to the variable > "something" - if I just print, I get all 500 entries displayed. Because you are printing inside the loop. So it prints each item. 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 Mon Jun 29 02:02:56 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 29 Jun 2015 01:02:56 +0100 Subject: [Tutor] removing nodes using ElementTree In-Reply-To: <1435363428.3645868.308926073.37C151F0@webmail.messagingengine.com> References: <1435363428.3645868.308926073.37C151F0@webmail.messagingengine.com> Message-ID: On 27/06/15 01:03, street.sweeper at mailworks.org wrote: > I'm trying to merge and filter some xml. This is working well, but I'm > getting one node that's not in my list to include. This may be similar to a recent post with similar issues. > for rec in xmlet: > if rec.find('part').find('pid').text not in il: > xmlet.remove(rec) You're removing records from the thing you are iterating over. That's never a good idea, and often causes the next record to be stepped over without being processed. Try taking a copy before iterating and then modify the original. for rec in xmlet[:]: # slice creates a copy if rec.... xmlet.remove(rec) 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 breamoreboy at yahoo.co.uk Mon Jun 29 02:06:57 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 29 Jun 2015 01:06:57 +0100 Subject: [Tutor] Loop not iterating In-Reply-To: <173732399.1437176.1435519960841.JavaMail.yahoo@mail.yahoo.com> References: <173732399.1437176.1435519960841.JavaMail.yahoo@mail.yahoo.com> Message-ID: On 28/06/2015 20:32, Nym City via Tutor wrote: > Hello, > I am working on my second program and its a two part progam that I want to design However, i am not sure what silly mistake I am making on the first part: > Here is my code: > > | 2 > 3 > 4 > 5 > 6 > 7 | import csv > domains = open('top500domains.csv') > domainsReader = csv.reader(domains) > domainLists = list(domainsReader) > for domain in domainLists: > something = ("www." + str(domain)) > print(something) > > | > > My program reads in a CSV file that has 500 list of domains. However, when I save the output of my loop to the variable name "something" - and later print "something" it contains only 1 entry from my csv file. > On the other hand, instead of saving of loop output to the variable "something" - if I just print, I get all 500 entries displayed. > Please advise. Thanks! > You are not saving your loop output to anything. The above code simply sets 'something' every time around the loop, and only prints 'something' once when the loop has finished. Try something like this. urls = [] # a Python list in case you didn't know. for domain in domainLists: urls.append("www." + str(domain)) # add to the end of the list for url in urls: doWhatever(url) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From steve at pearwood.info Mon Jun 29 04:52:07 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 29 Jun 2015 12:52:07 +1000 Subject: [Tutor] Loop not iterating In-Reply-To: <173732399.1437176.1435519960841.JavaMail.yahoo@mail.yahoo.com> References: <173732399.1437176.1435519960841.JavaMail.yahoo@mail.yahoo.com> Message-ID: <20150629025206.GA20701@ando.pearwood.info> Hi Nym, and welcome, On Sun, Jun 28, 2015 at 07:32:40PM +0000, Nym City via Tutor wrote: [...] > for domain in domainLists: > something = ("www." + str(domain)) > print(something) > > My program reads in a CSV file that has 500 list of domains. However, > when I save the output of my loop to the variable name "something" - > and later print "something" it contains only 1 entry from my csv file. Of course it does. Each time you go through the loop, you change the value of "something" to the new value. If you do this: x = 23 x = 42 print(x) What do you expect to print? Hopefully 42. If you want multiple values, you need something like a list: x = [] x.append(23) x.append(42) print(x) Of course, in *this* case, there is an easier way to create a list with two values: x = [23, 42] but in the general case where you don't know how many values you will have, you need to add them using append inside a loop. -- Steve From __peter__ at web.de Mon Jun 29 10:58:26 2015 From: __peter__ at web.de (Peter Otten) Date: Mon, 29 Jun 2015 10:58:26 +0200 Subject: [Tutor] removing nodes using ElementTree References: <1435363428.3645868.308926073.37C151F0@webmail.messagingengine.com> Message-ID: street.sweeper at mailworks.org wrote: > Hello all, > > I'm trying to merge and filter some xml. This is working well, but I'm > getting one node that's not in my list to include. Python version is > 3.4.0. > > The goal is to merge multiple xml files and then write a new one based > on whether or not is in an include list. In the mock data below, > the 3 xml files have a total of 8 nodes, and I have 4 values > in my list. The output is correctly formed xml, but it includes 5 > nodes; the 4 in the list, plus 89012 from input1.xml. It runs without > error. I've used used type() to compare > rec.find('part').find('pid').text and the items in the list, they're > strings. When the first for loop is done, xmlet has 8 rec nodes. Is > there a problem in the iteration in the second for? Any other > recommendations also welcome. Thanks! > > > The code itself was cobbled together from two sources, > http://stackoverflow.com/questions/9004135/merge-multiple-xml-files-from-> command-line/11315257#11315257 > and http://bryson3gps.wordpress.com/tag/elementtree/ > > Here's the code and data: > > #!/usr/bin/env python3 > > import os, glob > from xml.etree import ElementTree as ET > > xmls = glob.glob('input*.xml') > ilf = os.path.join(os.path.expanduser('~'),'include_list.txt') > xo = os.path.join(os.path.expanduser('~'),'mergedSortedOutput.xml') > > il = [x.strip() for x in open(ilf)] > > xmlet = None > > for xml in xmls: > d = ET.parse(xml).getroot() > for rec in d.iter('inv'): > if xmlet is None: > xmlet = d > else: > xmlet.extend(rec) > > for rec in xmlet: > if rec.find('part').find('pid').text not in il: > xmlet.remove(rec) > > ET.ElementTree(xmlet).write(xo) > > quit() I believe Alan answered your question; I just want to thank you for taking the time to describe your problem clearly and for providing all the necessary parts to reproduce it. Bonus part: Other options to filter a mutable sequence: (1) assign to the slice: items[:] = [item for item in items if is_match(item)] (2) iterate over it in reverse order: for item in reversed(items): if not ismatch(item): items.remove(item) Below is a way to integrate method 1 in your code: [...] # set lookup is more efficient than lookup in a list il = set(x.strip() for x in open(ilf)) def matching_recs(recs): return (rec for rec in recs if rec.find("part/pid").text in il) xmlet = None for xml in xmls: inv = ET.parse(xml).getroot() if xmlet is None: xmlet = inv # replace all recs with matching recs xmlet[:] = matching_recs(inv) else: # append only matching recs xmlet.extend(matching_recs(inv)) ET.ElementTree(xmlet).write(xo) # the script will end happily without a quit() or exit() call # quit() At least with your sample data > for rec in d.iter('inv'): iterates over a single node (the root) so I omitted that loop. From nymcity at yahoo.com Tue Jun 30 03:05:13 2015 From: nymcity at yahoo.com (Nym City) Date: Tue, 30 Jun 2015 01:05:13 +0000 (UTC) Subject: [Tutor] Loop not iterating In-Reply-To: <20150629025206.GA20701@ando.pearwood.info> References: <20150629025206.GA20701@ando.pearwood.info> Message-ID: <1595536231.2446666.1435626313055.JavaMail.yahoo@mail.yahoo.com> Hello all, Thank you for your time and tips. The reason why I decided to create a loop is because the output is cleaner and did not require any formatting. However, based on what I have learned from all of your responses, that is not going to work with what I am trying to do. Here is the updated code: import csvdomains = open('top500domains.csv')domainsReader = csv.reader(domains)domainLists = list(domainsReader)print('\n'.join(["https://www ." + str(lst) for lst in domainLists]), sep='\n') ------------------------- It is almost how I want it - however, I cannot seem to figure out how to format the output to drop the [' '] from the output. For example, here is how the output comes up:https://www .['facebook.com/'] I would like to get it in:https://www.facebook.com Please suggest what is the best, as well as the easiest way to format data out of lists. (I image myself creating a lot of lists and would be helpful to know how to generally handle formatting with lists)? Thanks in advance! :)) ?Thank you. On Sunday, June 28, 2015 10:57 PM, Steven D'Aprano wrote: Hi Nym, and welcome, On Sun, Jun 28, 2015 at 07:32:40PM +0000, Nym City via Tutor wrote: [...] > for domain in domainLists: >? ? ? something = ("www." + str(domain)) > print(something) > > My program reads in a CSV file that has 500 list of domains. However, > when I save the output of my loop to the variable name "something" - > and later print "something" it contains only 1 entry from my csv file. Of course it does. Each time you go through the loop, you change the value of "something" to the new value. If you do this: x = 23 x = 42 print(x) What do you expect to print? Hopefully 42. If you want multiple values, you need something like a list: x = [] x.append(23) x.append(42) print(x) Of course, in *this* case, there is an easier way to create a list with two values: x = [23, 42] but in the general case where you don't know how many values you will have, you need to add them using append inside a loop. -- Steve _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor From steve at pearwood.info Tue Jun 30 04:19:01 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 30 Jun 2015 12:19:01 +1000 Subject: [Tutor] Loop not iterating In-Reply-To: <1595536231.2446666.1435626313055.JavaMail.yahoo@mail.yahoo.com> References: <20150629025206.GA20701@ando.pearwood.info> <1595536231.2446666.1435626313055.JavaMail.yahoo@mail.yahoo.com> Message-ID: <20150630021900.GB10773@ando.pearwood.info> On Tue, Jun 30, 2015 at 01:05:13AM +0000, Nym City wrote: > Hello all, > Thank you for your time and tips. The reason why I decided to create a > loop is because the output is cleaner and did not require any > formatting. However, based on what I have learned from all of your > responses, that is not going to work with what I am trying to do. There's no reason why a loop wouldn't work, although there may be better solutions, and a loop is a much better solution to what you have below. > Here is the updated code: > import csvdomains = open('top500domains.csv')domainsReader = > csv.reader(domains)domainLists = > list(domainsReader)print('\n'.join(["https://www ." + str(lst) for lst > in domainLists]), sep='\n') Please ensure you post as *plain text*, not HTML (so called "rich text" or "formatted text"). When you post as HTML, many mail programs mangle the code and destroy the formatting, as you can see above. Reconstructing what the code should look like on five separate lines: import csv domains = open('top500domains.csv') domainsReader = csv.reader(domains) domainLists = list(domainsReader) print('\n'.join(["https://www ." + str(lst) for lst in domainLists]), sep='\n') The first three lines seem to be correct, but the next: domainLists = list(domainsReader) is unnecessary and should be deleted. However, the last line does too much, and the wrong thing too. A simple loop is *much* better here, since you just print the domains and don't need to keep them for further processing: for row in domainLists: # row is a list of *one or more* fields; in this case, there # is only one field per row, the domain name domain = "https://www." + row[0] print(domain) Suppose that you do need to keep the domains for later, as well as print them. Then you can do this instead: import csv domains = open('top500domains.csv') domainsReader = csv.reader(domains) # Make a list of the domains. domains = ["https://www." + row[0] for row in domainsReader] # Print each domain. for domain in domains: print(domain) # Now continue to do more work on the list of domains... -- Steve From marilyn at pythontrainer.com Tue Jun 30 08:47:45 2015 From: marilyn at pythontrainer.com (Marilyn Davis) Date: Mon, 29 Jun 2015 23:47:45 -0700 (PDT) Subject: [Tutor] __repr__ and __str__ Message-ID: <58064.50.168.22.182.1435646865.squirrel@mail.tigertech.net> Hello Python Tutors, A student has asked a question that has me stumped. We are using 2.7. Looking at this code: #!/usr/bin/python class MyList(list): def __str__(self): return """Here are your data: %s """ % list.__str__(self) def main(): a = MyList([1,2]) print a if __name__ == "__main__": main() ___ We get the expected output: Here are your data: [1, 2] But if we add the special method: def __repr__(self): return "MyList(%s)" % (list.__str__(self)) we get: Traceback (most recent call last): File "./stack2.py", line 17, in main() File "./stack2.py", line 14, in main print a File "./stack2.py", line 10, in __str__ """ % list.__str__(self) File "./stack2.py", line 5, in __repr__ return "MyList(%s)" % (list.__str__(self)) File "./stack2.py", line 5, in __repr__ return "MyList(%s)" % (list.__str__(self)) and on and on to the: RuntimeError: maximum recursion depth exceeded -- >From https://docs.python.org/2/reference/datamodel.html: If a class defines __repr__() but not __str__(), then __repr__() is also used when an ?informal? string representation of instances of that class is required. __ So ????? __str__ is defined and works just fine unless we also define __repr__. What am I missing? Thank you for any help. Marilyn Davis From stephanie.quiles001 at albright.edu Tue Jun 30 07:02:23 2015 From: stephanie.quiles001 at albright.edu (Stephanie Quiles) Date: Tue, 30 Jun 2015 01:02:23 -0400 Subject: [Tutor] GUI program Message-ID: Hello, i am attempting to create a GUI program using Python 3.4. please see the pasted code below. Why is nothing showing up? i am using Pycharm to run the program to see what it does and it says there are no errors but it does not show me an output. please let me know where i am falling short on this. Thank you __author__ = 'stephaniequiles' """ Write a GUI program that displays your name and address when a button is clicked. when the user clicks the 'show info' button, the program should display your name and address, as shown in the sketch.""" import tkinter class AddressGUI: def __init__(self): self.main_window = tkinter.Tk() self.top_frame= tkinter.Frame() self.mid_frame= tkinter.Frame() self.bottom_frame = tkinter.Frame() self.name_label= tkinter.Label(self.top_frame,\ text='Steven Marcus') self.name_label.pack(side='left') self.value = tkinter.StringVar() self.address_label = tkinter.Label(self.mid_frame,\ text='274 Baily Drive Waynesville, NC 27999') self.address_label.pack(side='left') self.show_button = tkinter.Button(self.bottom_frame,\ text="show info",\ command=self.showinfo) self.quit_button = tkinter.Button(self.bottom_frame,\ tect ='Quit',\ command=self.main_window.destroy) self.show_button.pack(side='left') self.quit_button.pack(side='left') self.top_frame.pack() self.mid_frame.pack() self.bottom_frame.pack() tkinter.mainloop() def showinfo(self): name = 'Steven Marcus' address = '274 Baily Drive Waynesville, NC 27999' info = name + address allinfo = AddressGUI() From alan.gauld at btinternet.com Tue Jun 30 14:33:33 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 30 Jun 2015 13:33:33 +0100 Subject: [Tutor] __repr__ and __str__ In-Reply-To: <58064.50.168.22.182.1435646865.squirrel@mail.tigertech.net> References: <58064.50.168.22.182.1435646865.squirrel@mail.tigertech.net> Message-ID: On 30/06/15 07:47, Marilyn Davis wrote: > class MyList(list): > def __str__(self): > return """Here are your data: > %s > """ % list.__str__(self) > > def main(): > a = MyList([1,2]) > print a > But if we add the special method: > > def __repr__(self): > return "MyList(%s)" % (list.__str__(self)) > > we get: > > File "./stack2.py", line 10, in __str__ > """ % list.__str__(self) > File "./stack2.py", line 5, in __repr__ > return "MyList(%s)" % (list.__str__(self)) > File "./stack2.py", line 5, in __repr__ > return "MyList(%s)" % (list.__str__(self)) > RuntimeError: maximum recursion depth exceeded > If a class defines __repr__() but not __str__(), then __repr__() is also > used when an ?informal? string representation of instances of that class > is required. My guess is that list.__str__ is calling self.__repr__ But you have defined your own self.__repr__ so it gets called and it then calls list.__str__ again, and again and .... Try replacing the call to list.__str__ with a call to list.__repr__ and see if that fixes things? -- 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 Jun 30 14:45:57 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 30 Jun 2015 13:45:57 +0100 Subject: [Tutor] GUI program In-Reply-To: References: Message-ID: On 30/06/15 06:02, Stephanie Quiles wrote: > Hello, i am attempting to create a GUI program using Python 3.4. please see the pasted code below. > Why is nothing showing up? Because you have defined the GUI inside a class. But you never instantiate that class so the code never gets executed. However, there are several other issue that you should think about... > import tkinter > > class AddressGUI: > def __init__(self): > self.main_window = tkinter.Tk() > > self.top_frame= tkinter.Frame() Your widgets, including Frames should always have an explicit parent defined. Things can get awfully confused otherwise and debugging what's happening is a pain. So use self.main_window as your parent for these frames. > self.mid_frame= tkinter.Frame() > self.bottom_frame = tkinter.Frame() > > self.name_label= tkinter.Label(self.top_frame,\ > text='Steven Marcus') > > self.name_label.pack(side='left') > > > self.value = tkinter.StringVar() > self.address_label = tkinter.Label(self.mid_frame,\ > text='274 Baily Drive Waynesville, NC 27999') > > self.address_label.pack(side='left') > > self.show_button = tkinter.Button(self.bottom_frame,\ > text="show info",\ > command=self.showinfo) > self.quit_button = tkinter.Button(self.bottom_frame,\ > tect ='Quit',\ > command=self.main_window.destroy) Personally I'd probably use quit() rather than destroy(). The latter leaves the objects in memory, and the evebnt loop running, only removing the window widgets. quit() closes the event loop and shuts things down a bit more thoroughly in my experience. > self.show_button.pack(side='left') > self.quit_button.pack(side='left') > > self.top_frame.pack() > self.mid_frame.pack() > self.bottom_frame.pack() > > tkinter.mainloop() Its usually better to start the mainloop outside the application class. Not least because it makes reuse easier. But also because it offers better control of initialisation/ finalisation actions. > def showinfo(self): > name = 'Steven Marcus' > address = '274 Baily Drive Waynesville, NC 27999' > info = name + address > > allinfo = AddressGUI() And a recursive call to the app inside an event handler is a recipe for confusion. You will have multiple instances around in memory with potentially multiple event loops (see note on destroy) above. Especially since you don;t even store a reference to the new app instance. The allinfo variable gets deleted when the method completes. In general its a good idea to byui8ld your program in small chunks. Get a basic GUI with windows to display then add the widgets one by one and test them as you go. Its much easier to debug things when you only have a small amount of new code to look at. -- 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 Jun 30 15:10:52 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 30 Jun 2015 23:10:52 +1000 Subject: [Tutor] __repr__ and __str__ In-Reply-To: <58064.50.168.22.182.1435646865.squirrel@mail.tigertech.net> References: <58064.50.168.22.182.1435646865.squirrel@mail.tigertech.net> Message-ID: <20150630131051.GC10773@ando.pearwood.info> On Mon, Jun 29, 2015 at 11:47:45PM -0700, Marilyn Davis wrote: > Hello Python Tutors, > > A student has asked a question that has me stumped. We are using 2.7. Ooh, nice one! That had me stumped for a while too, but I think I have the solution. I wrote this class to investigate: class MyList(list): def __str__(self): print "called __str__" return list.__str__(self) def __repr__(self): print "called __repr__" return list.__repr__(self) Then I ran this in the interactive interpreter: py> L = MyList([1, 2, 3]) py> repr(L) called __repr__ '[1, 2, 3]' py> str(L) called __str__ called __repr__ '[1, 2, 3]' So what appears to be happening is that list.__str__ calls __repr__. My guess is that it is written something like this: # built-in list class list: def __str__(self): return self.__repr__() -- Steve From jdv12 at case.edu Tue Jun 30 17:10:37 2015 From: jdv12 at case.edu (Joshua Valdez) Date: Tue, 30 Jun 2015 11:10:37 -0400 Subject: [Tutor] memory error Message-ID: So I wrote this script to go over a large wiki XML dump and pull out the pages I want. However, every time I run it the kernel displays 'Killed' I'm assuming this is a memory issue after reading around but I'm not sure where the memory problem is in my script and if there were any tricks to reduce the virtual memory usage. Here is my code (I assume the problem is in the BeautifulSoup partition as the pages file is pretty small. from bs4 import BeautifulSoup import sys pages_file = open('pages_file.txt', 'r') #Preprocessing pages = pages_file.readlines() pages = map(lambda s: s.strip(), pages) page_titles=[] for item in pages: item = ''.join([i for i in item if not i.isdigit()]) item = ''.join([i for i in item if ord(i)<126 and ord(i)>31]) item = item.replace(" ","") item = item.replace("_"," ") page_titles.append(item) ##################################### with open(sys.argv[1], 'r') as wiki: soup = BeautifulSoup(wiki) wiki.closed wiki_page = soup.find_all("page") del soup for item in wiki_page: title = item.title.get_text() if title in page_titles: print item del title *Joshua Valdez* *Computational Linguist : Cognitive Scientist * (440)-231-0479 jdv12 at case.edu | jdv2 at uw.edu | joshv at armsandanchors.com From marilyn at pythontrainer.com Tue Jun 30 19:08:24 2015 From: marilyn at pythontrainer.com (Marilyn Davis) Date: Tue, 30 Jun 2015 10:08:24 -0700 (PDT) Subject: [Tutor] __repr__ and __str__ In-Reply-To: <20150630131051.GC10773@ando.pearwood.info> References: <58064.50.168.22.182.1435646865.squirrel@mail.tigertech.net> <20150630131051.GC10773@ando.pearwood.info> Message-ID: <58884.50.168.22.182.1435684104.squirrel@mail.tigertech.net> Thank you so much Alan and Steve. We are good now. Marilyn On Tue, June 30, 2015 6:10 am, Steven D'Aprano wrote: > On Mon, Jun 29, 2015 at 11:47:45PM -0700, Marilyn Davis wrote: > >> Hello Python Tutors, >> >> >> A student has asked a question that has me stumped. We are using 2.7. >> > > Ooh, nice one! That had me stumped for a while too, but I think I have > the solution. I wrote this class to investigate: > > class MyList(list): def __str__(self): print "called __str__" return > list.__str__(self) def __repr__(self): print "called __repr__" return > list.__repr__(self) > > > > Then I ran this in the interactive interpreter: > > > py> L = MyList([1, 2, 3]) py> repr(L) called __repr__ '[1, 2, 3]' > py> str(L) called __str__ called __repr__ '[1, 2, 3]' > > > > So what appears to be happening is that list.__str__ calls __repr__. My > guess is that it is written something like this: > > # built-in list > class list: def __str__(self): return self.__repr__() > > > > -- > Steve > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From ben+python at benfinney.id.au Tue Jun 30 22:38:19 2015 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 01 Jul 2015 06:38:19 +1000 Subject: [Tutor] __repr__ and __str__ References: <58064.50.168.22.182.1435646865.squirrel@mail.tigertech.net> Message-ID: <85fv59rkxw.fsf@benfinney.id.au> "Marilyn Davis" writes: > Hello Python Tutors, > > A student has asked a question that has me stumped. We are using 2.7. > > Looking at this code: > > #!/usr/bin/python > > class MyList(list): > > def __str__(self): > return """Here are your data: > %s > """ % list.__str__(self) That's okay, but yo should instead use the ?super? method to get the superclass, instead of assuming it's known. Python allows any class to participate in multiple inheritance, and that's not determined at the point of writing your class. So you can never assume you know what class is next in the resolution order; that's what ?super? is for:: class MyList(list): def __str__(self): text = """Here are your data: %s """ % super().__str__() return text (I am assuming this is Python 3 code, since Python 2 is legacy-only and should not be used for teaching today. If you need Python 2, it needs a different ?super? invocation; see its documentation.) > But if we add the special method: > > def __repr__(self): > return "MyList(%s)" % (list.__str__(self)) That's another problem (as pointed out by others in this thread). In addition to using ?super? to determine the superclass, you should also be calling the equivalent method on the superclass. In other words, since you're defining ?__repr__?, it is ?__repr__? you should be calling on the superclass:: def __repr__(self): text = "MyList(%s)" % super().__repr__() return text > So ????? __str__ is defined and works just fine unless we also define > __repr__. > > What am I missing? The complications of inheritance and calls to the superclass. When defining special methods (the ?dunder? methods, so named because they are named with a double leading and trailing underscore), it is best only to extend the same method on the superclass, and not complicate the connextions back and forth. > Thank you for any help. Hope that helps. Thank you for teaching Python 3 to more students! -- \ ?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