Re: [Tutor] Good approach regarding classes attributes
On 7 September 2014 21:01, Danny Yoo d...@hashcollision.org wrote: snip Let's use a concrete example: say that we'd like to make sure a Person's name is always capitalized. We might try to enforce this capitalization property in the constructor. Hi all, rant on I've just again experienced a new employer that tells my students my name is 'Van Den Broek' when I tell them that it is 'van den Broek.' This is the third time this week I've encountered this as a programming example. Perhaps the use of the example is responsible for the false belief amongst programmers that a surname always starts with a captial letter. (Also delightful is the view that no name can contain spaces.) For the love of puppies, can people please stop using this example?! /rant off (Apologies to Danny; as the other two cases I saw recently were in books, it was easiest to lash out against this example.) notVanDenly yours, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How inefficient is this code?
On May 7, 2014 7:30 PM, C Smith illusiontechniq...@gmail.com wrote: snip Someone suggested projecteuler.net and I started blazing through things I had done before, when I realized this would be a good time to start more efficient practices instead of code that just happens to work and may be very inefficient. #sum all even fib seq integers under 4 million fibs = [1,2] sum = 0 while fibs[-1] 400: nexty = fibs[-1] + fibs[-2] fibs.append(nexty) for xer in fibs: if xer%2 == 0: sum += xer print sum This gets the correct solution, but what would be ways to improve speed or use more complicated parts of Python to do the same thing. Intuitive judgements about efficiency and 5$ will buy you a Starbuck's. That qualification made: It is most likely to be more efficient to dispense with the results list. Instead, move the parity test into the while loop and augment the running sum there. But, test the resultant code for efficiency or you only know that some guy told you it was likely more efficient. Best, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How inefficient is this code?
On May 7, 2014 8:42 PM, C Smith illusiontechniq...@gmail.com wrote: I guess intuiting efficiency doesn't work in Python because it is such high-level? Or is there much more going on there? Hi, The level is a good part, yes. If, like me, you don't know what C constructs are under python constructs, you are guessing shapes of objects by the shadows they cast. But, that's not the sole issue. Ever write code that you thought did what you wanted only to run it and find out you were wrong? That happens because your intuitive judgements aren't giving you perfectly reliable insight into what code does :-) Best, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] sending email via SMTP: code review requested
On 5 May 2014 13:53, Steven D'Aprano st...@pearwood.info wrote: On Sun, May 04, 2014 at 07:00:24PM -0400, Brian van den Broek wrote: Hi all, I am playing with the smtp and email modules from the standard library of Python 2.7.3 (I also want it to run on 2.6.6). I've not found the going easy; the SMTP and RFC 2822 standards are not ones I have worked with before. Neither have I :-( Hi All, Thanks for the feedback, Steven. (And to Japhy for the earlier reply). I have something that works, but I am not confident I am doing the right thing. For that matter, I am not very confident that I am not doing the wrong thing. The code seems nicely written, it's understandable and easy to read. I haven't tried running it yet, but nothing stands out as obviously wrong. Well, gosh'n'golly-gee. I would very much appreciate some more experienced eyes on the code below. In addition to any outright errors concerning interaction with an SMTP server and constructing a MIME message, I would of course also welcome style comments. (Preemptively, I will note it isn't obvious I ought to have gone OOP with this.) Having the SMTPSender object send a message automatically on instantiation strikes me as a bit wiffy. I'm not sure if it's a good design or not. But for a simple cron job, it may be fine. That is a pattern I often have and for which I often have an associated spidey-tingle. If I have a class that exists to handle some processing and then be heard from no more, it always seems a bit funny to do: my_thing = MyOneTimeTaskClass(vars) my_thing.do_it() as every time I instantiate MyOneTimeTaskClass I am going to immediately ask the instance to do the things it does. Either way feels, as you say `wiffy.' (I think I shall steal that.) [...] And, as I side note, could anyone explain why changing a first world of a body line 'From' to 'From' is the preferred standard? Because it's a dirty, nasty hack invented by somebody who wasn't thinking very carefully at the time, and now everybody does it. Bleh. I understand what the problem is that is being solved, but as most email clients interpret a leading '' as an indication of quoting, I would have thought ' From' or something like '-From' would have been better. If I have my own code deal with the problem in one of these ways, will I be breaking anything? Yes. The idea is that your email client should recognise the hack when it sees a line From ... and hide the leading . So if you use some other character, say, !From ..., other people's mail clients won't know to hide the !. Oh dear. I developed my code mostly checking the resulting email with the gmail app on Android. It doesn't handle things this way; instead, some (variable! No, really) portion of the message body gets displayed as a quote. I would declare my surprise, but little about the act of malice that is the gmail Android app could surprise me now. (Unlike the web interface, there is quite literally no way to send plain text from the app.) Anyway, thanks again, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] sending email via SMTP: code review requested
Hi all, I am playing with the smtp and email modules from the standard library of Python 2.7.3 (I also want it to run on 2.6.6). I've not found the going easy; the SMTP and RFC 2822 standards are not ones I have worked with before. I have something that works, but I am not confident I am doing the right thing. For that matter, I am not very confident that I am not doing the wrong thing. I would very much appreciate some more experienced eyes on the code below. In addition to any outright errors concerning interaction with an SMTP server and constructing a MIME message, I would of course also welcome style comments. (Preemptively, I will note it isn't obvious I ought to have gone OOP with this.) I should also mention that I am writing this code as part of some tools to send myself and others reminder emails, the tools to be run from a cron job. I am storing an actual email account password in plaintext in my code. But, the account in question is one established just for the purpose of the reminder project and similar projects; it is not an account which houses my plans for world domination or the like. That said, I have removed the account name and password string below; it will thus require some adjustments to run for testing. And, as I side note, could anyone explain why changing a first world of a body line 'From' to 'From' is the preferred standard? I understand what the problem is that is being solved, but as most email clients interpret a leading '' as an indication of quoting, I would have thought ' From' or something like '-From' would have been better. If I have my own code deal with the problem in one of these ways, will I be breaking anything? Anyway, thanks and best, Brian vdB import smtplib class SMTPSender(object): def __init__(self, server, port, sender, password, messages): self.server = server self.port = port self.sender = sender self.password = password self.messages = messages self._connect() try: self._send() finally: self._logout() def _connect(self): self.session = smtplib.SMTP(server, port) self.session.ehlo() self.session.starttls() self.session.ehlo self.session.login(sender, password) def _send(self): for message in self.messages: to_addresses = message[To].split(,) self.session.sendmail(sender, to_addresses, message.as_string()) def _logout(self): self.session.quit() if __name__ == __main__: server = smtp.gmail.com port = 587 sender = myfunnyhan...@gmail.com password = mysecret from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart # Quick and dirty test message msg = MIMEMultipart(alternative) msg[Subject] = SMTP Test MIMEText plain msg[From] = sender # Setting to anything but sender gets removed by gmail. msg[To] = some...@example.com, someonee...@example.com msg[Reply-to] = answerh...@example.com body = \n\n.join([Test msg MIME Text, From is a problem when occuring as the first word of a line.]) msg.attach(MIMEText(body, plain)) sender = SMTPSender(server, port, sender, password, [msg,]) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Alice_in_wonderland Question
On May 4, 2014 8:31 PM, Jake Blank jakenbl...@gmail.com wrote: Hi, So I'm doing a problem on the Alice_in_wonderland.txt where I have to write a program that reads a piece of text from a file specified by the user, counts the number of occurrences of each word, and writes a sorted list of words and their counts to an output file. The list of words should be sorted based on the counts, so that the most popular words appear at the top. Words with the same counts should be sorted alphabetically. My code right now is word_count = {} file = open ('alice_in_wonderland.txt', 'r') full_text = file.read().replace('--',' ') full_text_words = full_text.split() for words in full_text_words: stripped_words = words.strip(.,!?'`\- ();:) try: word_count[stripped_words] += 1 except KeyError: word_count[stripped_words] = 1 ordered_keys = word_count.keys() sorted(ordered_keys) print (All the words and their frequency in, 'alice in wonderland') for k in ordered_keys: print (k, word_count[k]) The Output here is just all of the words in the document NOT SORTED by amount of occurrence. I need help sorting this output of words in the Alice_in_wonderland.txt, as well as help asking the user for the input information about the files. If anyone could give me some guidance you will really be helping me out. Please and Thank you Hi Jake, You are sorting the dictionary keys by the keys themselves, whereas what you want is the keys sorted by their associated values. Look at the key parameter in https://docs.python.org/3.4/library/functions.html#sorted. To get you started, here is an example in the vicinity: data = ['abiab', 'cdocd', 'efaef', 'ghbgh'] sorted(data) ['abiab', 'cdocd', 'efaef', 'ghbgh'] sorted(data, key=lambda x:x[2]) ['efaef', 'ghbgh', 'abiab', 'cdocd'] def get_third(x): return x[2] ... sorted(data, key=get_third) ['efaef', 'ghbgh', 'abiab', 'cdocd'] In case the lambda version is confusing, it is simply a way of doing the get_third version without having to create a function outside of the context of the sorted expression. If that sorts you, great. If not, please do ask a follow-up. (I was trying not to do it for you, but also not to frustrate by giving you too little of a push.) Best, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Alice_in_wonderland Question
Hi Jake, Please do be sure to use Reply All rather than just Reply. I'm sending my reply and and quotes from yours to the list; that way, others can follow along, learn and help. Also, in general, reply under the messages to which you respond, ideally trimming what isn't needed away. (You will see that is what I have done below.) Yes, that's not how email is used outside of technical circles. I'd maintain the technical circles's preference for not top posting is right. But, right or wrong, it is what those whom you are asking for free help prefer, so it is prudent to do it, gritting your teeth if you must :-) On 4 May 2014 21:36, Jake Blank jakenbl...@gmail.com wrote: Hey Thanks for responding. So now my code looks like this: from wordtools import extract_words source_filepath=input(Enter the path to the source file:) dest_filepath =input(Enter the path to the destination file:) sourcef=open(source_filepath, 'r') destf=open(dest_filepath, 'w') for line in sourcef: destf.write(line) file=input (Would you like to process another file?(Y/N):) if file== Y: source_filepath=input(Enter the path to the source file:) dest_filepath =input(Enter the path to the destination file:) else: word_count = {} file = open (source_filepath, 'r') full_text = file.read().replace('--',' ') full_text_words = full_text.split() for words in full_text_words: stripped_words = words.strip(.,!?'`\- ();:) try: word_count[stripped_words] += 1 except KeyError: word_count[stripped_words] = 1 ordered_keys = word_count.keys() sorted(ordered_keys) print ('This is the output file for Alice in Wonderland') for k in sorted(ordered_keys): print (k, word_count[k]) The first part about the user specifying the file is a little off but besides that I am able to return all of the words in the story with the number of times they occur alphabetically. In order to return the sorted list by number of times that each word occurs I am a little confused if i have to change something in my print statement? I understand how i have to sort the words by their associated values i'm confused where in my code i would do that. Thanks, Jake On Sun, May 4, 2014 at 9:16 PM, Brian van den Broek brian.van.den.br...@gmail.com wrote: On May 4, 2014 8:31 PM, Jake Blank jakenbl...@gmail.com wrote: snip Jake's original question Hi Jake, You are sorting the dictionary keys by the keys themselves, whereas what you want is the keys sorted by their associated values. Look at the key parameter in https://docs.python.org/3.4/library/functions.html#sorted. To get you started, here is an example in the vicinity: data = ['abiab', 'cdocd', 'efaef', 'ghbgh'] sorted(data) ['abiab', 'cdocd', 'efaef', 'ghbgh'] sorted(data, key=lambda x:x[2]) ['efaef', 'ghbgh', 'abiab', 'cdocd'] def get_third(x): return x[2] ... sorted(data, key=get_third) ['efaef', 'ghbgh', 'abiab', 'cdocd'] In case the lambda version is confusing, it is simply a way of doing the get_third version without having to create a function outside of the context of the sorted expression. If that sorts you, great. If not, please do ask a follow-up. (I was trying not to do it for you, but also not to frustrate by giving you too little of a push.) So, the code in your second message didn't seem to reflect any changes in light of the hint I gave. Did you not see how to apply it? If so, that's fine. But, rather than leave me guessing, it would be better to say; that way I, or others in the thread, can better direct efforts to help. Does this help more? data = {'a':2, 'b':4, 'c':3, 'd':1} sorted(data,key=lambda x:data[x]) ['d', 'a', 'c', 'b'] sorted(data,key=lambda x:data[x]) ['d', 'a', 'c', 'b'] data = {'a':2, 'b':4, 'c':3, 'd':1} sorted(data) ['a', 'b', 'c', 'd'] sorted(data,key=lambda x:data[x]) ['d', 'a', 'c', 'b'] for letter in sorted(data,key=lambda x:data[x]): ... print(letter, data[letter]) ... d 1 a 2 c 3 b 4 for letter in sorted(data,key=lambda x:data[x],reverse=True): ... print(letter, data[letter]) ... b 4 c 3 a 2 d 1 Can you see how key=lambda x:data[x] is forcing the sort to consider not the keys of the dictionary, but their associated values? Best, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Alice_in_wonderland Question
On May 4, 2014 11:13 PM, Jake Blank jakenbl...@gmail.com wrote: To figure that last part out I just did a simple if statement. for k in sorted(word_count, key=lambda x:word_count[x], reverse=True): if word_count[k] =300: print (k, word_count[k]) And the output was correct. Jake, That was in an effort to get only the 15most frequent words, if I understood your earliest post aright. If so, even if the output was correct for the case, that is by accident. What happens in only 3 distinct words show up 300 times? If 42 do? You need to rethink, I think. Do you know how list indexing and list slicing work? I did have one more question though. import os from wordtools import extract_words source_filepath=input(Enter the path to the source file:) dest_filepath =input(Enter the path to the destination file:) sourcef=open(source_filepath, 'r') destf=open(dest_filepath, 'w') for line in sourcef: destf.write(line) file=input (Would you like to process another file?(Y/N):) if file== Y: source_filepath=input(Enter the path to the source file:) dest_filepath =input(Enter the path to the destination file:) else: This code asks the user for a source/dest_filepath. I'm wondering how I can make it so the program can tell if the source/dest_filepath the user entered is actually a program on the computer. a program on the computer? I assume that you mean file. What happens if you run open( nowayyouhaveafilecalledthiscausethatdbesilly, 'r') That's rather different than if the path is the path of an existing file, right. So, you could try to react differently to the two sorts of results. Do you know how to use try an except? Also i have to ask the user if they would like to process another file(Y/N)? and I'm not sure where to put that. I shall leave this for others; I'm not ready for my Monday, yet. Best, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Cantor pairing in three dimensions?
On 24 December 2013 16:21, Brian van den Broek brian.van.den.br...@gmail.com wrote: On 23 December 2013 13:32, Danny Yoo d...@hashcollision.org wrote: I've got a puzzle: so there's a well-known function that maps the naturals N to N^2: it's called Cantor pairing: http://en.wikipedia.org/wiki/Pairing_function snip Hi Danny, It does generalize; a well known result of set theory has it that the Cartesian product of finitely many countable sets is itself countable (where countable means either finite or infinite but able to be mapped 1:1 to the natural numbers). Here's a hand-wavy proof sketch that assumes we've already got the map N - N^2: snip me blathering wrongly Hi Danny and all, What I said was not right. (I cannot now see how I thought it was.) Apologies. For an actual proof: http://planetmath.org/thecartesianproductofafinitenumberofcountablesetsiscountable. Best, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Cantor pairing in three dimensions?
On 23 December 2013 13:32, Danny Yoo d...@hashcollision.org wrote: I've got a puzzle: so there's a well-known function that maps the naturals N to N^2: it's called Cantor pairing: http://en.wikipedia.org/wiki/Pairing_function It's one of those mind-blowing things that I love. I ran across it a few years ago in a thread on Python-tutor a few years back: https://mail.python.org/pipermail/tutor/2001-April/004888.html Recently, the topic came up again for me, but in an expanded context: https://plus.google.com/117784658632980303930/posts/4SMcjm2p9vv So here's the question: is there an analogy of the Cantor pairing function that maps N to N^3? Hi Danny, It does generalize; a well known result of set theory has it that the Cartesian product of finitely many countable sets is itself countable (where countable means either finite or infinite but able to be mapped 1:1 to the natural numbers). Here's a hand-wavy proof sketch that assumes we've already got the map N - N^2: Given a map from N - N^m we can easily create a new map N - N^(m+1): replicate the grid from http://en.wikipedia.org/wiki/File:Pairing_natural.svg (the diagram in the wiki page that you linked to), with the natural numbers along the x-axis replaced by the members of N^m. Now, follow the same procedure that was used to demonstrate the existence of the map N - N^2. The resulting function is a map N - N^(m + 1), as desired. Best, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] [OT] Replies go to individuals, not the list?
On Aug 20, 2013 3:04 PM, Andy McKenzie amckenz...@gmail.com wrote: On Tue, Aug 20, 2013 at 2:53 PM, Alan Gauld alan.ga...@btinternet.com wrote: On 20/08/13 13:15, Andy McKenzie wrote: Yep. Someone decided it didn't make sense for reply to go to the list that sent the message Lists never send messages. People do. So reply goes to the *person* who sent the message. snip The problem is, as far as I'm concerned the message came from the list. Needing to go to the dropdown and select Reply to all is just one extra movement, and it's one I have to make every single time I reply. In all honesty, I can't think of a single time that I've wanted to reply to just the original sender: that's the point of a mailing list, to have conversations on it. I've occasionally been prompted to remember that I wanted to ask an individual something specific off-list, but it's never been a direct response to what was posted ON the list. snip It's basically a practicality thing for me. On a list where the vast majority of replies went to the original sender, I'd agree with you. For something like this, it's just making me do extra work without providing me with an extra benefit. Hi all, Alan's argument seems compelling, but is principled, thus perhaps vulnerable to a `practicality beats purity' response. What tips me against reply to munging is the principle of least damage, itself eminently practical. Imagine the non-actual possible world where this list reply munges and in which I wished to write Andy directly to cast aspersions on Alan's character and ancestry out of a misguided belief that reply to munging is right. I hit reply and shortly afterwards realize that I am missing toes. In the actual world, I might have accidentally sent this solely to Andy out of inattention. Irksome, but I still have all 7 of my toes. Powerful software often can and ought allow one to shoot oneself in the foot. It ought not however be designed so that in one context, doing what is safe and normal in another context surprisingly points a firearm at your feet without the accompaniment of klaxons and lights. (And even then …) Best, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Clear screen questions
On 5 May 2013 22:10, boB Stepp robertvst...@gmail.com wrote: On Sun, May 5, 2013 at 7:54 PM, Steven D'Aprano st...@pearwood.info wrote: snip So my main question is there a truly clean, cross-platform solution to the clear screen dilemma? If my online searching is accurate, then the answer appears to be no, unless one wants to print many blank lines. Your googling is accurate. There is no clean, cross-platform solution, not even for the main three (Linux/Unix, Windows, Mac), let alone minority and legacy platforms, other implementations, etc. So it appears that the only way to cover the various possibilities is to query for the platform being used and then apply the correct statement for that platform. And it still would not work for the point noted above. Could be a lot of effort for little gain! Try: def pragmatic_as_if_clear(): print '\n' * 100 which isn't too far off of what clear does in bash. A second question is that one person had as the answer to use: os.system( [ 'clear', 'cls' ][ os.name == 'nt' ] ) I don't understand this syntax. The writer said that if one understands what this is doing, then the method is more generally useful. Would someone explain how this works? And hopefully it will become apparent to me how this is more generally useful? snip terms when I saw the first pair of brackets, so it did not occur to me to see the second set of brackets as indexing. boB Steven explained it. I'd point out that wiser snake charmers than I discouraged me (some on this list) from using it from the position that it was too clever. I've done so from time to time anyway; there is a momentary jolt when reading the code months later. HTH, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Clear screen questions
On 5 May 2013 23:12, Steven D'Aprano st...@pearwood.info wrote: On 06/05/13 12:37, Brian van den Broek wrote: snip Try: def pragmatic_as_if_clear(): print '\n' * 100 which isn't too far off of what clear does in bash. Not in the version of bash I am using in an xterm window. (To be precise, Konsole under KDE 3.) If I start a bash session, and then do something large like print a file listing, the prompt ends up right at the bottom of the screen. If I then call clear, the visible area of the screen is cleared, the prompt ends up at the top of the screen, but if I scroll back using the scroll bar, I can see the previous output immediately before the clear command, without 100 blank lines separating them. terminator 0.93 under openbox 3.5 appears to fill a terminal window height with blank lines. That isn't a hard coded value as above, but that's why I put in the weasel words. Since those words are there, I'll press them into service to cover the further inaccuracy you point out :-) A second question is that one person had as the answer to use: os.system( [ 'clear', 'cls' ][ os.name == 'nt' ] ) I don't understand this syntax. The writer said that if one understands what this is doing, then the method is more generally useful. Would someone explain how this works? And hopefully it will become apparent to me how this is more generally useful? snip terms when I saw the first pair of brackets, so it did not occur to me to see the second set of brackets as indexing. boB Steven explained it. I'd point out that wiser snake charmers than I discouraged me (some on this list) from using it from the position that it was too clever. I've done so from time to time anyway; there is a momentary jolt when reading the code months later. I don't know who they were, I certainly hope they didn't include me. Not so far as I recollect, but it is nearing a decade ago, now. I'll leave my fuzzy memories where they are. FWIW, as indicated, that's a bit of advice I didn't always follow. Best, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] creating dictionary from a list
On 12 Apr 2013 21:25, Steven Dapos;Aprano st...@pearwood.info wrote: Also, you might find it easier to process the list if you strip out empty items. There are two simple ways to do it: lst = [x for x in list if x != ''] # or lst = filter(None, lst) Hi all, For the first, I would use lst = [x for x in list if x] instead. Best, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Additional help
On 10 February 2013 15:29, Ghadir Ghasemi ghasemm...@leedslearning.net wrote: Hi guys, I wondered if you knew what I could add to this code so that when the user enters 1 from the menu and then doesn't enter a valid binary number the program should ask them over and over again until valid binary number is entered. here is the code: snip while True: show_menu() choice = input(please enter an option: ) if choice == '1': binary = input(Please enter a binary number: ) denary = 0 place_value = 1 for i in binary [::-1]: denary += place_value * int(i) place_value *= 2 print(The result is,denary) snip elif choice == '3': break Hi Ghadir, over and over again until suggests a while loop. So, you need something like the pseudo-code: while True: binary = input(Please enter a binary number: ) if isgood(binary): pass # do stuff then break else: pass #remind user of constraints before they are prompted again (This assumes you've an isgood function that will return a boolean as the user input is acceptable. That's not necessarily the best way, but it makes for easy pseduo-code and doesn't do the work for you ;-) Last, a better subject line is a good idea. Pretty much every post asking for help from someone who's posted before could have your subject line. Best, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] using 'and ' and 'or' with integers
On 9 January 2013 01:56, ken brockman krush1...@yahoo.com wrote: I was looking through some lab material from a computer course offered at UC Berkeley and came across some examples in the form of questions on a test about python. 1 and 2 and 3 answer 3 I've goggled it till i was red in the fingers, but to no avail.. Could someone be kind enuff to direct me to some docs that explain this?? I've no clue what the hell is going on here.. Thanks much for any help you may supply. Ken, I don't have a link, but I'll take a stab. Any non-zero integer evaluates to True: if 42: print ! ! Python's boolean operators use short-circuit evaluation---they return a value as soon as they have seen enough to know what truth-value the compound evaluates to. And, the value they return isn't always True or False. Rather, they return the object in virtue of which they had seen enough to know whether the evaluated value is True or False: True or 4 True 4 or True 4 Since 4 evaluates as True, and `something True or anything at all' will evaluate to True, in the second case 4 is returned. Likewise, in your case: 1 and 2 and 3 3 (1 and 2) and 3 3 1 and (2 and 3) 3 (I put the two bracketting ones in as I cannot recall if python associates to the left or to the right. I'm pretty sure left, but it doesn't matter here.) Consider the last version. Since 1 evals as True, python has to look at the left conjunct. 2 does, too, so it has to look at 3. Since 3 does, and python now knows the whole evals as True, it returns 3. HTH, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] writing effective unittests
On 4 January 2013 03:34, Alan Gauld alan.ga...@btinternet.com wrote: On 04/01/13 07:10, Brian van den Broek wrote: ... confirm that the code works as intended when written, but that it continues to work several moths later moths? They'll be the bugs I guess? Sorry I couldn't resist :-) :-) I shouldn't like to meet the man who could. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] writing effective unittests
On 3 January 2013 14:46, Luke Thomas Mergner lmerg...@gmail.com wrote: * Albert-Jan Roskam fo...@yahoo.com wrote: Hi, I am trying to learn a bit of test-driven programming using unittests and nosetests. I am having trouble finding resources that explain how to write effective tests. I am not a programmer or a student, so I do not have access to snip To partially answer my own question, let me tell you what I've learned in the last 48 hours. It is easy to learn that unittest is the standard testing module in Python 2.6, that it is backported, that it is being improved in Python 3 with new tools. There are a few PyCon videos that discuss this evolution. It is also easy to learn that unittest is based off of prior library for Java (JUnit) and SmallTalk. It is fairly easy to find an introduction to the syntax of writing a test: snip And there are a few videos available that walk through how to put this together into a test suite. (I've included what I found below, so that this email will have some value to others.) What am I missing? The biggest problem is that no one is explaining the rationale behind testing. The trivial examples compare integers: 2 == 2. At first glance this seems pointless. I had assumed that tests would attempt to confuse my functions and teach me how to write more robust code. But I *think* now that tests are a way to determine if new code has changed old behaviors. Testing 2 == 2 is trivial, but if the function starts returning 3 in a few months, it would be helpful to know right away. In general, though, I'm finding it difficult to conceptualize what my tests should be doing, testing, and telling me about my code. Hi Luke, First, I should like to commend your post; collecting together the results of your research and posting it is a valuable thing to do. While I agree with Steven that you'd be better off not taking the list as a digest, for me at least, the mild irritation that digest use imposes is small compared to the goodwill the effort shown produces. Second, I don't test nearly as much as I ought. So, read with a grain of salt :-) Now, for the meat. A key idea that was implicit in Steven's first reply might be better made explicit. When testing, you want to look for odd or edge cases where things might break and embed tests that will let you know if they do. What counts as an edge or odd case is obviously context dependent. But, if dealing with an arithmetical function of one input, you'd generally want tests for at least 0, 1, -1, some large positive, some large negative, and small and large positive and negative non-integer rational numbers. If writing against 2.x, you'd also want an integer large enough to be a long rather than an int, etc. If testing a function that takes one string, you'd want tests for at least the empty string, a string consisting solely of whitespace, a single character string, a string with odd whitespacing that you wouldn ' t expect, strings in mixed case, ones with punctuation, etc. Another principle that I use to generate tests: while writing code, every time I find myself considering some possibility and thinking But, that's impossible! I try to put in a test to ensure that the impossible actually is. http://www.youtube.com/watch%3Fv%3DD58LpHBnvsI I didn't try to find the context, but testing 2 == 2 does seem a bit pointless. However, a similar sort of test might be worthwhile. Consider: class A(object): def __eq__(self, other): return False a=A() a==a False Now, one might think: But that's such a stupid bug. I'd never do that. If so tempted, go watch the link above :-) In seriousness, the way that sort of test will help isn't so much to confirm that the code works as intended when written, but that it continues to work several moths later when you've forgotten most of it and need to tweak just one thing that couldn't possibly affect other parts of the code. HTH, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] still confused about for loops
On 19 December 2012 01:19, Brandon Merritt merrit...@gmail.com wrote: Sorry, I am just so confused and aggravated as to why this won't work - why doesn't it print out the whole list? : number = raw_input('Enter a 7-unit number: ') for i in number: count = [] count.append(i) print count Enter a 7-unit number: 78953298 ['8'] -- Brandon Merritt (707) 481-1744 Brandon, Others have pointed out the problem here and in your counter thread. I have a bit of meta-advice that will help you to resolve these sorts of problems on your own. When confronted by a small chunk of code that is not behaving as you expect, it can help to grab a pen and paper and interpret the code by hand, going through it and updating the various data values as you run through the program step by step. Often, this will force you to see the point at which your mental model of what you have written diverges from what you have actually written. Less work, and often sufficient to expose the problem is to put in some print statements. Had you tried: for i in number: count = [] count.append(i) print count I suspect the problem would have become much more clear. If I am doing print statement debugging where I've multiple print statements exposing the same data structure, I will often tag them like so for i in number: print count, 11 count = [] count.append(i) print count, That helps figure out just where each printed instance of count came from. In the case at hand, this version would almost certainly have sorted you out; the first print will fail with a NameError, and this might have suggested to you that you have to define count before the loop. HTH, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Fwd: Re: Tutor Digest, Vol 106, Issue 31
Forwarding to the list what I sent privately. Stupid android UI. -- Forwarded message -- From: Brian van den Broek brian.van.den.br...@gmail.com Date: 14 Dec 2012 10:01 Subject: Re: [Tutor] Tutor Digest, Vol 106, Issue 31 To: Waters, Mike [ITSCA Non-JJ] mwat...@its.jnj.com On 14 Dec 2012 08:43, Waters, Mike [ITSCA Non-JJ] mwat...@its.jnj.com wrote: Hi Python tutor I have a question I believe I have posted before: when you have filled the page with text (commands,list etc) how do you clear the page to allow a clean page to continue on writing script? Thanks appreciate your help. Mike Mike, Please start a new thread for a new question rather than replying to the digest as you have done. This avoids a tonne of text irrelevant to your question (which I have removed) and affords you the easy to avail yourself of oportunity to give your inquiry a meaningful subject line. What do you mean by 'page'? What software are you working with? What OS? You've not given enough information. If you are thinking of an interactive prompt (though you don't seem to be) you can clear it with print \n * 80 # or some appropriate value If that doesn't help, please ask again with enough information about your context to allow those willing to help you to do so. Best, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] reverse diagonal
On 1 December 2012 10:40, richard kappler richkapp...@gmail.com wrote: I'm working through Mark Lutz's Python, reviewing the section on lists. I understand the list comprehension so far, but ran into a snag with the matrix. I've created the matrix M as follows: M = [[1, 2, 3[, [4, 5, 6], [7, 8, 9]] then ran through the various comprehension examples, including: diag = [M[i][i] for i in [0, 1, 2]] which, of course, gave me [1, 5, 9]. Then I tried creating revdiag, wanting to return [3, 5, 7], tried several different ways, never quite got what I was looking for, so I'm looking for guidance as I'm stuck on this idea. Here's the various attempts I made and the tracebacks: Richard, It is good you copy and pasted everything I snipped. But, you typed in the line defining M. Better to also copy paste that, as you typed it in wrong :-) Here's one way that assumes of M only that it is an n-by-n matrix: M = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] for i in reversed(range(len(M))): M[i][i] 9 5 1 Best, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] reverse diagonal
On 1 December 2012 20:12, Dave Angel d...@davea.name wrote: On 12/01/2012 11:28 AM, Brian van den Broek wrote: On 1 December 2012 10:40, richard kappler richkapp...@gmail.com wrote: I'm working through Mark Lutz's Python, reviewing the section on lists. I understand the list comprehension so far, but ran into a snag with the matrix. I've created the matrix M as follows: M = [[1, 2, 3[, [4, 5, 6], [7, 8, 9]] then ran through the various comprehension examples, including: diag = [M[i][i] for i in [0, 1, 2]] which, of course, gave me [1, 5, 9]. Then I tried creating revdiag, wanting to return [3, 5, 7], tried several different ways, never quite got what I was looking for, so I'm looking for snip my answer The only catch to that is it's not what he wants. He said he wants 3, 5, 7 That does seem true. I would suggest that calling the desired function `revdiag' invited the mistake I made. But, it is still on me for not reading closely enough. Best, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] run with default value if input not given
On 29 Oct 2012 02:30, Saad Javed sbja...@gmail.com wrote: I've come up with this: try: sys.argv[1] x = sys.argv[1] main(x) except IndexError: main(x) It works but seems hackish. Saad Saad, The first sys.argv is not needed. Notice how i have replied below the text i am quoting? That is the preference of most on the list. Best, Brian Vdb ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] urllib2.urlopen()
On 14 October 2012 02:15, Ray Jones crawlz...@gmail.com wrote: On 10/13/2012 07:50 PM, Steven D'Aprano wrote: snip If you can do `print e.info()`, then you can also do `info = e.info()` and inspect the info programmatically. One would expect that to be true. But when I do info = e.info(), info is httplib.HTTPMessage instance at 0x85bdd2c. When I print e.info(), I get the following: Content-Type: text/html Connection: close WWW-Authenticate: Basic realm= Content-Length: xx I can iterate through e.info() with a 'for' loop, but all I get as a result is: connection content-type www-authenticate content-length In other words, I get the headers but not the corresponding values. Ray, That smells rather like you are dealing with a dictionary. What happens if you try e.info()[connection] Best, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] urllib2.urlopen()
On 13 October 2012 19:44, Ray Jones crawlz...@gmail.com wrote: I am attempting to capture url headers and have my script make decisions based on the content of those headers. Here is what I am using in the relative portion of my script: try: urllib2.urlopen('http://myurl.org') except urllib2.HTTPError, e: In the case of authentication error, I can print e.info() and get all the relevant header information. But I don't want to print. I want the information from the instance available to use in my script. How do I accomplish that? Ray Hi Ray, (Sorry for the double message, Ray. I forgot to Reply to all.) I'm not very familiar with using urllib2 and I've never used it with a page which requires authentication. So, this might not sort you. But, perhaps it will get you started on how to figure it out for yourself: import urllib2 E = None try: urllib2.urlopen('http://fdghgdshdghmyurl.org') except urllib2.URLError, e: print 42 E = e 42 print dir(E) ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__getitem__', '__getslice__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__unicode__', '__weakref__', 'args', 'errno', 'filename', 'message', 'reason', 'strerror'] Best, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Through a glass, darkly: the datetime module
On 6 Oct 2012 22:40, Richard D. Moores rdmoo...@gmail.com wrote: snip I remain bewildered. Where did these strangely named things come from, strftime and strptime? I see that Hi Dick, These names carry over from well entrentched names from C. My guess is format time and print time are what they are supposed to suggest. from datetime import date date(2014, 2, 18).strftime(%A) 'Tuesday' gives me what I was after, but I need to understand it, and I understand very little of that section, 8.1.8. strftime() and strptime() Behavior. Take the first sentence in that section: date, datetime, and time objects all support a strftime(format) method, to create a string representing the time under the control of an explicit format string. Broadly speaking, d.strftime(fmt) acts like the time module’s time.strftime(fmt, d.timetuple()) although not all objects support a timetuple() method. Total gibberish. I feel like I've hit a brick wall. Where can I go to learn to understand it? I need some very basic, specific information. I expect your speaking from a place of frustration. I don't think this is the high point of the docs, but it isn't so bad as that. The strftime method of a datetime object uses a mechanism similar to string formatting to create strings displaying data from the datetime object. The docs for datetime don't provide the details, pointing instead to the docs for the very similar method of the time module. I'm on my phone so cannot easily show an example but if d is a datetime.datetime instance, d.strftime('%Y') will produce a string of d's year. Consult the time docs and see if you can get somewhere. If not, post again. Best, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] MAXIMUM LOOP LOGIC
On 4 Oct 2012 13:22, medusa magicwizards...@gmail.com wrote: Hello i got stuck with the last bit of my programming practice. snip Instead of printing off a number beside the email, i got another email and i dont know how to fix it. http://python.6.n6.nabble.com/file/n4990842/9.4_stuck.png Hi, Is your code long? If not, you should include it in your message. If it is, you should spend the time to trim it down to a short chunk that demonstrates the issue. While opinions are divided, many don't like code provided via a link in tutor posts. That cuts down on the number of people willing to look at your code. By the link you gave, it seems like you've posted a screenshot or other image. Even those who are happy to follow links to code are unlikely to be willing to retype what is shown in your image file. I'd suggest posting again, this time with code. Best, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Why difference between printing string typing its object reference at the prompt?
On 2 Oct 2012 23:17, boB Stepp robertvst...@gmail.com wrote: snip I am puzzled by the results of the following: x = Test x 'Test' print(x) Test I understand that 'Test' is the stored value in memory where the single quotes designate the value as being a string data type. So it makes sense to me that just typing the object reference for the string results in including the single quotes. But why does the print() strip the quotes off? Is just as simple as Hi boB, Under the covers, in python 2.x, print x causes the human readable string representation of x to be output by calling x.__str__. In an interactive prompt, typing x displays the python representation of x by calling x.__repr__. These can be the same or quite similar or quite different. When possible, __repr__ special methods ought to be defined so x equals eval(x.__repr__()). I believe, but don't warrant that in this regard python 3.x behave like 2.x (modulo the difference in the print syntax). Best, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] html checker
On 1 Oct 2012 15:28, Matthew Dalrymple computer_dud...@hotmail.com wrote: I don't need to hear how bad my programs are...either you are gonna help or your not...if Matthew, Bob didn't cuddle you and he may have been a bit more brusque than you'd have liked. However, his response to you was intended as help, it provided what would be help if you would read it as such, and it was worth much more than you paid for it. Your reply to that offer of help is not such as to encourage anyone else to give their time to you. I suggest you have a calm breath and reflect. You can surmount your start with this list, but for more than a few who answer here, you'll have to demonstrate you are more appreciative of the time and effort you are given before you get more. While you may not like this email I am fairly sure it contains a message you very much need to hear. Best, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Lotka-Volterra Model Simulation Questions
On 30 September 2012 04:37, Alan Gauld alan.ga...@btinternet.com wrote: off topic rant One of the things that makes math hard for people to grasp is its insistence on abstracting functions/values to single letter names etc. (especially when those names are in a foreign language/symbology, like Greek!) Of course, the abstraction is powerful in its own right because it can then be applied in multiple domains, but that abstraction is often the barrier to people understanding the principle. Those that are good at math are often really those who are good at abstraction. /off topic Hi Alan and all, While I think I see what you mean here, Alan, I cannot quite resist and, as this thread long since got hopelessly off-topic :-) I feel no need for restraint. To a first approximation, mathematics can reasonably be thought of as the science of abstraction. So, to say (with a hint of complaint) that those who are good at math are often those who are good at abstraction seems a bit like complaining that it is those with good spatial reasoning and a sense of direction that are good at navigation. While it is indeed possible for mathematical presentation to devolve into unhelpful abstraction (it is this that I suspect Alan intended to target), abstraction is of the essence to the enterprise; nothing that still counts as maths could be easily understood by those without the ability to think abstractly. Having posted twice in a half-hour, I resume my lurk-cloak. Best to all, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Lotka-Volterra Model Simulation Questions
On 1 October 2012 19:30, Alan Gauld alan.ga...@btinternet.com wrote: translation for them, not just complain of their 'ignorance'. But that's now taking things way, way off topic!! :-) I think you meant ``way^2 off topic'' ;-) Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] HELP!
On 1 Oct 2012 19:58, Mark Rourke mark.rour...@gmail.com wrote: hello, I am a college student in my first year of computer programming, I was wondering if you could look at my code to see whats wrong with it. # Mark Rourke # Sept 29, 2012 # Write a program to calculate the sales tax at the rate of 4% and 2% respectively # Thereafter compute the total sales tax (sum of the state tax and the county tax) # and the total purchase amount (sum of the purchase amount and the total sales tax). snip SALES_TAX = 0.4 COUNTY_TAX = 0.02 snip purchaseAmount = input(Please input the Purchase Amount: $) #Calculate the State Sales Tax, County Sales Tax, Total Sales Tax, Total Purchase Amount purchaseAmount = int(purchaseAmount) stateSalesTax = int(purchaseAmount * SALES_TAX) snip Hi Mark, c smith is certainly right to suggest that you ought to specify a bit more about what the symptoms are that you would like help diagnosing. That said, what should be the result if an item with a sticker price of 1.35 is purchased? Perhaps thinking about that and comparing the following will help: IDLE 2.6.6 user_input = 1.35 purchaseAmount = int(user_input) Traceback (most recent call last): File pyshell#1, line 1, in module purchaseAmount = int(user_input) ValueError: invalid literal for int() with base 10: '1.35' user_input = float(1.35) purchaseAmount = int(user_input) purchaseAmount 1 Best, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] running more than one python program at the same time
On 28 Aug 2012 18:33, Benjamin Fishbein bfishbei...@gmail.com wrote: Hello, I wrote a program that I want to have running 24/7. But the problem is that I also want to write and run other programs. I'm using Idle and it won't let me run more than one script at a time. Do you know if there's a way to do this? Or do I need to buy a second computer? Thanks, Ben Hi Ben, Idle may be useful for developing with (provided you aren't making an app with tkinter) but isn't always the best choice for running one. Do you know how to run python from a command prompt? (If not, post back to the list being sure to tell us your OS and I or someone else will help you.) If you run you 24/7 program that way, idle will be free for you to work. There are other ways to get your program to run in the background, but again these are OS-dependant. Best, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to print something just after 3 attempts?
On 17 Jul 2012 12:39, Mark Lawrence breamore...@yahoo.co.uk wrote: On 17/07/2012 16:28, Paul McNally wrote: snip enough context to perhaps have lost attributions I was able to get it working like this... password = foobar attempt = 0 while (password != unicorn) and (attempt = 3): Please we're talking Python here not C so strip out those unneeded parenthesis. Not so sure I agree. Python doesn't need them, but I often find code easier to parse when the scope of binary operators is made clear via parens. The precedence order of python is just one more thing to recall (and is fighting for space in my head with precedence orders for a bunch of formal languages). A bit of extra typing can save a second or cognitive lag each time the line is read. Best, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] str object is not callable
On 10 Jul 2012 11:31, Chris Hare ch...@labr.net wrote: This piece of code works: Big-Mac:Classes chare$ more tmp.py import re snip return not bool(search(string)) snip However, when I use the EXACT same code in the context of the larger code, I get the error return not bool(search(strg)) In addition to the comments about likely shaddowing, contrary to what you say, those two lines are not the same. Either you retyped instead of copy pasting (don't do that), or you are not running the code you think you are. Best, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Meaningless
On 27 May 2012 20:52, Dave Angel d...@davea.name wrote: On 05/27/2012 01:03 PM, Kimberly McManus wrote: help Sure. Head for the nearest exit, stopping before each door to make sure it's not hot before opening it. Hi Kimberly, While I share Dave's sadness at the general decline of list conduct (not a problem special to this list), and got a chuckle out of his message, I suspect your message was an honest mistake rather than what Dave took it to be. Reading , via email, send a message with subject or body 'help' to tutor-requ...@python.org and following it with a bit more care should sort you out. HTH, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] [OT] Re: Optimally configuring Emacs for W7-64bit and Python
On 23 May 2012 05:17, boB Stepp robertvst...@gmail.com wrote: but I will not be able to provide much (any?) help in the immediate future. (If emacs seems like you will stick to it, do have a look at orgmode.) Brian, does org-mode amount to a personal information manager? What are the things you especially like about it? Cheers! boB Hi boB, Org-mode is a lot of things. It is an outliner, a PIM, a brain-dump, a blog engine, a website generator, a literate programming tool, it embeds a simple DB and a featurefull spreadsheet, etc. I expect it shall soon achieve sentience. I like it because it is a plain text PIM that allows me to arrange my data as I want it, to quickly and flexibly capture it, and because it lets me employ my emacs-fu on my digital brain. I'd be happy to answer any further questions you might have. But, 1) I won't be prompt due to travel, and 2) if you write about org-mode, let us go off-list as we've strayed from tutor's purpose. Best, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Optimally configuring Emacs for W7-64bit and Python
On 22 May 2012 06:58, boB Stepp robertvst...@gmail.com wrote: Many thanks for all of the helpful input to my original questions. The deciding factors came down to the fact that GNU Emacs, vintage year 2001, is available on the Sun Blade at work, I already own the book Learning GNU Emacs and it would be nice to have my fingers trained the same way for both work and home study. What is the best way for me to get my W7-64bit laptop configured for Python programming? My consultations with the Google oracle have yielded inconclusive results this evening, though I confess I am quite tired, so I may be missing the obvious. boB, Having been the emacs advocate, I feel some obligation to try to help. However, 1) my last Windows use is a dim memory, and 2) I am just now embarking on a period of travel and uncertain connectivity. So, apologies, but I will not be able to provide much (any?) help in the immediate future. (If emacs seems like you will stick to it, do have a look at orgmode.) Best and good luck, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] [OT] Re: While learning Py: To IDE or not to IDE?
On 21 May 2012 03:39, Steven Dapos;Aprano st...@pearwood.info wrote: boB Stepp wrote: snip now on learning an IDE if it will save me time overall. IF it would be beneficial now to learn an IDE, then it begs the question No it doesn't. It RAISES the question -- begging the question means to *assume the answer in the question*, and it is a logical fallacy. Notepad is the best editor, because no other editor is as good as Notepad is begging the question. Steven, I am a philospher of logic and mathematics. Everytime I encounter 'begs the question' used in the way which you here resist, a little piece inside me dies. Thanks for fighting the good fight! However, as I hear this on the BBC and CBC Radio, and read it in periodicals I think ought be edited by those who know better, I confess I feel the worthy battle is lost. As W.V.O. Quine said: We cannot stem the tide of linguistic change, but we can drag our feet. Best, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] While learning Py: To IDE or not to IDE?
On 21 May 2012 01:19, boB Stepp robertvst...@gmail.com wrote: On Sun, May 20, 2012 at 4:44 PM, Brian van den Broek brian.van.den.br...@gmail.com wrote: snip With you polyglot agenda, I would say you would be much better off to learn a powerful multipurpose editor well than to try to find the best of breed of each class of special purpose tool. There are three basic choice: emacs, vi or vim, and everything else. There is widespread, though not uniform, consensus that The One True Editor is one of emacs and vi. After that, the rest is flamewars. I am an emacist, myself. But some of my best friends are vimists. I gather, then, that you feel my time would be well-spent now to learn a good editor/IDE now, rather than continue with IDLE? snip But since you brought it up, I'll ask a somewhat more general question: Why do you prefer an editor instead of a graphical IDE? I have limited experience with Emacs as I finally installed it on my PC at work to avoid having Windows-style end-of-line characters messing up my scripts which were to run in an UNIX environment. I can see potential there, but as my future projects get larger and more involved will it be able to do everything I would want it to do? Would I find myself wanting a full-fledged IDE? I don't have enough technical knowledge to answer these questions right now. Your thoughts? Hi boB, If IDLE is working well for you, there's a good reason to stick with it. I meant to address whether you ought build a stable of purpose-specific IDEs or learn one editor to rule them all. The advantage of emacs, as I see it, is that it provides general purpose tools of high power for text-wrangling and the (non-trivial) time you have to invest to learn to exploit that power yields fruit whenever you are editing text. Emacs key bindings turn on all over the place, too; bash shell supports a bunch, for instance. It might be that editor plus language would be frustrating to try to learn all at once, though. Best, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] While learning Py: To IDE or not to IDE?
On 20 May 2012 23:04, boB Stepp robertvst...@gmail.com wrote: snip Goals: Learn Python. While learning Python, learn all of the good C.Sc. stuff that I should have learned the first go-around, Learn Java and C/C++. Reevaluate. snip Finally to the question: With the stated goals above, would it be better to invest time now at the front-end in learning a powerful IDE, or am I better served, while learning Python, to stick with IDLE and the shell and worry about an IDE later? I am willing to invest time now on learning an IDE if it will save me time overall. IF it would be beneficial now to learn an IDE, then it begs the question as to whether I should search for the best IDE for Python, then later the best one for Java, etc., or, instead, look for the best one that can handle all of the languages I plan to learn and use. Thanks for any guidance you can provide! -- Cheers! boB Hi boB, These are close to religious questions :-) With you polyglot agenda, I would say you would be much better off to learn a powerful multipurpose editor well than to try to find the best of breed of each class of special purpose tool. There are three basic choice: emacs, vi or vim, and everything else. There is widespread, though not uniform, consensus that The One True Editor is one of emacs and vi. After that, the rest is flamewars. I am an emacist, myself. But some of my best friends are vimists. Good luck, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to read blog posts in python
On 17 May 2012 16:31, Surya K sur...@live.com wrote: Hi, I want to write a python code which read blog's RSS/ Atom feeds and gives us the all post's content of blog... I am currently trying to use FeedParser (Universal Feed Parser). I am able to get all post's titles and URL's but not a content.. I tried to use certain functions mentioned in documentation but couldn't really understand how to do.. Can anyone help me how to do that? (I snip Hi, You are much more likely to get help if you include the code you tried. It's fine to say what I have isn't working; I've pasted it at the end of this message or the like. Also, with evidence of your attempt, those who know UFP (not me, I am afraid), will be better able to aim their efforts to help at your level. Best, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Sorting the Parts of a Dictionary into a List
On 8 May 2012 23:23, Jacob Bender benderjaco...@gmail.com wrote: Dear Tutors, My original email was this: Dear tutors, I'm trying to create a neural network program. Each neuron is in a dictionary and each of its connections and their strengths are in a nested dictionary. So {0:{1:4, 2:5}}, 1:{0:6}, 2:{1:2}} would mean that neuron 0 is connected to neuron 1 with a strength of 4. And it also means that neuron 1 is connected to neuron 0 with a strength of 6. The problem is that I'm working on a function that is supposed to add the total strengths of each neuron. So, for example, neuron 0's connections have a total strength of 9 (4+5). The other problem is getting all of the total strengths and ordering the neurons into a list. So, from the example, the list would be from [0,1,2] because zero has the greatest total strength of 9, then 1 with a total strength of 6 and so on. I've been working on this problem for at least 2 hours now and still haven't found anything close to a solution. And here's my source code: snip The total function works when it returns the strength of a neuron, but I don't think the sorted function is the best because, with its current configuration, it returns a type error. I have been doing python for several years now. I don't know EVERYTHING there is to know, but I am able to do most tasks without error. Please help me get the neurons into an order in a list as described in my original email. Also, I do thank you for your original replies! -- Thank you, Jacob Hi Jacob, While I agree with those who suggested you send some code, I didn't look at it too closely. Only close enough to be fairly sure I wasn't doing everything for you by suggesting you consider the following approach :-) neurons = {0:{1:4, 2:5}, 1:{0:6, 2:1}, 2:{0:3, 1:1}} weights = {} for neuron in neurons: total_weight = 0 conections = neurons[neuron] for conection in conections: total_weight += conections[conection] weights[neuron] = total_weight for neuron in sorted(weights): print neuron, weights[neuron] 0 9 1 7 2 4 HTH, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] which gets called
On 6 April 2012 15:54, John Fabiani jo...@jfcomputer.com wrote: Hi, I want to create a class that inherits two other classes. class NewClass( A,B) But both A and B contain a method with the same name (onKeyDown). If my NewClass does not contain something to override the methods which one would be called if myinstance = NewClass() myinstance.onKeyDown() Hi John, Easy enough to sort out with a little experiment: class A(object): def doit(self): print A class B(object): def doit(self): print B class C(A,B): def __init__(self): self.doit() c=C() A Second to insure the right one is called is it possible to do the following NewClass(object): def onKeyDown(self, event): b.onKeyDown(event) Perhaps this helps, some: class D(A,B): def __init__(self): self.doit() def doit(self): print D super(D, self).doit() d=D() D A class E(A,B): def __init__(self): B.doit(self) e=E() B Best, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How is the return statement working in this function?
On 6 Apr 2012 02:43, Greg Christian glchrist...@comcast.net wrote: I am just wondering if anyone can explain how the return statement in this function is working (the code is from activestate.com)? Where does x come from – it is not initialized anywhere else and then just appears in the return statement. Any help would be appreciated. def primes(n): Prime number generator up to n - (generates a list) ## {{{ http://code.activestate.com/recipes/366178/ (r5) if n == 2: return [2] elif n 2: return [] s = range(3, n + 1, 2) snip return [2]+[x for x in s if x] Hi Greg, That it appears is a return isn't relevant. The bit '[x for x in s if x]' is a list comprehension. They build lists in an economical way. This one is equivalent to: result = [] for x in s: if x: result.append(x) Informally, you can think of the 'for x' as working kind of like for every student when a teacher reminds him or herself to praise students by repeating softly for every student in my class praise that student. HTH, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Any book to study Python
On 19 Mar 2012 11:42, Yan, Xianming xianming@intercallapac.com wrote: I'm following http://docs.python.org/tutorial/interpreter.html to type in the first script into python. According to the link, I typed below: the_world_is_flat = 1 if the_world_is_flat: ... print Be careful not to fall off! Then I get below output: File stdin, line1 Print dd ^ IndentationError:expected an indented block Xianming, I see you solved your problem; I am glad. But, a comment for future messages: Be sure to copy and paste (as in, do not retype) your code and any output that *that* code produces. The code you show cannot have produced the output you show. If you retype or mix and match code and output, you make it harder to help! Best wishes, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] seeing the results of a python program in windows7
On 15 Mar 2012 04:14, bob gailer bgai...@gmail.com wrote: On 3/14/2012 12:12 PM, Tamar Osher wrote: I can run a python program in Notepad++, but what happens is that the black box flashes and disappears immediately, so that I never see the results. How can I style it so that the results of the program stay on the computer screen, for me to see? Do this: try: # your program goes here finally: raw_input(Press any key) # if you are running Python 3 replace raw_input with input Adding the try-finally construct ensures that any exception in your code will be visible. Alternatively, invoke python to run your program at the prompt with the interactive switch: python -i myscript.py Best, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Cannot run python programs on my windows7 computer
On 14 Mar 2012 02:56, Tamar Osher emeraldoff...@hotmail.com wrote: Hello. Is there someone who can tutor me about how to run Python files on my windows7 computer? I have IDLE (the white box, the Python shell). I have the command prompt (the black box). And I also have Notepad++ on my computer. I have a total of 3 ways of trying to run my Python programs. I have tried and tried. The books Hi Tamar, I remember that I found it a bit non-obvious to get this working when I started with python, too. Unfortunately, that is nearing a decade ago and I don't recall what the bump was. If you can get idle going, you can run programs. On the File menu, New opens a new editor window where you can type a program and Open opens an extant file. It also provide a different menu with Run. If that doesn't run your program, something is messed up with your install. Idle isn't always the best choice; you'll want to be able to run from a command shell (the black box), too. What happens when you type 'python' there? If you get a python prompt, save a file mytest.py that has the sole line raw_input(42) somewhere and try 'python full\path\to\mytest.py'. If you don't get a python prompt on typing 'python' type 'path' and report your result. I don't have a windows box, so I am going on memory and might have got things wrong. As for top posting: notice how my text follows yours? This means a reader of this email hits the context before my content. If you are on a number of lists and watching a number of threads, top posted emails are annoying as you have to scroll down to read the context then up to read the content. Whether that makes sense to you or not, the community from which you seek help strongly prefers you not top post, so don't. Best, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] return integer from function
On 22 February 2012 12:57, David Craig dcdavem...@gmail.com wrote: Hi, I have a function that calculates the distance between two points on a sphere. It works but I cant get it to return a float for use in another script. Anyone know how I do that?? snip code cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) + math.cos(phi1)*math.cos(phi2)) arc = math.acos( cos ) type(arc) arc = arc*6378.1 #print str(arc*6378.1)+' km' # Remember to multiply arc by the radius of the earth # in your favorite set of units to get length. return arc Hi David, I'm a bit puzzled. A few lines above the return, you have 'type(arc)'. Try replacing that with 'print type(arc)' and also include 'print type(arc)' immediately above your return. I think you will find that the code you posted does return a float. Best, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] string integers?
On 12 Feb 2012 15:28, William Stewart williamjstew...@rogers.com wrote: I am trying to get 2 string variables and 2 integer variables to be able to be multiplied can anyone tell me what I did wrong str1 = raw_input(Type in a String: ) str2 = raw_input(Type in a String: ) int1 = raw_input(Type in a integer variable: ) int2 = raw_input(Type in a integer variable: ) print str1 + str2 + int1 + int2 import math print str1, *, str2, *, int1, *int2 =, str1, * str2, * int1 * int 2 and it wont let me write int2 I know this may look stupid to most people but I am just new at this so dont laugh :) Hi, It is a bit unclear what you mean by it wont let me write int2. Try running this function and see if it helps: def test(): data = raw_input(give me an integer) print type(data) print a string * another Best, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] exercise with classes 2nd attempt
On 12 Feb 2012 05:23, Tonu Mikk tm...@umn.edu wrote: I am learning Python using the Learn Python the Hard Way book by Zed Shaw. I reached exercise 42 where we learn about Python classes. The exercise shows a game with one class that includes all the definitions for playing the game. For extra credit we are asked to create another version of this game where we use two classes - one for the room definitions and the other for the playing the game. May attempt at creating two classes is here http://codepad.org/963vUgSt . I get the following error which I have been un-able to resolve. Any suggestions are welcome. Traceback (most recent call last): File ex42_3.py, line 233, in module run() File ex42_3.py, line 231, in run room1.doIt() # plays the game File ex42_3.py, line 32, in doIt self.obj.play() # use object File ex42_3.py, line 20, in play room = getattr(self, next) AttributeError: 'Engine' object has no attribute 'central_corridor' Hi, Your code is longer than I feel like reading carefully. (Not a complaint; just cautioning you about how closely I looked.) Also, the line numbers of your code sample do not agree with those of your traceback. (That is a mild complaint; it makes it harder to help you.) Notice that you defined central_corridor as a method of Room. The last line of your traceback is (it seems) in Engine.play; the code there looks for central_corridor in Engine and doesn't find it. If that help, great. If not, try to trim down your code to a smaller version that exhibits the problem and post again, this time making sure the posted code and the code that generate the traceback are the same. Best, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] string integers?
On 12 February 2012 21:27, William Stewart williamjstew...@rogers.com wrote: thanks i tried the code and it doesnt make anydiffference what I need is it to multiply now I fixed the error message but how do I get the 2 numbers that the person enters to multiply --- On Sun, 2/12/12, Brian van den Broek brian.van.den.br...@gmail.com wrote: From: Brian van den Broek brian.van.den.br...@gmail.com Subject: Re: [Tutor] string integers? To: William Stewart williamjstew...@rogers.com Cc: tutor@python.org Date: Sunday, February 12, 2012, 8:53 AM On 12 Feb 2012 15:28, William Stewart williamjstew...@rogers.com wrote: I am trying to get 2 string variables and 2 integer variables to be able to be multiplied can anyone tell me what I did wrong str1 = raw_input(Type in a String: ) str2 = raw_input(Type in a String: ) int1 = raw_input(Type in a integer variable: ) int2 = raw_input(Type in a integer variable: ) print str1 + str2 + int1 + int2 import math print str1, *, str2, *, int1, *int2 =, str1, * str2, * int1 * int 2 and it wont let me write int2 I know this may look stupid to most people but I am just new at this so dont laugh :) Hi, It is a bit unclear what you mean by it wont let me write int2. Try running this function and see if it helps: def test(): data = raw_input(give me an integer) print type(data) print a string * another Best, Brian vdB Hi William and list, To the list: I have only recently reappeared here on the Tutor list, but years back, I learned a great deal from various patient people, some of whom are still here. (Grateful waves to those folk!) I feel fairly confident that the message below is still in the spirit and cultural norms of the list. However, if I am wrong in that, I would welcome any Tutor veterans calling me out, in public (preferred) or in private. To William: I have a few observations that, if you take them to heart, will help you make better use of the Tutor mailing list. They may seem picky, but I assure you that there are reasons behind each thing I say and following these observations will give you a much more rewarding experience with the list. 1) Please don't top post. It bothers geeks and as you want geeks to help you, even if that preference seems silly (it isn't), grit your teeth and do as those who you are asking to help you would prefer. ('Geek' is, of course, a term of praise.) 2) Please be sure to hit Reply-to-All in your mail client. If it lacks such a button, be sure to add a to:tutor@python.org. If you don't your response will go only to the person to whom you are replying. This is what happened to your response to me. If I'd lost the time, interest, or ability to reply to you, your message to me would never get you any further help. Sent to both me and to the list, you can get help from others even if help from me is not forthcoming for whatever reason. 3) Please put more effort in to asking your question in a clear manner. In all honesty, I have no idea what it is you hope thanks i tried the code and it doesnt make anydiffference what I need is it to multiply now I fixed the error message but how do I get the 2 numbers that the person enters to multiply to produce by way of further help. What code? What difference were you expecting? Different from what? What error message? I am quite sure I spent longer typing up my first message to you than you did typing your reply. You will generally find that people here will respond positively to effort you expend to make your question clear as it makes it easy for them to help you. If you are not willing to spend much effort, in general, people are not likely to spend more effort than you are. To help see the importance of including your code, your output or backtrace, and a clear statement of your expectations and intentions, consider what happened with your first message. I said It is a bit unclear what you mean by it wont let me write int2. I noticed a problem with your code and, as you'd not been clear about what problem you were having, I said something about that. I didn't read carefully enough to see the problems that others pointed out to you. (If you didn't care to clearly state your problem, I didn't care to work it out for you.) While your code did have multiple issues (that's fine; we were all beginners once), the way you asked it made it hard for me to focus on the issue you were having at the time. Another benefit of taking the time to compose a clear email with a clear statement of your problem (including a *copy and paste* of the smallest chunk of code that exhibits the problem, a description of the expected output, and a *copy and paste* of the output or generate traceback) is that very often, the process of generating such a message will help you solve your own problem. I cannot begin to guess how many times I've started writing a question to this or some other technical mailinglist or newsgroup only to find
Re: [Tutor] string integers?
On 13 February 2012 01:34, William Stewart williamjstew...@rogers.com wrote: this is the code I have str1 = raw_input(Type in a String: ) str2 = raw_input(Type in a String: ) int1 = raw_input(Type in a integer variable: ) int2 = raw_input(Type in a integer variable: ) print str1 + str2 + int1 + int2 import math int1 = int(raw_input()) print str1, print str2, print int1, *, int2 print = and it does not give me an error message when I run it, the program runs fine except its did not multiply the 2 integer variables i entered it looks like this Type in a String: hello Type in a String: hi Type in a integer variable: 4 Type in a integer variable: 5 hellohi45 This part is exactly what I want it to look like except I want it to multply the 2 numbers I inputed (4 5 in this example) Hi William, That is a much better starting point from which to get help. It looks to me as though you took the responses concerning form that I and other gave you seriously; I'm glad. (I sympathize about the difficulty to find time to ask well. It does, however, take less time in the long run than asking several rounds of quick to compose questions.) Steven D'Aprano has given you enough that you should be able to make progress and ask again if needed. I did, however, want to point out that in my first message to you, when I suggested a function for you to run, it was with an eye to helping you to discover the problem. Here's the function and the results of running it in idle: IDLE 2.6.6 def test(): data = raw_input(give me an integer) print type(data) print a string * another test() give me an integer42 type 'str' Traceback (most recent call last): File pyshell#1, line 1, in module test() File pyshell#0, line 4, in test print a string * another TypeError: can't multiply sequence by non-int of type 'str' (Here, 42 is my input.) You can see that the type of data (the value returned by the raw_input call) is str---a string. The TypeError is telling you that the code I gave tries to multiply by a string and that caused a TypeError as multiplication isn't an operation defined for strings as the right-hand multiplier. Steven's email shows you how to surmount that problem; you must use int() to turn the returned value of raw_input into an integer. Compare: def test2(): data = int(raw_input(give me an integer)) print type(data) print data * data test2() give me an integer4 type 'int' 16 of course, there are still things that can go wrong: test2() give me an integer3.1415 Traceback (most recent call last): File pyshell#7, line 1, in module test2() File pyshell#5, line 2, in test2 data = int(raw_input(give me an integer)) ValueError: invalid literal for int() with base 10: '3.1415' test2() give me an integerFourtyTwo Traceback (most recent call last): File pyshell#8, line 1, in module test2() File pyshell#5, line 2, in test2 data = int(raw_input(give me an integer)) ValueError: invalid literal for int() with base 10: 'FourtyTwo' In both cases, I entered some string that int() cannot turn into an integer. If you get the basic idea working for the case where the user enters sane values, we can talk about how to deal with such cases if need be. Best, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Learn Python The Hard Way, Ex19-3
On 12 Feb 2012 00:29, amt 0101...@gmail.com wrote: Hello! I'm currently stuck at the Extra Credit 3 from LPTHW. Link to the actual exercise: http://learnpythonthehardway.org/book/ex19.html The exercise: Write at least one more function of your own design, and run it 10 different ways. Code from the book: def cheese_and_crackers(cheese_count, boxes_of_crackers): print You have %d cheeses! % cheese_count print You have %d boxes of crackers! % boxes_of_crackers print Man that's enough for a party! print Get a blanket.\n print We can just give the function numbers directly: cheese_and_crackers(20, 30) I wrote a function similar to cheese_and_crackers and it works just fine but I can't figure out more ways of calling a function other than the ones presented in the code(with integers as arguments,variables as arguments, two integer additions as arguments and with arguments in the form of variable+integer). The author states that there are 10 different ways to run it.(in a comment he states that: You can run it a lot of different ways, far too many to enumerate.). So, what other ways are there aside the ones already presented in the above code? Hi, Subject to the same caveats as your other replies: How about for (cheesecount, crackercount) in [(3,5), (7,42)]: cheese_and_crackers(cheesecount, crackercount) Best, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to make def where arguments are either stated when called or entered via raw_input
On 9 Feb 2012 13:34, David Craig dcdavem...@gmail.com wrote: Hi, I'm trying to write a function that will either take arguments when the function is called, such as myFunc(x,y,z) or if the user does not enter any arguments, myFunc() the raw_input function will ask for them. But I dont know how to check how many arguments have been entered. My code is below. Anyone know how?? Thanks D def NoiseCorr(file1,file2,500,0.25,0.35): ### ### Check number of arguments ?? ### ### User inputs. if numArgs == 0: file1 = raw_input('Path to Station 1: ') file2 = raw_input('Path to Station 2: ') shift_length = raw_input('Length of Correlation: ') freqMin = raw_input('Min. Frequency: ') freqMax = raw_input('Max. Frequency: ') Hi David, From your description, it doesn't sound as though you do need the number of arguments. Are you familiar with keyword args and default values? I would do it like so: def myfunc(x=None): if x is None: x=raw_input(a_prompt) expanding the arg list as needed. This also allows for callers to specify only some of the values. HTH, Brian vdB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help with getting python to run from command prompt onWindows XP
Alan Gauld said unto the world at 14/01/09 07:34 PM: Brian van den Broek van...@gmail.com wrote icon for Idle launching as expected. When run from IDLE, `print sys.executable' yields `C:\\Python26\\pythonw.exe'. He reports that C:\Python26 contains both python.exe and pythonw.exe. I've had him add the text `;C:\Python26' (without quotes) to the end of his Path environment variable via the Control Panel|System Properties way of editing Environment variables. I've had him reboot afterwards. Get him to type SET env.txt at the DOS prompt that should list all environment variables into env.txt Get him to email that file to you and check what it says about PATH. After all of that, he reports that an attempt to run python from the command prompt produces a complaint that `` `python' is not recognized as an internal or external command, operable program or batch file.'' What happens if he types C:PROMPT C:\Python26\python.exe In other words uses the full path? Hi all, Thanks to all respondents for the input. Apologies for the delay in reply; there's a bit of a lag as I'm communicating with my friend by email, too. With the full path, python loads as expected. I'm awaiting the results of SET env.txt as per Alan's suggestion above. If that doesn't clear it up for me, I shall report back. Thanks again, Brian vdB ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help with getting python to run from command prompt onWindows XP
Brian van den Broek said unto the world at 15/01/09 11:27 AM: Alan Gauld said unto the world at 14/01/09 07:34 PM: Brian van den Broek van...@gmail.com wrote snip my account of Windows using friend unable to invoke python at DOS prompt and replies including Alan's suggestion to get a text file dump of environment variables. With the full path, python loads as expected. I'm awaiting the results of SET env.txt as per Alan's suggestion above. Never fails. Shortly after posting, I got an answer back from the friend I'm trying to help. The (recognized by me as) relevant bits of output are: Path=C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program Files\texlive\2008\bin\win32;C:\Python26 PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH There is no subsequent Path line that might be stomping on the line shown above. I'm surprised that it is `Path' rather than `PATH'. Does that matter? I'm pretty sure that my friend didn't change that, as once he got into the `Edit System Variable' dialog, he felt uncertain and sent me a screen shot before he effected any modifications; the screen shot shows `Path'. Last, the texlive entry is from an installation of latex that I guided him through right before we installed python. Invoking latex from the command line works as expected, so I conclude that the Path is not broken. If that doesn't clear it up for me, I shall report back. Didn't and did. Thanks and best, Brian ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help with getting python to run from command prompt onWindows XP
Kent Johnson said unto the world at 15/01/09 12:33 PM: On Thu, Jan 15, 2009 at 11:48 AM, Brian van den Broek br...@cc.umanitoba.ca wrote: The (recognized by me as) relevant bits of output are: Path=C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program Files\texlive\2008\bin\win32;C:\Python26 PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH There is no subsequent Path line that might be stomping on the line shown above. I'm surprised that it is `Path' rather than `PATH'. Does that matter? I don't think so, my PC has 'Path' also. I'm stumped... Kent Hi all, Thanks for the further replies. As consensus seems to be there's nothing obvious to explain the problem, it's either going to be that my (relatively unsophisticated about computers) friend and I had a miscommunication over email or there is something at play that I won't be able to discern remotely. I'll have him verify all steps again and then call `gremlins'. Thanks for the help, Brian vdB ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] help with getting python to run from command prompt on Windows XP
Hi all, I'm trying, via email, to help a friend set up python on his Windows XP computer. I've been strictly linux for some time now, and don't have a Windows machine on which to investigate. We've hit a problem, and I'd appreciate a push. He's got python 2.6.1 installed as evidenced by the Startbar program icon for Idle launching as expected. When run from IDLE, `print sys.executable' yields `C:\\Python26\\pythonw.exe'. He reports that C:\Python26 contains both python.exe and pythonw.exe. I've had him add the text `;C:\Python26' (without quotes) to the end of his Path environment variable via the Control Panel|System Properties way of editing Environment variables. I've had him reboot afterwards. After all of that, he reports that an attempt to run python from the command prompt produces a complaint that `` `python' is not recognized as an internal or external command, operable program or batch file.'' Can someone with Windows knowledge please tell me what I am missing? Am I wrong in recalling that from the command prompt on Windows, one wants python, rather than pythonw? (I seem to recollect that pythonw.exe is what you associate with .py files to prevent a double-click on a .py icon from producing the `DOS box flash' and *not* what one wants to use from the prompt itself.) Thanks and best, Brian vdB ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] help with getting python to run from command prompt on Windows XP
Hi all, I'm trying, via email, to help a friend set up python on his Windows XP computer. I've been strictly linux for some time now, and don't have a Windows machine on which to investigate. We've hit a problem, and I'd appreciate a push. He's got python 2.6.1 installed as evidenced by the Startbar program icon for Idle launching as expected. When run from IDLE, `print sys.executable' yields `C:\\Python26\\pythonw.exe'. He reports that C:\Python26 contains both python.exe and pythonw.exe. I've had him add the text `;C:\Python26' (without quotes) to the end of his Path environment variable via the Control Panel|System Properties way of editing Environment variables. I've had him reboot afterwards. After all of that, he reports that an attempt to run python from the command prompt produces a complaint that `` `python' is not recognized as an internal or external command, operable program or batch file.'' Can someone with Windows knowledge please tell me what I am missing? Am I wrong in recalling that from the command prompt on Windows, one wants python, rather than pythonw? (I seem to recollect that pythonw.exe is what you associate with .py files to prevent a double-click on a .py icon from producing the `DOS box flash' and *not* what one wants to use from the prompt itself.) Thanks and best, Brian vdB ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Key Error
Sara Johnson said unto the world upon 07/08/2007 01:34 AM: Sorry, this is probably too general a question, but I can't find any specific information on it. What exactly is a key error and how do I clear it? I entered something like this: abcd=h[key]['ABCD'] and when I run it I'm getting KeyError: 'ABCD' What does this mean? Thanks! Hi Sara, It means you've tried to access a data structure (most likely a dictionary) with a key that does not exist in that structure. Witness my_dict={42:Six times seven, 1: The loneliest number} my_dict[42] 'Six times seven' my_dict['42'] Traceback (most recent call last): File stdin, line 1, in module KeyError: '42' my_dict[17] Traceback (most recent call last): File stdin, line 1, in module KeyError: 17 It isn't a question of `clearing' it, but of tracking down the wrong assumption behind your code. It may be that you thought you were using a key you'd added before and were wrong (my_dict['42'] as opposed to my_dict[42] shows a common source of that). But, from your abcd=h[key]['ABCD'] I'm guessing that you've got the key-access syntax a bit wrong. Did you mean abcd = h['ABCD'] instead? HTH, Brian vdB ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Money matters
Terry said unto the world upon 06/28/2007 02:55 PM: I am going to need to be handling money calculations and was wondering about the float problem in my calculations. Should I simply run the results of all calculations through something like this: from __future__ import division ... ... s=(int(round(s, 2)*100))/100 Or should I be using Decimal on all money calculations? Or, is there another more preferred approach? Hi Terry, I'd say definitely use Decimal. Money calculations were a primary use case for the Decimal module. (Though a bit more needs to be done to get the right decimal precision. See http://www.python.org/dev/peps/pep-0327/.) Best, Brian vdB ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] subprocess and launching an editor
Hi all, I want to have a script launch an editor open to a particular file and wait until that editor has closed before continuing. The aim is to allow the user to make edits to the file, have to script know that the edits are completed, and then make use of the newly saved file contents. gedit is the default text editor on my ubuntu feisty system, so in the first instance, I've tried to do this with gedit. The subprocess.call: subprocess.call(gedit somefilename, shell=True) works just fine *provided* that no instance of gedit is running when I invoke .call. However, if there is a gedit window up and running (there usually is on my system ;-), the .call immediately returns exit status 0: subprocess.Popen(ps -e|grep gedit, shell=True) subprocess.Popen object at 0xb7d06b4c 26066 pts/200:00:01 gedit subprocess.call(gedit somefilename, shell=True) 0 # The exit code is produced instantaneously Interestingly, it works just fine if I use emacs in place of gedit, irrespective of whether emacs was running before the subprocess.call invocation or not. Is there any way to get it to work with gedit as it is with emacs? I am largely ignorant of the family of modules which subprocess was designed to replace, and also of the details of processes on linux. (In particular, I've no clue why gedit and emacs behave differently in this respect.) Thanks and best, Brian vdB ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] More trouble debugging my game of life program
Matt Smith said unto the world upon 06/03/2007 04:12 PM: Hi, I've got my program working correctly (or so it seems) with my original data file (r-pentomino.txt - attached) but when I run it with a larger (30*30) file (big-r-pentomino - also attached) in an attempt to make it work with out so many edge effects it returns the following error message: Traceback (most recent call last): File Python/game_of_life/life.py, line 75, in module curses.wrapper(main) File curses/wrapper.py, line 44, in wrapper File Python/game_of_life/life.py, line 60, in main draw_board(matrix, stdscr, generation) File Python/game_of_life/life.py, line 28, in draw_board stdscr.addch(y + 1, x + 1, ' ') _curses.error: addch() returned ERR I thought I had designed the program to work with any text file as long as the lines are all the same length so I cannot understand why I get this error message. When I read through the code I cannot see a reason why the program should work for one size file and not another. The part of the program that is failing is just drawing a space character at a particular location on the screen. Here is the listing of the program that I have also attached: snip Hi Matt and all, I'm not familiar with curses, and I didn't look too closely at your code. But, if I understand you aright, things work fine with a 15x15 matrix, and go sideways with the 30x30. The first thing I would do to try to track down the problem would be to try 15x30 and 30x15 matrices. If you have two cases where one behaves as expected and one does not, it is usually very useful to try to match the two cases as closely as possible as an aid to pinpointing the problem. HTH, Brian vdB ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Design Question
[EMAIL PROTECTED] said unto the world upon 06/01/2007 10:46 AM: I think I may have sent an incomplete version of this question a moment ago (sorry). Here is the complete question: I'm designing something along the lines of a flash card program. It's mostly just an exercise in learning Python, but I'd like it to be at least marginally usable when I'm done. So I'm looking for comments/suggestions on the key pieces of the design: the questions and the flash card deck: Psudo-code of current design: class Deck(): Provides managment and informational functions about a set of questions to be asked methods incldue: __init__(questions) -- takes a list of question and creates a new deck with these questions. add_question(self,question) -- Adds a question to the current deck remove_question(self,question) -- returns True if the question was removed, False otherwise get_question() -- Returns the next unanswered question in the deck get_stats() -- returns a tuple containing: number_asked, number_correct, number_remaining shuffle_deck() -- shuffles the order of the remaining questions. Deck Overrived the __len__ function so that the len returned is the number of questions in the deck. class Question(): Provides questions to be asked methods: __init__(self,question,answer) -- question string representing the question. answer can be a text string, a tupple (for multiple correct answers) or an object implementing an is_correct() method that returns a boolean check_answer(self,answer) -- tests to see if the answer is correct and returns a boolean Mostly I'm wondering, is this over-kill? The idea is to allow for the deck to be used for as wide a variety of purposes as possible. Also, I want to make it easy to write code that generates decks. Is this design over-kill? Any comments/suggestions welcome. Thanks, David ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor David, I'd make Deck and Question subclass object so as to have new-style classes, as in: class Deck(object): # code here If you don't know about the difference between classic classes and new-style, you needn't worry about it for now. There are a number of ways in which new-style are better, though. I also have a suggestion that you might want to think about after you get the basic functionality working. When I did something similar, I used the pickle module make my Questions persistent between sessions, and had each Question keep track of how many times it has been asked and correctly answered. I then had my Deck.get_question pick which Question to ask in a way that favoured both Questions that had been rarely asked, and those that had the highest error rates. Best, Brian vdB ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] [Fwd: Re: trouble with if]
Adam Urbas said unto the world upon 05/30/2007 11:01 AM: I can't exactly show you the error message anymore, because the program is now screwed up in so many ways that I can't even get it to do the things it used to. It says things like ERROR: Inconsistent indentation detected! 1) Your indentation is outright incorrect (easy to fix), OR 2) Your indentation mixes tabs and spaces. Then it tells me to untabify everything, which i did and it still gives this message. I've started completely over with the exact same indentation and that one works. Oh my gosh this gmail is a fricken crack head... none of this stuff was here last night. I have no idea what was going on then, but everything you guys said is right here. The plain text is right next to the Check spelling, the reply to all is right above send and save now and in the corner near the little arrow. Well, it's working now. Ok, so if i have a section of code that is: answer=(2+3): print answer, answer so for the code above I would put: (I think I would have to have the two numbers and the addition thing in there wouldn't I; I saw something like this on Alan's tutorial last night.) def answer(2,3): answer=(2+3) print answer,answer That is obviously not right.: There's an error in your program: invalid syntax when it says that it highlights the 2: def answer(2+3): Ok I think I understand these now. Thanks for the advice. I have this now: def answer(): print(answer) answer() It works too, yay! Thanks, Au Adam, Glad you are sorting out the gmail---in the long run, plain text will make this all much easier than what you had before :-) Your answer function definition above is saying something like this: make answer the name of a function that takes no parameters, and, when called, have it execute a print. This: def answer(2,3): answer=(2+3) print answer,answer doesn't work, as you are trying to set the values of the two parameters to 2 and 3 in the function definition itself. That's not how parameters work. The definition of a function sets the parameters up as named `slots' that function calls will give values to. (There are, as Andre pointed out, more details, but let those aside for now and focus on the simplest cases.) This: def answer(): answer=(2+3) print answer,answer would work, but it isn't much different than the code that did work. Try this: def answer(my_first_parameter, my_second_parameter): value = my_first_parameter + my_second_parameter print Answer:\t, value (I wouldn't use the cumbersome names `my_first_parameter', etc. in real code, but perhaps they help keeping track of what is going on in early stages.) That says, in effect, let answer be a function which takes two positional parameters, adds them, and prints the result in an informative way. answer(40, 2) Answer: 42 answer(A string, and another string) Answer: A string and another string These work because the function definition ensures that the first parameter (40, in the first case above) will, as far as the function is concerned, be called my_first_parameter. (Likewise for 2 and my_second_parameter.) Does that help? Brian vdB ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] trouble with if
adam urbas said unto the world upon 05/29/2007 12:39 PM: The scary part is, I think I understand this. I copied your last example and put it in IDLE and it doesn't like you code. Never mind. I figured it out. So that is so it will notify you if your choice is invalid. Nice lil tidbit of information there. I'll be sure to use this. Oh and while your here, I'd like to ask about loops I guess they are. I want to have the program go back to the part where it asks for the user to select an option after it has run one of its if statements.Like, when the user tells it, circle, then radius, then enters the radius: here I would like the program to go back and ask the user if they want to do anything else, like find the area of a square, instead of the circle. Would I have to tell python to print all those selections again, or would there be a way to just return to the beginning?Thanks,Au Date: Hi Adam, Again, I cut the mess, but I expect that if you use the gmail account you just posted about here on in, that will be the end of it. I'm glad that you are starting to have the warm glow of understanding :-) What you are asking about here is one reason why functions are so useful. They allow you (more or less) to give a name to a chunk of code, and then you can rerun that chunk at will by invoking the name. Given the problem you want to solve, I'd structure my code something like the following. Most of the details need to be filled in, but this is the skeletal structure. def welcome_message(): # Some actions to invoke when the user starts the program print Welcome to this program. def display_menu(): # Insert code for showing the user the menu of options pass def circle_area(): # insert code here to ask user for the radius, compute the area, # and display the result. You might well want to divide that up # into other functions that this one calls. pass def square_area(): # Likewise pass # And so on, for each shape that you wish to handle def exit_message(): # Some actions to invoke when the user chooses to terminate # the program. print Thank you for using this program. Goodbye. def prompt_user(): # Here is where the sort of code I showed you before would go. # I'd include an option, say 0, for exiting, which, when the # user picks it, you call exit_message() while True: try: choice = int(raw_input(Please make your choice )) if choice 0 or choice 2: # Adjust to suit options raise ValueError break except ValueError: print Please make a choice from the options offered. # sends the choice back to the code that called prompt_user # We won't get here until a good choice has been made return choice def main(): # The main function driving your program. It might look # something like this: welcome_message() while True: # This will loop forever until you break out display_menu() choice = prompt_user() if choice == 0: exit_message() break # Terminate the while loop elif choice == 1: # Assuming 1 was the option for circle circle_area() elif choice == 2: square_area() # And so on print Please make another choice: # Go back to top of loop if __name__ == '__main__': # This will run if you run the script, but not if you import it. main() This has not been tested (it is only an outline) but it does pass the only so reliable eyeball check :-) I'd suggest you try filling this sketch out to be useful, and post if you run into troubles. Best, Brian vdB ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] [Fwd: Re: trouble with if]
Forwarding to the list as I'm out of time on this one for now. Adam, it is better to reply to all so that messages are sent to the list and not just the original sender. That way, more people can help, more people can learn, and you don't have to wait on one person to find the time. Anticipating: when you are displaying a message in gmail, the top right-hand side of the message display window has a clickable `Reply'. Immediately beside that is a down pointing arrow. Click on that, and you will have a menu with an option `Reply to all.' That's the reply mechanism you want to use to reply to the list and the original sender rather than just the sender. Best, Brian vdB Original Message Subject: Re: [Tutor] trouble with if Date: Tue, 29 May 2007 23:07:57 -0500 From: Adam Urbas [EMAIL PROTECTED] To: Brian van den Broek [EMAIL PROTECTED] References: [EMAIL PROTECTED] [EMAIL PROTECTED] In the def welcome(), what do you put in the parentheses? Another question, what code do you use for ending the program. I want the user to be able to cancel the program from the main menu, where it asks you to choose circle, square, etc. Or even perhaps allow the user to go back to a previous menu, well I suppose that would be the def thing() code. But what if they were at the part where the program was asking them to input the radius, how would I give them the option of returning to the list of given measurements of a circle? On 5/29/07, Brian van den Broek [EMAIL PROTECTED] wrote: adam urbas said unto the world upon 05/29/2007 12:39 PM: The scary part is, I think I understand this. I copied your last example and put it in IDLE and it doesn't like you code. Never mind. I figured it out. So that is so it will notify you if your choice is invalid. Nice lil tidbit of information there. I'll be sure to use this. Oh and while your here, I'd like to ask about loops I guess they are. I want to have the program go back to the part where it asks for the user to select an option after it has run one of its if statements.Like, when the user tells it, circle, then radius, then enters the radius: here I would like the program to go back and ask the user if they want to do anything else, like find the area of a square, instead of the circle. Would I have to tell python to print all those selections again, or would there be a way to just return to the beginning?Thanks,Au Date: Hi Adam, Again, I cut the mess, but I expect that if you use the gmail account you just posted about here on in, that will be the end of it. I'm glad that you are starting to have the warm glow of understanding :-) What you are asking about here is one reason why functions are so useful. They allow you (more or less) to give a name to a chunk of code, and then you can rerun that chunk at will by invoking the name. Given the problem you want to solve, I'd structure my code something like the following. Most of the details need to be filled in, but this is the skeletal structure. def welcome_message(): # Some actions to invoke when the user starts the program print Welcome to this program. def display_menu(): # Insert code for showing the user the menu of options pass def circle_area(): # insert code here to ask user for the radius, compute the area, # and display the result. You might well want to divide that up # into other functions that this one calls. pass def square_area(): # Likewise pass # And so on, for each shape that you wish to handle def exit_message(): # Some actions to invoke when the user chooses to terminate # the program. print Thank you for using this program. Goodbye. def prompt_user(): # Here is where the sort of code I showed you before would go. # I'd include an option, say 0, for exiting, which, when the # user picks it, you call exit_message() while True: try: choice = int(raw_input(Please make your choice )) if choice 0 or choice 2: # Adjust to suit options raise ValueError break except ValueError: print Please make a choice from the options offered. # sends the choice back to the code that called prompt_user # We won't get here until a good choice has been made return choice def main(): # The main function driving your program. It might look # something like this: welcome_message() while True: # This will loop forever until you break out display_menu() choice = prompt_user() if choice == 0: exit_message() break # Terminate the while loop elif choice == 1: # Assuming 1 was the option for circle circle_area() elif choice == 2: square_area() # And so on print Please make
Re: [Tutor] trouble with if
adam urbas said unto the world upon 05/27/2007 01:49 PM: Thank you for the help Brian. I would like to ask you about these things. Which one of the examples you gave would be most fool proof. snip of all previous exchanges which are too badly formatted to be readable Hi Adam and all, Adam was asking about how to use raw_input to drive a basic command prompt menu system. I'd tried to explain that raw_input returns strings, so his if tests which were something like: choice = raw_input(Enter an option) if choice == 1: do_option_1_stuff() elif choice == 2: do_option_2_stuff() were not going to work, as choice will never be equal to an int. I'd sketched a few ways to deal with this, chiefly applying int() to choice or comparing choice to '1', etc. That's more of less the gist of the above snippage and takes us more or less up to the point where Adam asked his question above. I'm going to show you a few things that might be new to you, Adam. Let's build up in steps. As a first pass, I would do the following: choice = int(raw_input(Please make your choice )) if choice == 1: # Option 1 code here print In option 1 elif choice == 2: # Option 2 code here print In option 2 # Carry on if-test as needed (or until you get to the point # of learning about dictionary dispatch :-) That will be fine, until your user enters something silly: Please make your choice I like bikes! Traceback (most recent call last): File /home/brian/docs/jotter/python_scraps/adamcode.py, line 1, in module choice = int(raw_input(Please make your choice )) ValueError: invalid literal for int() with base 10: 'I like bikes!' That's no good! So, we can use Python's exception handling tools to make this a bit better. try: choice = int(raw_input(Please make your choice )) except ValueError: print Please make a choice from the options offered. if choice == 1: print In option 1 elif choice == 2: print In option 2 There is still a problem, though: # Make sure the previous value assigned to choice is gone. del(choice) Please make your choice I like Bikes Please make a choice from the options offered. Traceback (most recent call last): File /home/brian/docs/jotter/python_scraps/adamcode.py, line 7, in module if choice == 1: NameError: name 'choice' is not defined We've printed the reminder to the user, but then have gone on to compare the non-existent choice value to 1, and that doesn't work so well. It isn't enough to make sure that choice isn't insane---we need to make sure that there is a choice value at all. So, better still: while True: try: choice = int(raw_input(Please make your choice )) # If the previous line worked, end the while loop. If it did # not work, we won't get here, so the loop will keep looping. break except ValueError: print Please make a choice from the options offered. if choice == 1: print In option 1 elif choice == 2: print In option 2 Now we get the following: Please make your choice I like bikes! Please make a choice from the options offered. Please make your choice Please take this Please make a choice from the options offered. Please make your choice1 In option 1 There is still a problem, though: Please make your choice 42 Our sanity check has only insisted that the user enter a value that can be turned into an int; nothing as yet makes it be one of the ints we are expecting. So, try this: while True: try: choice = int(raw_input(Please make your choice )) if choice 1 or choice 2: # Adjust to suit options raise ValueError break except ValueError: print Please make a choice from the options offered. if choice == 1: print In option 1 elif choice == 2: print In option 2 Please make your choice I like bikes! Please make a choice from the options offered. Please make your choice 42 Please make a choice from the options offered. Please make your choice 2 In option 2 Now, all of this should be formatted to be a bit prettier---and displaying the allowable options up front is a good idea, too---but the essential ideas are there. There might be some parts of this that are new to you, so ask away if you've gotten a bit lost. And, I'm no expert, so if someone else comes along and says `No, don't do it like that', odds are they might be right. (Especially if their name is Alan, Danny, or Kent ;-) Best, Brian vdB ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] trouble with indents
adam urbas said unto the world upon 05/28/2007 12:24 AM: Thanks for the clarification, but I'm still a tad confused. I'm not sure when to indent. I understand that it has to be done. That link was really confusing. Very newb non-friendly. Arrg... That site is doom. So confusing. I need somewhere to start from the beginning. This site uses all kinds of big words and doesn't explain things in a clear manner. Oh well. Thanks for the help, though.Au From: [EMAIL PROTECTED] To: tutor@python.org Date: Thu, 24 May 2007 15:30:34 -0400 Subject: Re: [Tutor] trouble with if I'm not sure what the whole indentation thing is for. And now I'm having trouble with the if statement things. Maybe your if statement troubles have been solved by others by now, but I'll just add that the indentation thing is a vital feature of Python, it is the way to separate code blocks. Other languages uses other means, like curly braces, etc. I get the sense those who like Python enjoy indentation because it forces the code to be quite readable, and I agree. See this: http://www.diveintopython.org/getting_to_know_python/indenting_code.html snip Adam, I think Dive Into Python is quite good, but as a second book or a first book for someone with a bit more experience of other languages than it seems like you might have. The first think I read was http://www.ibiblio.org/obp/thinkCSpy/ which is aimed at high school students. It might move a bit slowly for some tastes, but it sounds like DIP is moving a bit too fast. The full text is free; give it a look. Best, Brian vdB ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] trouble with if
adam urbas said unto the world upon 05/23/2007 11:57 AM: Hi all, I've been working with this new program that I wrote. I started out with it on a Ti-83, which is much easier to program than python. Now I'm trying to transfer the program to python but its proving to be quite difficult. I'm not sure what the whole indentation thing is for. And now I'm having trouble with the if statement things. #Circle Data Calculation Program: print Welcome to the Circle Data Calcuation Program. print #Menu 1: print Pick a shape: print (NOTE: You must select the number of the shape and not the shape itself) print 1 Circle print 2 Square print 3 Triangle #User's Choice: shape=raw_input( ) #Select Given: if shape == 1: print Choose the given value: print 1 radius print 2 diameter print 3 circumference print 4 area #User's Choice: given=raw_input( ) if given == 1: radius=raw_input(Enter Radius:) diameter=(radius*2) circumference=(diameter*3.14) area=(radius**2*3.14) print Diameter:, diameter print Circumference:, circumference print Area:, area if given == 2: diameter=raw_input(Enter Diameter:) radius=(diameter/2) circumference=(diameter*3.14) area=(radius**2*3.14) print Radius:, radius print Circumference:, circumference print Area:, area if given == 3: circumference=raw_input(Enter Circumference:) radius=(circumference/3.14/2) diameter=(radius*2) area=(radius**2*3.14) print Radius:, radius print Diameter:, diameter print Area:, area if given == 4: area=raw_input(Enter Area:) radius=(area/3.14) This is the whole program so far, because I haven't quite finished it yet. But I tried to get it to display another list of options after you select a shape but it just does this. Pick a shape: 1 Circle 2 Square 3 Triangle 1 1 I'm not sure why it does that but I do know that it is skipping the second list of options. Another of my problems is that I can't figure out how to get it to accept two different inputs for a selection. Like I want it to accept both the number 1 and circle as circle then list the options for circle. It won't even accept words. I can only get it to accept numbers. It's quite frustrating actually. Any advice would be greatly appreciated. Thanks in advance, Adam Adam, Could you send plain text email rather than html, please? At least for me, your code's indentation is all messed up unless I take some steps to rectify it. The problem is that raw_input returns a string, and you are testing whether given is equal to integers. See if this helps make things clear: data = raw_input('Feed me!') Feed me!42 type(data) type 'str' data == 42 False int(data) == 42 True Best, Brian vdB ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] trouble with if
adam urbas said unto the world upon 05/23/2007 01:04 PM: Sorry, I don't think Hotmail has turn off HTML. If it does I havn't been able to find it. I think you're going to have to explain your little bit of text stuff down there at the bottom. I have no idea what most of that means. All my choice things are working now though. I think that is what you were trying to help me with. What I used wasif shape in[1,circle]:and if shape == 1 or shape ==circle:It works perfectly fine now.Ya that little bit o' code is really puzzling. I wish I knew more about this python deal. I understand the concept, but not the rules or the techniques and things of that sort. OK... I've got it... the data=raw_input('Feed Me!'). Ok I now understand that bit. Then it says Feed Me! and you put 42 (the ultimate answer to life the universe, everything). OK, it won't accept the type 'str' bit. it doesn't like the . Well, I just removed that bit and it said:Feed Me! and I put 42, and it said (I guess it's satisfied now, with the whole feeding). Well if I understood what 'str' meant, then I could probably figure the rest out. Well I have to go do other things so I'll save the rest of this figuring out till later.I shall return,Adam Date: Wed, 23 May 2007 12:12:16 -0400 From: [EMAIL PROTECTED] To: [EMAIL PROTECTED] CC: tutor@python.org Subject: Re: [Tutor] trouble with if adam urbas said unto the world upon 05/23/2007 11:57 AM:Hi all, I've been working with this new program that I wrote. I started out with it on a Ti-83, which is much easier to program than python. Now I'm trying to transfer the program to python but its proving to be quite difficult. I'm not sure what the whole indentation thing is for. And now I'm having trouble with the if statement things. #Circle Data Calculation Program: print Welcome to the Circle Data Calcuation Program. print#Menu 1: print Pick a shape: print (NOTE: You must select the number of the shape and not the shape itself) print 1 Circle print 2 Square print 3 Triangle#User's Choice: shape=raw_input( ) #Select Given: if shape == 1: print Choose the given value: print 1 radius print 2 diameter print 3 circumference print 4 area#User's Choice: given=raw_input( ) if given == 1: radius=raw_input(Enter Radius:) diameter=(radius*2) circumference=(diameter*3.14) area=(radius**2*3.14) print Diameter:, diameter print Circumference:, circumference print Area:, areaif given == 2: diameter=raw_input(Enter Diameter:) radius=(diameter/2) circumference=(diameter*3.14) area=(radius**2*3.14) print Radius:, radius print Circumference:, circumference print Area:, areaif given == 3: circumference=raw_input(Enter Circumference:) radius=(circumference/3.14/2) diameter=(radius*2) area=(radius**2*3.14) print Radius:, radius print Diameter:, diameter print Area:, area if given == 4: area=raw_input(Enter Area:) radius=(area/3.14) This is the whole program so far, because I haven't quite finished it yet. But I tried to get it to display another list of options after you select a shape but it just does this.Pick a shape: 1 Circle 2 Square 3 Triangle 1 1 I'm not sure why it does that but I do know that it is skipping the second list of options.Another of my problems is that I can't figure out how to get it to accept two different inputs for a selection. Like I want it to accept both the number 1 and circle as circle then list the options for circle. It won't even accept words. I can only get it to accept numbers. It's quite frustrating actually.Any advice would be greatly appreciated. Thanks in advance, Adam Adam, Could you send plain text email rather than html, please? At least for me, your code's indentation is all messed up unless I take some steps to rectify it. The problem is that raw_input returns a string, and you are testing whether given is equal to integers. See if this helps make things clear:data = raw_input('Feed me!') Feed me!42 type(data) type 'str' data == 42 False int(data) == 42 TrueBest, Brian vdB Adam, As you can see from the above, the way hotmail is formatting things makes the conversation a bit tricky :-) I'm only willing to spend so much time trying to sort through it, so I hope what follows helps. data = raw_input(Feed me!) Feed me!42 This calls the builtin function raw_input with a parameter setting the prompt to Feed me! and assigns the result to data. Since I hit 42 and then enter, data '42' Notice the quotes around 42. They indicate that the value of data is a string. That's what this tells us: type(data) type 'str' The string '42' is not the same as the integer 42:
Re: [Tutor] Rounding to nearest cent
Jessica Brink said unto the world upon 05/22/2007 09:08 AM: How would I round to the nearest cent when doing calculations with dollar amounts? -Jess Hi Jess, The decimal module was introduced in large part to facilitate financial calculations. Have a look at http://www.python.org/doc/current/lib/module-decimal.html and see if you can get what you need from the docs. If not, ask for more help. Best, Brian vdB ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Function for converting ints from base10 to base2?
Dick Moores said unto the world upon 02/21/2007 08:08 PM: At 05:17 PM 2/21/2007, Terry Carroll wrote: snip I like the approach of mapping hex or octal digits posted by Alan and Bob, but, not thinking of that, this would be my straightforward approach: def computeBin(n): converts base10 integer n to base2 b as string if n == 0: return '0' sign = ['','-'][n0] snip Thanks! But there's syntax(?) there I've never seen before. ['','-'][n0]. I see it works: n = -6 ['','-'][n0] '-' n = 98 ['','-'][n0] '' What's this called? I'd like to look it up. Hi Dick and all, I don't know that it has a name other than `trickery!' ;-) But, if you're scratching your head over it: Python 2.4.4c1 (#2, Oct 11 2006, 21:51:02) [GCC 4.1.2 20060928 (prerelease) (Ubuntu 4.1.1-13ubuntu5)] on linux2 Type help, copyright, credits or license for more information. 1==True True 0==False True Best, Brian vdB ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] shebang problem
Alan Gauld said unto the world upon 11/04/2006 06:47 PM: [EMAIL PROTECTED]:~/test$ ls -la shebangtest.py -rwxr-xr-- 1 brian brian 68 2006-11-04 02:29 shebangtest.py so the file is called shebangtest.py... [EMAIL PROTECTED]:~/test$ shebangtest bash: shebangtest: command not found but you try to run shebangtest... bash can't find the file. you didn't put the .py on the end Well, shebangtest.py also didn't work as evidenced by one of the lines you snipped. Also you may not have . in your path. For security reasons it isn't there by default. Try [EMAIL PROTECTED]:~/test$ ./shebangtest.py And that would be it. It didn't occur to me to try ./shebangtest.py in lieu of the bare shebangtest.py. My command-line instinct were installed back in the days of using DOS on an XT. DOS (at least the version I used) first checked the cwd and only then searched the path. The security implications that Alan and Rick pointed to make the POSIX/bash behaviour make perfect sense on reflection, though. Thanks to all who replied, both on and off list, Brian vdB ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] shebang problem
Hi all, I'm still getting comfortable with Linux and this might be an OS rather than a python problem. I am trying to make a script directly executable. I've reviewed the 2nd ed of the Nutshell, and I cannot work out what I'm doing wrong. I'm running ubunutu 6.10 (edgy eft). Here's a copy past of my command line: [EMAIL PROTECTED]:~/test$ which python /usr/bin/python [EMAIL PROTECTED]:~/test$ ls -la shebangtest.py -rwxr-xr-- 1 brian brian 68 2006-11-04 02:29 shebangtest.py [EMAIL PROTECTED]:~/test$ cat shebangtest.py #!/usr/bin/python if __name__ == '__main__': print It works [EMAIL PROTECTED]:~/test$ shebangtest bash: shebangtest: command not found [EMAIL PROTECTED]:~/test$ shebangtest.py bash: shebangtest.py: command not found I've also tried: #!/usr/bin python as my shebang line. I've been unable to get this to work. Clearly, there is something I've misunderstood. (`#!' is not an easy thing to google for :-) Best, Brian vdB ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Trying to extract the last line of a text file
Asrarahmed Kadri said unto the world upon 19/10/06 12:55 PM: My algorithm is like this: first count the number of lines in the file by using a loop. Use a second loop and when teh counter reaches the num_of_lines values: take the line. Is there any other way to do it?? On 10/19/06, Danny Yoo [EMAIL PROTECTED] wrote: On Thu, 19 Oct 2006, Asrarahmed Kadri wrote: I want to extract the last line of the text file. Any idea ??? Hi Asrarahmed, Ok, so what part do you get stuck on when you try to do this? That is, what sort of things do you already know how to do with files? Hi Asrarahmed, one way would be to use the readlines method of the file object. That will get you a list of lines. From that, you could slice out the last line. Would you know how to do that? If not, ask again. Best, Brian vdB ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] What is a Python project?
Dick Moores said unto the world upon 03/10/06 01:41 PM: At 10:01 AM 10/3/2006, Mike Hansen wrote: snip Dick asking about the point of projects in Wing IDE and Mike replying I've been doing some web programming, so my projects consist of cheetah template files, CSS, config files, a handful of python modules... Why do you make python modules part of a project? They can be used without copying them around, can't they? Or is it that by a project is meant in part a list of pointers to all the files you mean for that program to use, and you don't actually have to copy or move them so they are all in the same folder/directory? Thanks, Mike. Dick Hi Dick, I've never used Wing, but unless its `project' concept is radically different than many other editors, it isn't about organizing the files on disk. Rather, it is about organizing a group of files into a collection the editor can open in one swell foop. The idea is to liberate you from having to recall just where the files live and allow you to merely open a group of related files and get on with what you're up to. (It is sort of like saving a group of tabs in firefox.) Best, Brian vdB ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] folder and module
linda.s said unto the world upon 17/09/06 02:03 PM: snip I checked sys.path and environemntal variables: since the desktop directory is not listed in either of them, why there is no error report when I import a module which is in the desktop into test.py which is under a different folder? Linda ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor Hi Linda, what do you get when you try: import os os.getcwd() The current working directory is represented in sys.path as the first element: import sys sys.path[0] '' Not the most intuitive, perhaps. I suspect you are launching your Python environment from a desktop icon. That would explain why import can `see' your Desktop, even though it doesn't at first glance seem to be in sys.path. Best, Brian vdB ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Lists in lists
Kent Johnson said unto the world upon 16/09/06 07:49 PM: Brian van den Broek wrote: Kent Johnson said unto the world upon 16/09/06 04:35 PM: Brian van den Broek wrote: You say you are new to Python. Well, it might not now be obvious why dictionaries are especially useful, but they are *central* to the pythonic approach. The sooner you become comfortable with them, the better (IMHO). I agree that dicts are extremely useful, but I don't think they add anything in this case unless there is actually a need for keyed access. A list of lists (or tuples) seems very appropriate to me. A good alternative might be a list of Bunches. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52308 Kent Hi Kent and all, I should have included the reason why I thought a dict might be better here. (I did send it in a private email after the post.) A lot of ways I could imagine the time-line data being used might involve wanting to access some one year, rather than the entire time-line. Yes, I was a bit hasty in denouncing dicts, the best data structure does depend entirely on how it is to be used, and we don't know enough about this application to know. Hi Kent and all, I absolutely agree that my suggestions did get a bit ahead of the spec :-) A combination of thinking about what *I* would want a yearly headline program to do and wanting to encourage comfort with dicts ASAP is what drove the suggestion. But, if the OP has a simpler spec than my imaginary one . . . . print timeline_data[800][0] seems *way* better than something like: for year_data in timeline_data_as_list_of_lists: ...if year_data[0] == 800: ... print year_data[1] ... break which would be what the original list structure seems to require. The thing is, though, how will you know that 800 is a valid year? You need a list of valid years. If you get that list from the dict keys, and iterate that, you haven't really gained anything over a list of tuples. Maybe you have a lot of items and the user enters a year and you want to print out the data you have on the year... def print_year_headline(year): try: print timeline_data[year][0] except KeyError: print I am sorry; we have no data on year %s. %year allows for random access by year while handling the problem. But Kent's point about not getting too far ahead of the spec is surely right. To the OP: if Kent and I disagree, there are very good odds that Kent's the one to listen to ;-) Best to all, Brian vdB ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Lists in lists
Morten Juhl Johansen said unto the world upon 16/09/06 08:29 AM: # Newbie warning I am making a timeline program. It is fairly simple. I base it on appending lists to a list. Ex. [[year1, headline1, event text1], [year2, headline2, event text2]] This seemed like a brilliant idea when I did it. It is easy to sort. Now, if I want to OUTPUT it, how do I indicate that I want to extract first entry in a list in a list? How do I print the separate entries? Yours, Morten Hi Morten, Andrei answered the question you asked; I'd like to make a suggestion involving a bit of reworking. You might think about structuring your timeline data as a dictionary, rather than a list. So: timeline_data = { ... 800: [Charlemagne Crowned Holy Roman Emperor, 'event_text'], ... 1066: [Battle at Hastings, 'event_text']} This makes it very easy to access a given year's data: timeline_data[800] ['Charlemagne Crowned Holy Roman Emperor', 'event_text'] and timeline_data[800][0] 'Charlemagne Crowned Holy Roman Emperor' will get you the headline alone. You expressed a liking for the lists as they are easy to sort. On recent versions of python one can easily obtain a sorted list of dictionary keys, too: d = {1:2, 3:4, 43545:32, -3434:42} d {1: 2, 3: 4, -3434: 42, 43545: 32} sorted(d) [-3434, 1, 3, 43545] (Older versions of Python can do the same, but with a bit more keyboard action.) So, if you wanted to print the headlines in increasing year order: for year in sorted(timeline_data): ... print timeline_data[year][0] ... Charlemagne Crowned Holy Roman Emperor Battle at Hastings You say you are new to Python. Well, it might not now be obvious why dictionaries are especially useful, but they are *central* to the pythonic approach. The sooner you become comfortable with them, the better (IMHO). Best wishes, Brian vdB ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Lists in lists
Kent Johnson said unto the world upon 16/09/06 04:35 PM: Brian van den Broek wrote: Morten Juhl Johansen said unto the world upon 16/09/06 08:29 AM: # Newbie warning I am making a timeline program. It is fairly simple. I base it on appending lists to a list. Ex. [[year1, headline1, event text1], [year2, headline2, event text2]] This seemed like a brilliant idea when I did it. It is easy to sort. Now, if I want to OUTPUT it, how do I indicate that I want to extract first entry in a list in a list? How do I print the separate entries? Yours, Morten Hi Morten, Andrei answered the question you asked; I'd like to make a suggestion involving a bit of reworking. You might think about structuring your timeline data as a dictionary, rather than a list. So: timeline_data = { ... 800: [Charlemagne Crowned Holy Roman Emperor, 'event_text'], ... 1066: [Battle at Hastings, 'event_text']} This makes it very easy to access a given year's data: timeline_data[800] ['Charlemagne Crowned Holy Roman Emperor', 'event_text'] and timeline_data[800][0] 'Charlemagne Crowned Holy Roman Emperor' will get you the headline alone. You expressed a liking for the lists as they are easy to sort. On recent versions of python one can easily obtain a sorted list of dictionary keys, too: d = {1:2, 3:4, 43545:32, -3434:42} d {1: 2, 3: 4, -3434: 42, 43545: 32} sorted(d) [-3434, 1, 3, 43545] (Older versions of Python can do the same, but with a bit more keyboard action.) So, if you wanted to print the headlines in increasing year order: for year in sorted(timeline_data): ... print timeline_data[year][0] ... Charlemagne Crowned Holy Roman Emperor Battle at Hastings You say you are new to Python. Well, it might not now be obvious why dictionaries are especially useful, but they are *central* to the pythonic approach. The sooner you become comfortable with them, the better (IMHO). I agree that dicts are extremely useful, but I don't think they add anything in this case unless there is actually a need for keyed access. A list of lists (or tuples) seems very appropriate to me. A good alternative might be a list of Bunches. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52308 Kent Hi Kent and all, I should have included the reason why I thought a dict might be better here. (I did send it in a private email after the post.) A lot of ways I could imagine the time-line data being used might involve wanting to access some one year, rather than the entire time-line. So, if you wanted to get the headline for the year 800, print timeline_data[800][0] seems *way* better than something like: for year_data in timeline_data_as_list_of_lists: ...if year_data[0] == 800: ... print year_data[1] ... break which would be what the original list structure seems to require. It may be a case of over-design for needs that won't arise, though. Best to all, Brian vdB ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] [OT] Re: Limiting Characters
Luke Paireepinart said unto the world upon 21/08/06 03:48 PM: snip Sort of how my last name is 12 characters long, but on some apps that only have a 12 character array (with the actual length being 11 because of the null terminator) the last letter of my name gets truncated. This doesn't happen anymore, but I used to have everyone calling me 'paireepinar' because that's what was in the computer so they believed it. Stupid old programs :) Hi all, I've noticed fewer programs stymied by length, though paper forms with their boxes for each letter still suck. There are, however, quite a few programs in the wild that, suffused with Anglo-Saxon assumptions, refuse to admit that a surname might just possibly commence with a lower case letter or contain spaces (the horror!) Indeed, my current email address was auto assigned by software that gives you your last name as your user name, except when it doesn't ;-) Brian van den Broek ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] All of Kermit's E-Mails
Danny Yoo said unto the world upon 17/08/06 12:16 PM: Suggest an alternative way of transmitting code. Hi Kermit, snip Just as a side note: you may want to investigate a good email client such as Thunderbird if you have spare time. http://www.mozilla.com/thunderbird/ Much of the frustration I've been seeing on this thread deals with IncrediMail's feature set; what it is providing you isn't so well suited for the kind of technical communication that's on this list. snip Hi Kermit, I'd like to second Danny's suggestion of Thunderbird. It is a very nice client by the same people that produce firefox. I spent a few minutes trying to find out how to set IncrediMail to quote properly. Unfortunately, there is no downloadable documentation (at least not separate from the program itself). Searching http://www.incredimail.com/english/help/searchfaq.asp for `quote' gave no results :-( So, IncrediMail doesn't quite seem so Incredi to me ;-) For what its worth, the feature set that they promote it with (things such as ``Amazing animations'', ''beautiful email backgrounds'', and the ability to ''add funny animations to your emails'') are all likely to be *very* unwelcome on any python or other technical list. If you really like IncrediMail for your personal email, you might think of installing Thunderbird, getting a gmail account and using the combination to post to technical lists, keeping IncrediMail for messages to friends, etc.[*] (If you need help with any of that, you can write me off-list.) [*] My guess is that after a while, you'll find yourself switching to Tbird. :-) Best wishes, Brian vdB ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Which Book
Nagendra Singh said unto the world upon 17/08/06 12:14 PM: Hi All, I have very little programming experience, I have decided to learn Python..there are tons of material and refernces on the web-pages, can you guys please suggest what is the best way to start or which ONE book which I should follow to start. thanks.. Nagendra ``Beware the man of one book.'' Saint Thomas Aquinas Free ($ sense) books I read and liked: http://www.ibiblio.org/obp/thinkCSpy/ (easy) http://diveintopython.org/ (less easy) Both of those can be bought in dead-tree form, as can http://www.oreilly.com/catalog/lpython2/ I'd start with the first and if you don't like it, try the next. Either way, multiple books compliment each other. Best, Brian vdB ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] All of Kermit's E-Mails
Kermit Rose said unto the world upon 17/08/06 02:38 PM: Now if I can only get Thunderbird to quit treating the up and down arrow as a page up or page down, whenever it's at the top line or bottom line of what it thinks is a page. Hi Kermit, I'm glad you've given Thunderbird a try and that you seem to have taken all of the advice in the right spirit. I'm not sure what you mean by a `page' in the context of email. Could you describe the exhibited and expected behaviour in a bit more detail? For now, have you tried clicking in the message body and then using the arrows? (That's all I've got.) You might also what to try the mozilla support forums and knowledge base. Best, Brian ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help regarding forms... (fwd)
Alan Gauld said unto the world upon 08/08/06 12:59 PM: I've been on the internet for over 20 years now and every mail tool/newreader I've ever used has (at least) two reply options: ... I don't understand why this seems to come as a surprise? What am I missing? Alan, I think you are judging based on technical lists, no? There are other kinds?!! :-) :-) mailing list, the more likely it is to be set up with a munged `reply to' header. What exactly does this mean? I still don't quite see how it works. Does this mean a user hits Reply to reply to the whole list and then Reply All - does what The same? What a waste! I've never actually tried `Reply to all' on a munged list. But, since on such lists `Reply' is, in effect, an alias for `Reply to all' I assume that in addition to breaking expectations, munging is also, as you suspect, brought to you by the Department of Redundancy Department. FWIW, the munging preference is pretty runs pretty deep, I think. I my case it took public shame caused by a `private' message that wasn't to see the light. :-[ Burned by the memory, I refuse to munge the class mailing lists I administer. But one day the complaints will wear me down . . . . Best, Brian vdB ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help regarding forms... (fwd)
Alan Gauld said unto the world upon 07/08/06 04:43 PM: this list is setup to send to the poster by default. I made the mistake of doing such a thing earlier myself. I know this is a huge item of contention, but do people favor having the default be to send replies to the list? OK, I've got to ask. This comes up every so often and I really don't understand it. I've been on the internet for over 20 years now and every mail tool/newreader I've ever used has (at least) two reply options: 1) Reply = reply to the original sender 2) Reply All = reply to everyone The same principle has always worked for all of the mailing lists I've ever been on. So why do people seem to expect some other kind of response? Are there mail clients out there that don't offer a Reply All option? Why would anyone want a mailing list that didn't offer two options, one for private reply and the other to include everyone? I don't understand why this seems to come as a surprise? What am I missing? Hi all, Alan, I think you are judging based on technical lists, no? In my experience, the further from computing-technical the domain of a mailing list, the more likely it is to be set up with a munged `reply to' header. It could be worse; there is a photography list I've been occasionally on for a decade or so where the list-denizens are steadfast in their reply to list preference and have to cope with 2-3 ``How do I subscribers?'' emails a week. (This despite instructions being provided in the footer of each and every message posted on the list.) Best, Brian vdB ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] request for sugestions on fragement of code for generating truth-tables
Danny Yoo said unto the world upon 31/03/06 08:27 PM: Then, the output is like so: atoms = [a,b,c] tvas = tva_dict_maker(atoms) display_tvas(tvas) a:Trueb:True c:True a:Trueb:True c:False a:Trueb:False c:True a:Trueb:False c:False a:False b:True c:True a:False b:True c:False a:False b:False c:True a:False b:False c:False Hi Brian, We might be able to take advantage of the recursive nature of this problem. I'll sketch out the idea and try to fight the temptation to write it out in full. *grin* If you haven't encountered recursion before, please shout out and ask for more details. Hi Danny and all, thanks for the response and my apologies for the delayed reply. (No internet at home and end of academic term death-march conspired :-) My first thought about how to tackle the problem was indeed to do it recursively. I got bogged down and ended up with the alternate approach I posted in the original post. Your post got me to take another bash and I obtained a recursive solution. But, subject to the caveat that my recursive solution might well be non-optimal, the non-recursive approach seems a bit better to me. Opinions welcome :-) My recursive solution: def recursive_tva_dict_maker(atoms, recursed=False): tvas = [{atoms[0]:True}, {atoms[0]:False}] if atoms[1:]: temp = [] rest = recursive_tva_dict_maker(atoms[1:], True) for r in rest: for tva in tvas: new = tva.copy() new.update(r) temp.append(new) tvas = temp if not recursed: # if test seemed cheaper than pointless sorting tvas.sort(key = lambda x: [x[y] for y in sorted(x)], reverse=True) return tvas My non-recursive solution: def tva_dict_maker(atoms): tvas = [] val = False for k in range(2**len(atoms)): tvas.append(dict()) for i in range(len(atoms)): key = atoms[i] for j in range(2**len(atoms)): if j % ( len(tvas) / 2.0 ** (i+1) ) == 0: val = not val tvas[j][key]=val return tvas The two functions have identical output. I don't much care about time or resources, as atoms will in practice never be more than 4 or 5 items long. (So, the recursive solution could be simplified by getting rid of the if guard on the sorting. That the ultimate output be so sorted is essential, however.) I'm more concerned with style and clarity. Best, Brian vdB ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] request for sugestions on fragement of code for generating truth-tables
Orri Ganel said unto the world upon 01/04/06 03:04 PM: Brian van den Broek wrote: snip Then, the output is like so: atoms = [a,b,c] tvas = tva_dict_maker(atoms) display_tvas(tvas) a:Trueb:Truec:True a:Trueb:Truec:False a:Trueb:Falsec:True a:Trueb:Falsec:False a:Falseb:Truec:True a:Falseb:Truec:False a:Falseb:Falsec:True a:Falseb:Falsec:False snip What this shouts immediately to me, at least, is binary numbers and bool(). Just use your favorite binary conversion recipe, and count down from int(len(atoms)*1,2), converting as you go. And then you take the boolean value of each digit of the binary number. If you need help, let me know as I've completed a working model. HTH, Orri Hi Orri, thanks for the suggestion, and apologies for the delayed response. I absolutely agree that the problem is connected to binary representations of integers as you suggest. The problem -- given my needs -- with your suggested approach is in use your favo[u*]rite binary conversion recipe. I want my code to be stand alone and I feel fairly safe in asserting that if I implemented your suggestion in a self-contained chunk of code, I'd end up with something more complex than the code I originally posted. In effect, my original code exploited the same principle, without actually going through the binary representation. I am of course open to the possibility that my suspicion is ill-grounded ;-) But, thanks! Best, Brian vdB [*] I'm Canadian, eh! ;-) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Logical Operaor
Kaushal Shriyan said unto the world upon 06/04/06 08:06 AM: Hi I am referring to http://www.ibiblio.org/obp/thinkCSpy/chap04.htm about Logical operators I didnot understood x = 5 x and 1 1 y = 0 y and 1 0 How 5 and 1 means 1 and 0 and 1 means 0 Thanks Regards Kaushal Kaushal, as Jason pointed out, any non-zero number evaluates to True. Also, any non-empty list, string, dict, etc. Witness: bool(6) True bool(0) False bool(non-empty string) True bool('') True bool('') False The other part of the puzzle is that 'and' and 'or' are short-circuit operators. 'or' works like this: return the first value flanking the or if that evaluates to True. Otherwise return the second value: 42 or 0 42 0 or 42 42 7 or 42 7 42 or 7 42 0 or [] [] [] or 0 0 'and' works similarly. It returns the first value if that evaluates to False. Otherwise, it returns the second: 42 and 7 7 7 and 42 42 0 and [] 0 [] and 0 [] HTH, Brian vdB ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] request for sugestions on fragement of code for generating truth-tables
Danny Yoo said unto the world upon 06/04/06 04:38 PM: snip Yes, I agree that the readability of the code is primary. Understandng the recursive approach depends on the reader's comfort with recursive functions, and the non-recursive code depends on the reader's comfort with arithmetic operators. But all arithmetical operations are recursively definable from 0 and sucessorship, so what's the difference? ;-) In all seriousness, though: thanks for the further comments and the helper-function-intense sample code. I'll have a think before I try to decide which I prefer -- I like the division of responsibilities, but worry that the conceptual units have become a bit too small for taste. And, fret not over the typos that you followed up about. I parsed as intended just fine. :-) Thanks again, Brian vdB ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] 'in-place' methods
Michael Broe said unto the world upon 17/02/06 03:57 PM: snip Second question. Do I really have to write the sort_print() function like this: def sort_print(L): L.sort() print L i.e. first perform the operation in-place, then pass the variable? Is this the idiomatic way of doing it? Hi Michael, others have answered what you asked; I thought I'd try to head off a potential problem for you. Perhaps you've seen this already, but since you are wrapping the print in a function, I suspect you want the original list to be unmodified. Thus, compare: def sort_print1(a_list): a_list.sort() print a_list def sort_print2(a_list): t = list(a_list) t.sort() print t list1 = [sort_print1, mutates, the, original] list2 = [sort_print2, doesn't, mutate, the, original] sort_print1(list1) ['mutates', 'original', 'sort_print1', 'the'] list1 ['mutates', 'original', 'sort_print1', 'the'] sort_print2(list2) [doesn't, 'mutate', 'original', 'sort_print2', 'the'] list2 ['sort_print2', doesn't, 'mutate', 'the', 'original'] HTH, Brian vdB ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] problems with the shebang line and linux
Thanks to all for the replies. Indeed, it must have been the DOS vs. Unix line terminators as several people suggested. A couple of comments in-line below. Roel Schroeven said unto the world upon 16/02/06 11:14 AM: On 16/02/06, *Brian van den Broek* [EMAIL PROTECTED] mailto:[EMAIL PROTECTED] wrote: [EMAIL PROTECTED]:~$ which python /usr/bin/python [EMAIL PROTECTED]:~$ cd /media/windata/ [EMAIL PROTECTED]:/media/windata$ ./testerlyfoo.py Working! [EMAIL PROTECTED] :/media/windata$ ./testerlybar.py bash: ./testerlybar.py: /usr/bin/python^M: bad interpreter: No such file or directory snip That ^M looks familiar to me: normally it means that the file is in DOS/Windows format instead of UNIX format, i.e. with CR/LF at the end of each line instead of only CR. Converting the file with dos2unix or a similar utility should solve the problem in that case. While I'm unable to recall exactly what I did, this must have been it. I *think* I created the offending file while running ubuntu, but launched IDLE by using a right-click context menu entry for Open with IDLE on a file originally created earlier today while running Windows. So, my guess is that doing this put IDLE into Win endings mode. I guess it's there because the file comes from a FAT32 file system, and I presume it has mount options that make the filesystem translate the line endings automatically (though I don't know if such an option even exists). This doesn't seem to be the case as older .py files created on Windows before the last Windows reinstall that inspired me to try ubuntu show Unix endings. (Knowing that Windows takes Unix endings just fine for .py's, I'd set my previous Windows install's IDLE to use Unix endings. I guess I didn't make that setting after reinstalling Windows.) Strange thing is that the problem persists after retyping the file, but I guess that's because the editor was still in CR/LF mode. Did you create a new file before starting to retype, or did you just clear everything? Just cleared. So, somewhere in the complex of ill-recalled events surely lives the answer. Anyway, thanks again to all for the help! Brian vdB ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] problems with the shebang line and linux
Hi all, I've switched to Linux fairly recently and am still at the fumbling about stage :-) I'm having a devil of a time with the shebang line and running a py file from a command line. I wrote the following little test script with IDLE 1.1.2 under Python 2.4.2 on Ubuntu 5.10: code #!/usr/bin/python print Working! /code I then C P'ed it to another .py file. testerlyfoo.py is the original, testerlybar.py is the pasted copy. Here's my command line results: [EMAIL PROTECTED]:~$ which python /usr/bin/python [EMAIL PROTECTED]:~$ cd /media/windata/ [EMAIL PROTECTED]:/media/windata$ ./testerlyfoo.py Working! [EMAIL PROTECTED]:/media/windata$ ./testerlybar.py bash: ./testerlybar.py: /usr/bin/python^M: bad interpreter: No such file or directory [EMAIL PROTECTED]:/media/windata$ I even retyped the testerlybar.py file, but I end up with the same results as when the small script was copied and pasted. Likewise, I got the same results after saving the two files to my Home directory on the hail mary thought that perhaps the fact I'd save the originals on a FAT32 mounted drive might be making things goofy. I'm stumped. Any steps I can take to work out what's going on? Best to all, Brian vdB ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] problems with the shebang line and linux
[EMAIL PROTECTED] said unto the world upon 16/02/06 08:22 AM: bash: ./testerlybar.py: /usr/bin/python^M: bad interpreter: No such file or directory [EMAIL PROTECTED]:/media/windata$ Note the ^M the additional fileformat character inserted. That is causing the problem. Instead of copying and pasting try to use cp file1 file2. Else, open the copied file and try to remove ^M from it. Under vim, it is :%s/\r//g ( this removed the additional line break character which your editor or something had introduced. Hi, thanks; I did notice the '^M' and was puzzled by it. It persisted even when I manually retyped the script in IDLE. Or, more conservatively, I feel certain that this is so :-) Either way, the cp dance worked. I call Gremlins! ;-) Best, Brian vdB ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] tutorials
catherine curley said unto the world upon 16/01/06 08:26 AM: Hi Has anyone got an easy way of printing the Python documentation in PDF format. Its all in HTML and is time consuming to print. Catherine pdf format is available here: http://docs.python.org/download.html. Best, Brian vdB ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Finding the Index of a member of a Tuple
bob said unto the world upon 11/01/06 10:47 PM: At 08:31 PM 1/11/2006, Steve Haley wrote: Hello everyone, I need to do something very simple but I'm having trouble finding the way to do it - at least easily. I have created a tuple and now need to find the position of individual members of that tuple. Specifically, the tuple is something like: words = (you, me, us, we, and, so, forth) and I need to be able to name a member, for example, us and find what the position (index) of that word is in the tuple. I would have thought there would be a simple built in function for that but I just went through the built in functions in the Python Library Reference and I didn't find anything. I could probably figure out how to write a while loop or something to do a sequential search until I found the right member but I really believe there must be an easier way and I'm just not seeing it. You can probably tell I'm just learning Python so any help would be appreciated. Unfortunately there is no list method find. Sigh. Here's how I'd do it: # create a dictionary with each word as key and ordinal as value words = dict([(n,m) for m,n in enumerate((you, me, us, we, and, so, forth))]) words[me] # returns 1 I assume Bob meant that tuples have no index or find method. His suggested procedure will work, but it seems more work than: t = (I'm, a, tuple., I, have, only, magic, methods.) l = list(t) l.index(have) 4 t[4] 'have' I say more work as the way above builds a list to turn into a dictionary. But, since dictionary access is fast, it might be quicker for long tuples where the sought item is near then end. If it matters, test. HTH, Brian vdB ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Locating directory of script?
Liam Clarke said unto the world upon 12/01/06 12:32 AM: Hi all, Let's say I have a script called bob.py in a directory called c:\pythonstuff, which is in my PATH env_var, and python is also in my PATH, and from a completely different directory I call python bob.py is there a right way to determine what directory bob.py resides in? So far I've found that import inspect class Foo: pass sourceP = inspect.getsourcefile(Foo) works, but I'm not too sure how resilient that is... Regards, Liam Clarke Hey Liam, import this The Zen of Python, by Tim Peters snip the wisdom this.__file__ '/usr/lib/python2.4/this.pyc' HTH, Brian vdB ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] declaring list in python
Logesh Pillay said unto the world upon 10/01/06 11:28 PM: Hello list I want to declare a list of a specific size as global to some nested function like so Hi Logesh, what problem are you trying to solve by doing this? Knowing that will help generate more useful answers, I suspect. def foo (n): A[] (of size n) def foo1 ... The only way I can think to declare the list is to use dummy values: A = [0] * n A = [] * n doesn't work. [] * n = [] A = [None] * n would be a better way to created an n-placed list of dummy values in Python, I think. I'd prefer not to use dummy values I have no use for. Is there any way? This is why knowing your problem would be helpful. Built-in Python data structures don't have size limitations that are declared when an instance of the data structure is created. (Python's not C.) There is no way (that I know of) to create an n-placed list save creating a list with n objects. So, I think you will have to either give up on not employing dummy values or give up on creating a list of a fixed length. You could subclass list to create a class with a max. and/or min. length, but I think knowing more about what you want to do would be helpful before getting into that :-) Best, Brian vdB ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor