Re: [Tutor] Getting os.walk output into a list :p:
On 03/15/2013 02:31 PM, Dave Angel wrote: On 03/15/2013 01:53 AM, Paradox wrote: There is something I can't figure out about the following code (using python 2.7.3): def return_tree_files(rootpath, pattern): for root, dirs, files in os.walk(rootpath): i = [os.path.join(root, filename) for filename in fnmatch.filter(files, pattern)] return i I thought the function would return a list of lists of filenames in the rootpath and all subfolders. Instead I get only the filenames that match the pattern in the rootpath, it doesn't go into the subfolders. That's because you returned out of the loop, the first time through. Each time through the loop, it describes one directory. Since your return after the first one, that's the only directory you'll see. That makes a lot of sense, thanks so much. I knew the return must be doing something I didn't understand. thomas ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Random Python Tip
I seem to remember a web page that generated a random Python programming tip. However my Google Fu is weak today. Does anyone recall the URL of what I am talking about? -- Mark :) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Random Python Tip
On 03/15/2013 03:57 AM, Mark Lybrand wrote: I seem to remember a web page that generated a random Python programming tip. However my Google Fu is weak today. Does anyone recall the URL of what I am talking about? Closest that I've seen is the "Module of the Week" http://www.doughellmann.com/PyMOTW/ Or maybe this: https://twitter.com/python_tips But I'd love to see a daily tip that supplied something very simple, elegant and memorable. http://openbookproject.net/pybiblio/practice/wilson/ One other thing: Much of what you'll find for advice is mistaken or misguided. So learn how to test the advice, and learn who to trust when you have no way to test it yourself. One advantage with a mailing list like this is you have lots of people ready to correct typos and misconceptions. This can generate lots of noise, but has a huge net benefit.l -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Designing a program (File-Fetcher)
On 3/14/2013 5:25 PM, Christopher Emery wrote: Hello All, Okay, I know the best way to learn how to do something is to jump in so I have decided I would like to make a program (command line) to get files from a website that will be then used later on by another program. I read your post before reading Alan's reply. I had the same thought - tackle one piece then add on.file-fetcher (within zip file) [snip] Okay with the above said, how should I start to do pseduo code? There is no formal pseudocode - you write the steps as you think of then ask is that explicit enough to code or should I break it down more? Python has been called executable pseudocode. Might as well begin writing in Python but not rigidly. Would each of the above be a function within the program? Perhaps. In your case I'd do that to keep the "main" program simple. How would someone run a command that is normally done at the command line like espeak within python program? There seems to be an inconsistency at http://espeak.sourceforge.net/download.html It says Compiled for Windows. SAPI5 and command-line versions. but all I get is TTSApp.exe which opens the GUI I am looking for the command line program (Linux and Windows) to speak text from a file or from stdin. Do you know where it is or how one gets it? Take a look at thesubprocess module - this is the usual way to run such a program and give it input. Also how would I hide the visual output of a command like espeak, it throws alot of erros but it works, it happens to others using it too. Can't address this as I apparently don't have the correct executable. -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] converting upper case to lowercase and vice-versa
I am just learning Python and my book does not solve my problem. I have not yet been successful in searching the Python 2.7.3 tutorial I am doing an encryption exercise. Python 2.7.3 MAC OS X 10.6.8 What is the correct syntax to covert English characters from uppercase to lowercase and from lowercase to uppercase? With many thanks, Sydney -- Professor Sydney Shall, Department of Haematological Medicine, King's College London, Medical School, 123 Coldharbour Lane, LONDON SE5 9NU, Tel & Fax: +44 (0)207 848 5902, E-Mail: sydney.shall, [correspondents outside the College should add; @kcl.ac.uk] www.kcl.ac.uk ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] converting upper case to lowercase and vice-versa
> What is the correct syntax to covert English characters from uppercase to > lowercase and from lowercase to uppercase? > s.upper() and s.lower() -- best regards, Robert S. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Designing a program (File-Fetcher)
Hello Bob, BG: I am looking for the command line program (Linux and Windows) to speak text from a file or from stdin. Do you know where it is or how one gets it? CE: If you are putting it on Linux such as debian then you can run apt-get install eSpeak, it is in most distro of Linux these days. Otherwise I don't have a clue. To run it on the command line type espeak "text here" there are other things you can do with it but I don't know yet a whole lot as I am just learning. Sincerely in Christ, Christopher On Fri, Mar 15, 2013 at 8:49 AM, bob gailer wrote: > On 3/14/2013 5:25 PM, Christopher Emery wrote: >> >> Hello All, >> >> Okay, I know the best way to learn how to do something is to jump in so I >> have decided I would like to make a program (command line) to get files from >> a website that will be then used later on by another program. >> >> I read your post before reading Alan's reply. I had the same thought - >> tackle one piece then add on.file-fetcher (within zip file) > > [snip] >> >> Okay with the above said, how should I start to do pseduo code? > > There is no formal pseudocode - you write the steps as you think of then ask > is that explicit enough to code or should I break it down more? > > Python has been called executable pseudocode. Might as well begin writing in > Python but not rigidly. > >> Would each of the above be a function within the program? > > Perhaps. In your case I'd do that to keep the "main" program simple. > >> How would someone run a command that is normally done at the command line >> like espeak within python program? > > There seems to be an inconsistency at > http://espeak.sourceforge.net/download.html > It says Compiled for Windows. SAPI5 and command-line versions. but all I get > is TTSApp.exe which opens the GUI > I am looking for the command line program (Linux and Windows) to speak text > from a file or from stdin. > Do you know where it is or how one gets it? > > Take a look at thesubprocess module - this is the usual way to run such a > program and give it input. > > >> Also how would I hide the visual output of a command like espeak, it >> throws alot of erros but it works, it happens to others using it too. > > Can't address this as I apparently don't have the correct executable. > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Fwd: converting upper case to lowercase and vice-versa
Did'nt realise this went offlist, my fault -- Bodsda -- Forwarded message -- From: Shall, Sydney Date: 15 March 2013 14:43 Subject: Re: [Tutor] converting upper case to lowercase and vice-versa To: Bod Soutar On 15/03/2013 14:30, Bod Soutar wrote: On 15 March 2013 13:52, Shall, Sydney wrote: I am just learning Python and my book does not solve my problem. I have not yet been successful in searching the Python 2.7.3 tutorial I am doing an encryption exercise. Python 2.7.3 MAC OS X 10.6.8 What is the correct syntax to covert English characters from uppercase to lowercase and from lowercase to uppercase? With many thanks, Sydney -- mystring = "THIS is A string" newstring = "" for item in mystring: if item.isupper(): newstring += item.upper() else: newstring += item.lower() print newstring Thanks Bod, This is most helpful. In fact, your syntax allows me to now simplify my code. Sydney -- Professor Sydney Shall, Department of Haematological Medicine, King's College London, Medical School, 123 Coldharbour Lane, LONDON SE5 9NU, Tel & Fax: +44 (0)207 848 5902, E-Mail: sydney.shall, [correspondents outside the College should add; @kcl.ac.uk] www.kcl.ac.uk ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Fwd: converting upper case to lowercase and vice-versa
Bod Soutar wrote: > mystring = "THIS is A string" > newstring = "" > for item in mystring: > if item.isupper(): > newstring += item.upper() > else: > newstring += item.lower() > > print newstring This does nothing the hard way as newstring and mystring are equal ;) If you accidentally swapped the if-suite and the else-suite -- there's the swapcase() method: >>> mystring = "THIS is A string" >>> print mystring.swapcase() this IS a STRING ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] File-Fetcher (cmdline-parser)
Hello All, OS = Raspbain Wheezy & Ubuntu 12.10 (both updated daily) Python Version = 3.2 & 3.3 Python Understanding = Beginner (very basic - just started) See paste bin for code, has 44 lines, code does not give any errors. http://pastebin.com/2tLHvUym Okay, I am writing to ask a few question and provide what I have done already. When using argparse.argument is it wise to use dest="" even if you don't mind having it set automatic to the arg option such as -u will become u="None" if it no arg is passed? Because there are options that can be added to each .add_argument such as help=, action= is it a good idea to set each one of them even if the default behavior is what you want? I thinking future proofing wise. In my formatting of my function which will be one of many, am I laying the code out in a way that will become a good habit or should I do it different? If so how? Based on my comments within the function am I understanding what is going on? At the end I use a print() to see if all is being passed or not being passed through the cmdline, my question for you is if I want to access the varibles that are passed through the return args, do I just take the function like this: outside_of_functions_var = cmdline_parser() Does this make outside_of_functions_var a dict or list or other? Thank you for your assistance and insight into learning. Also if I can format my emails to the list in a different way that would make it easier for those to help please do inform me too. Sincerely in Christ, Christopher ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] File-Fetcher (cmdline-parser)
Christopher Emery wrote: > Hello All, > > OS = Raspbain Wheezy & Ubuntu 12.10 (both updated daily) > > Python Version = 3.2 & 3.3 > Python Understanding = Beginner (very basic - just started) > > See paste bin for code, has 44 lines, code does not give any errors. > http://pastebin.com/2tLHvUym > > Okay, I am writing to ask a few question and provide what I have done > already. > > When using argparse.argument is it wise to use dest="" even if you > don't mind having it set automatic to the arg option such as -u will > become u="None" if it no arg is passed? dest determines the attribute name under which the option is stored. I rarely set it explicitly; instead I provide a --long-option: cmdline_parser.add_argument( "-u", "--url-source", help="the url of where the file can be downloaded.") > Because there are options that can be added to each .add_argument such > as help=, action= is it a good idea to set each one of them even if > the default behavior is what you want? I thinking future proofing > wise. To my eyes this is just noise. > In my formatting of my function which will be one of many, am I laying > the code out in a way that will become a good habit or should I do it > different? If so how? > > Based on my comments within the function am I understanding what is going > on? > > At the end I use a print() to see if all is being passed or not being > passed through the cmdline, my question for you is if I want to access > the varibles that are passed through the return args, do I just take > the function like this: > outside_of_functions_var = cmdline_parser() > Does this make outside_of_functions_var a dict or list or other? Neither a dict nor a list, it is an argparse.Namespace object. You can access commandline options as its attributes: args = cmdline_parser() print(args.url_source) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] File-Fetcher (cmdline-parser)
Hello Peter, First let me say thanks for your feedback, please see comments / question below, yours starting with PO and mine starting with CE. PO: dest determines the attribute name under which the option is stored. I rarely set it explicitly; instead I provide a --long-option: CE: Is there a advantage over on or the other? CE: Because there are options that can be added to each .add_argument such as help=, action= is it a good idea to set each one of them even if the default behavior is what you want? I thinking future proofing wise. PO: To my eyes this is just noise. CE: I would agree, to me less the better as long as it can be understood and your not going to break something in the near future that will change. CE: At the end I use a print() to see if all is being passed or not being passed through the cmdline, my question for you is if I want to access the varibles that are passed through the return args, do I just take the function like this: outside_of_functions_var = cmdline_parser() Does this make outside_of_functions_var a dict or list or other? PO: Neither a dict nor a list, it is an argparse.Namespace object. You can access commandline options as its attributes: CE: Okay, so when I use print(args.file_list) or better yet if I take list = args.file_list does it stay a Namespace object or does it change? if it stays the same how do I access the list of files inside it? Thank you ahead of time for your assistance in helping me to learn and understand. Sincerely in Christ, Christopher ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] File-Fetcher (cmdline-parser)
Christopher Emery wrote: > Hello Peter, > > First let me say thanks for your feedback, please see comments / > question below, yours starting with PO and mine starting with CE. > > PO: dest determines the attribute name under which the option is > stored. I rarely set it explicitly; instead I provide a --long-option: > CE: Is there a advantage over on or the other? The advantage is basically that you get a long option ;) This makes for calls in bash scripts, say, that are easier to understand. Also, if you make it a habit to keep long option and dest in sync (something you get for free if you only specify the option) you can deduce the attribute name used in the script from its commandline interface. If in a few months you want to make modifications you will know what to look for in the script. > CE: Because there are options that can be added to each .add_argument > such as help=, action= is it a good idea to set each one of them even > if the default behavior is what you want? I thinking future proofing > wise. > PO: To my eyes this is just noise. > CE: I would agree, to me less the better as long as it can be > understood and your not going to break something in the near future > that will change. > > CE: At the end I use a print() to see if all is being passed or not > being passed through the cmdline, my question for you is if I want to > access the varibles that are passed through the return args, do I just > take the function like this: > outside_of_functions_var = cmdline_parser() > Does this make outside_of_functions_var a dict or list or other? > PO: Neither a dict nor a list, it is an argparse.Namespace object. You > can access commandline options as its attributes: > CE: Okay, so when I use print(args.file_list) or better yet if I take > list = args.file_list does it stay a Namespace object or does it > change? if it stays the same how do I access the list of files inside > it? While args is a Namespace instance args.file_list is a list (if you provide the option at least once on the commandline): $ cat tmp_filefetcher.py import argparse parser = argparse.ArgumentParser() parser.add_argument('-l', "--file-list", action="append") args = parser.parse_args() print("args =", args) print("args.file_list = ", args.file_list) $ python3 tmp_filefetcher.py args = Namespace(file_list=None) args.file_list = None $ python3 tmp_filefetcher.py -l alpha -l beta args = Namespace(file_list=['alpha', 'beta']) args.file_list = ['alpha', 'beta'] ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] File-Fetcher (cmdline-parser)
Hello Peter, Thank you this is much appreciated! It is much clear now. Thank you PO: Also, if you make it a habit to keep long option and dest in sync (something you get for free if you only specify the option) you can deduce the attribute name used in the script from its commandline interface. CE: Can you please explain this deeper please? I am not sure if I am getting it. Sincerely in Christ, Christopher ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Script to generate statements
I was recently given this task. it's a very IBM mainframe specific task so I'm not sure how to find equivalent terms in another environment. I will just use the mainframe terminology and hopefully y'all can figure out what I mean. Given a list of DBRM members create a JCL which has a series of bind statements for each DBRM. This is the tack I took. I have 3 input files a_ contains the fixed part of the JCL b_ contains the template for the bind statement. c_ contains the list of DBRMs This is the script I came up with...Would you critique it and let me know how I could have done it better? #create a series of bind statements fo = open('i:/text/jclout.txt', 'w') fi = open('i:/text/bindjclfirstpart.txt','rU') fibindjclvar = open('i:/text/bindjclvariable.txt','rU') filistofdbrms= open('i:/text/bindjcldbrmlist.txt','rU') varlines =[] varlines = fibindjclvar.readlines() for line in fi: #write out all the lines in the first part of JCL fo.write(line) fo.write('\n') varline = '' for dbrm in filistofdbrms: fo.write('\n') for index in range(0,9): if varlines[index].find('member') > 0: varline = varlines[index] + '('+ dbrm + ')' + ' -' else: varline = varlines[index] fo.write(varline) fo.close() fi.close() fibindjclvar.close() filistofdbrms.close() The "variable" part of the bind statement is where I have to include the DBRM name. I look for the word 'member' in the template. Template looks like this (content of bindjclvariable.txt) BIND PACKAGE(PROD) - MEMBER OWNER(PRODOWNR) - QUALIFIER(PRODTBLS) - ISOLATION(CS) - EXPLAIN(YES) - ACTION(REPLACE) - CURRENTDATA(YES) - VALIDATE(BIND) Thanks! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] File-Fetcher (cmdline-parser)
Christopher Emery wrote: > Hello Peter, > > Thank you this is much appreciated! It is much clear now. Thank you > > PO: Also, if you make it a habit to keep long option and dest in sync > (something you get for free if you only specify the option) you can > deduce the attribute name used in the script from its commandline > interface. > CE: Can you please explain this deeper please? I am not sure if I am getting > it. Don't take offense at the below, I am just making a suggestion that I think will help you communicate better on this list (and others). This is not really the style for this mailing list responses. Normally, you add an attribution header and quote level so people can see who is talking and who is being quoted. In addition, post your response in-line (or after) the quoted text. Quoting is indicated by prefixing "> " to the quoted text. Most (if not all) email/news reader programs have an option to do this for you. This makes it easy to understand the who said what and in response to what. An example is below (and I made up the conversation, not actually quoting anything). = Christopher Emery wrote: > Peter wrote: > > Imaginary_Talker wrote: > > > I am Imaginary_Talker > > Hi Imaginary_Talker, I am Peter. > Hi Peter, I am Christopher. Hi Christopher, I am Ramit. = > > Sincerely in Christ, > Christopher ~Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] File-Fetcher (cmdline-parser)
Hello Ramit, No offense taking. I guess I am now going to disclose information. I do this because I am blind and its not easy to follow people basing it off of > or >> or as people don't know how to clean up there mails,I try my best to and clean others trails all the time. However in a perfect world my taking extra time would not be needed to figure out and keep track of who is saying what. So please don't mind me adjusting information so I can follow the flow for future and even present. Hope you understand! Sincerely in Christ, Christopher On Fri, Mar 15, 2013 at 4:30 PM, Prasad, Ramit wrote: > Christopher Emery wrote: >> Hello Peter, >> >> Thank you this is much appreciated! It is much clear now. Thank you >> >> PO: Also, if you make it a habit to keep long option and dest in sync >> (something you get for free if you only specify the option) you can >> deduce the attribute name used in the script from its commandline >> interface. >> CE: Can you please explain this deeper please? I am not sure if I am getting >> it. > > Don't take offense at the below, I am just making a suggestion that I > think will help you communicate better on this list (and others). > > This is not really the style for this mailing list responses. > Normally, you add an attribution header and quote level so people > can see who is talking and who is being quoted. In addition, post > your response in-line (or after) the quoted text. Quoting is indicated > by prefixing "> " to the quoted text. Most (if not all) email/news > reader programs have an option to do this for you. This makes it easy > to understand the who said what and in response to what. > > An example is below (and I made up the conversation, not actually quoting > anything). > > = > Christopher Emery wrote: >> Peter wrote: >> > Imaginary_Talker wrote: >> > > I am Imaginary_Talker >> > Hi Imaginary_Talker, I am Peter. >> Hi Peter, I am Christopher. > Hi Christopher, I am Ramit. > = > >> >> Sincerely in Christ, >> Christopher > > > ~Ramit > > > > This email is confidential and subject to important disclaimers and > conditions including on offers for the purchase or sale of > securities, accuracy and completeness of information, viruses, > confidentiality, legal privilege, and legal entity disclaimers, > available at http://www.jpmorgan.com/pages/disclosures/email. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] func-question_y_n.py
Hello All, Okay, I have created a small function that will check to see if a user has answered with a Yes, No or other response. If the user puts yes or no the function ends, if they put anything but yes or no then the function will ask them the same question and tell them they either need to put yes or no for their response This is what I have as of now: ### Start of Code ### def question_y_n(question): answer = input(question) while(answer != "Yes"): if answer != "No": print("Please enter Yes or No for your response!") answer = input(question) else: answer = "No" break return answer answer = question_y_n("You want a drink of water? :") print("Your answer to the question was ", answer) ### End of Code ### Is this the best way to handle this? I would like to use this any time I have a yes or no question. In the future I will add to this and make it work with yes/no, true/false, 1/0 so that anytime there is anything that only has two answer I could use this instead of writing more code for each two answer type questions. Thank you for your advice ahead of time!!! PS: I hope don't mind me posting code that works to see if I can improve on it! Sincerely in Christ, Christopher ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Script to generate statements
On Fri, Mar 15, 2013 at 7:42 PM, Charles Leviton wrote: > I was recently given this task. it's a very IBM mainframe specific task > so I'm not sure how to find equivalent terms in another environment. I > will just use the mainframe terminology and hopefully y'all can figure out > what I mean. > > Given a list of DBRM members create a JCL which has a series of bind > statements for each DBRM. > > This is the tack I took. I have 3 input files > a_ contains the fixed part of the JCL > b_ contains the template for the bind statement. > c_ contains the list of DBRMs > > > This is the script I came up with...Would you critique it and let me know > how I could have done it better? > #create a series of bind statements > fo = open('i:/text/jclout.txt', 'w') > fi = open('i:/text/bindjclfirstpart.txt','rU') > fibindjclvar = open('i:/text/bindjclvariable.txt','rU') > filistofdbrms= open('i:/text/bindjcldbrmlist.txt','rU') > > varlines =[] > varlines = fibindjclvar.readlines() > for line in fi: #write out all the lines in the first part of JCL > fo.write(line) > fo.write('\n') > varline = '' > for dbrm in filistofdbrms: > fo.write('\n') > for index in range(0,9): > if varlines[index].find('member') > 0: > varline = varlines[index] + '('+ dbrm + ')' + ' -' > else: > varline = varlines[index] > fo.write(varline) > > fo.close() > fi.close() > fibindjclvar.close() > filistofdbrms.close() > > The "variable" part of the bind statement is where I have to include the > DBRM name. I look for the word 'member' in the template. > Template looks like this (content of bindjclvariable.txt) > BIND PACKAGE(PROD) - > MEMBER > OWNER(PRODOWNR) - > QUALIFIER(PRODTBLS) - > ISOLATION(CS) - > EXPLAIN(YES) - > ACTION(REPLACE) - > CURRENTDATA(YES) - > VALIDATE(BIND) > > Thanks! > I have a few comments * Does the script work? If yes, I'd say it's probably fine. Pretty short so easy to understand whatever you do, and I see no obviously crazy broken shit in there. I don't much like 'fi' and 'fo' for variable names because I have no idea what it means, but it's not a huge issue in a script this small. If anything, I'd suggest more descriptive variable names and just a tad more use of underscores in them to make it easier on the eyes. Google PEP 8 and check it out, it's the python style guide. * I have no clue what DBRM or JCL are, and what a bind statement is. Ideally, if you could give us some examples of what your input and output looks like, I have a much better idea of what the script is trying to do. * Not knowing what version of python you have greatly limits the amount of useful advice I can give you. More modern versions support stuff like with statements to simplify file handling and the str.format function which may be very useful in your template (you could also use % style formatting, perhaps?). But if you're still on 2.5, which wouldn't surprise me on a big mainframe, you don't have the cool stuff yet. Like I said in the first point though, the script is very small and everything looks quite reasonable. It seems readable enough *if* you know what kind of input and output date it's dealing with. HTH, Hugo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] func-question_y_n.py
On Fri, Mar 15, 2013 at 9:01 PM, Christopher Emery wrote: > Hello All, > > Okay, I have created a small function that will check to see if a user > has answered with a Yes, No or other response. If the user puts yes > or no the function ends, if they put anything but yes or no then the > function will ask them the same question and tell them they either > need to put yes or no for their response > > This is what I have as of now: > ### Start of Code ### > def question_y_n(question): > answer = input(question) > while(answer != "Yes"): > if answer != "No": > print("Please enter Yes or No for your response!") > answer = input(question) > else: > answer = "No" > break > return answer > > answer = question_y_n("You want a drink of water? :") > print("Your answer to the question was ", answer) > ### End of Code ### > > Is this the best way to handle this? I would like to use this any > time I have a yes or no question. In the future I will add to this and > make it work with yes/no, true/false, 1/0 so that anytime there is > anything that only has two answer I could use this instead of writing > more code for each two answer type questions. > > Thank you for your advice ahead of time!!! > > PS: I hope don't mind me posting code that works to see if I can improve > on it! > Hey Christopher, posting code that works is totally fine! Let's see how we can improve this little function. The thing that is bugging me most about this code is that the structure of the code is kind of hard to understand, because it doesn't quite clearly match the description you gave of the purpose of the function. Your description was quite nice and simple already, I'm just going to slightly reformat it and put it in a numbered step-by-step format: 1. ask a question, receive an answer 2. if the answer is "Yes" or "No", return the answer 3. else, print a message and go back to step 1 That's a very clear description of the problem, and we like that. So ideally, the code should look as much as possible like that description and it will be very clear and simple as well! I could write the code for you now, but I think you will learn far better if first you try yourself. You might notice some words in the description are already very similar to python code structures. If you get stuck, don't hesitate to come back with whatever code you have, even if that's totally broken and not even valid python. We love seeing people who are trying to figure stuff out and don't want the solution handed to them :) HTH, Hugo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] __init__ doesn't seem to be running
Hello everyone, I'm using Python 3.3 and am trying to write a simple to-do list program. I have a class which runs pretty much everything called todo and the __init__ method doesn't seem to be running. class todo(): def __init__(self): tasks = [] def writeTask(todoList): name = input("Please enter the task > ") desc = input("Please enter a short description (optional) > ") while True: try: imp = int(input("How important is this task? 1-100 > ")) break except TypeError: imp = int(input("How important is this task? 1-100 > ")) if imp > 100: imp = 100 elif imp < 1: imp = 1 todoList.write("\"" + name + "\",\"" + desc + "\",\"" + str(imp) + "\"") print("Task written!") try: todoList = open('todo.txt', 'r+') except IOError: todoList = open('todo.txt', 'w') for line in todoList: tasks.append(line.strip()) writeTask(todoList) todoList.close() main = todo() Whenever I run this, I get the error: Traceback (most recent call last): File "C:\Python33\todo.py", line 8, in class todo(): File "C:\Python33\todo.py", line 34, in todo tasks.append(line.strip()) NameError: name 'tasks' is not defined Indicating that __init__ hasn't run since that is the initialization for tasks. I had always understood that __init__ was the equivalent of a constructor, and should be run at the instantiation of any class. Any help would be much appreciated, Cameron ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] func-question_y_n.py
On 03/15/2013 05:01 PM, Christopher Emery wrote: Hello All, > > Okay, I have created a small function that will check to see if a user > has answered with a Yes, No or other response. If the user puts yes > or no the function ends, if they put anything but yes or no then the > function will ask them the same question and tell them they either > need to put yes or no for their response > > This is what I have as of now: > ### Start of Code ### > def question_y_n(question): > answer = input(question) > while(answer != "Yes"): > if answer != "No": > print("Please enter Yes or No for your response!") > answer = input(question) > else: > answer = "No" > break > return answer > > answer = question_y_n("You want a drink of water? :") > print("Your answer to the question was ", answer) > ### End of Code ### > > Is this the best way to handle this? I would like to use this any > time I have a yes or no question. In the future I will add to this and > make it work with yes/no, true/false, 1/0 so that anytime there is > anything that only has two answer I could use this instead of writing > more code for each two answer type questions. > > Thank you for your advice ahead of time!!! > > PS: I hope don't mind me posting code that works to see if I can improve on it! > > Sincerely in Christ, > Christopher Hi Christopher, I've recently made a couple of functions that do this in a more general way. There are some usage examples at the end, including y/n input. The difference between them is that the 2nd function adds more options. import re def simpleinp(pattern, prompt="> ", convert=None, errmsg="Invalid Input", blank=False): """Keep asking user for input until it matches `pattern`.""" if pattern == "%d": pattern = "\d+"; convert = int if pattern == "%s": pattern = ".+" while True: i = input(prompt).strip() if blank and not i: return None if re.match('^'+pattern+'$', i): return convert(i) if convert and i else i else: print(errmsg) def getinp(pattern, prompt="> ", convert=None, errmsg="Invalid Input", ignorecase=False, lower=False, blank=True): """Keep asking user for input until it matches `pattern`.""" if pattern == "%d": pattern = "\d+" convert = int if pattern == "%f": pattern = "\d+.?\d*" convert = float if pattern == "%s": pattern = "\S+" while True: i = input(prompt).strip() if blank and not i: return None if lower: i = i.lower() flags = re.I if ignorecase else 0 if re.match('^'+pattern+'$', i, flags=flags): return convert(i) if convert else i else: print(errmsg) # print( getinp("%d", "integer: ") ) # print( getinp("%f", "float: ") ) # print( getinp("%s", "string: ") ) # print( getinp("(y|n)", "y/n: ", lower=True) ) # print( simpleinp("%d", "integer: ") ) # print( simpleinp("%s", "string: ") ) # print( simpleinp(".*", "string or blank: ") ) # print( simpleinp("[ynYN]", "y/n: ") ) HTH, -m -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ The dreamer can know no truth, not even about his dream, except by awaking out of it. George Santayana ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] __init__ doesn't seem to be running
On Fri, Mar 15, 2013 at 9:21 PM, Cameron Macleod wrote: > Hello everyone, I'm using Python 3.3 and am trying to write a simple to-do > list program. I have a class which runs pretty much everything called todo > and the __init__ method doesn't seem to be running. > > class todo(): > def __init__(self): > tasks = [] > > def writeTask(todoList): > name = input("Please enter the task > ") > desc = input("Please enter a short description (optional) > ") > while True: > try: > imp = int(input("How important is this task? 1-100 > ")) > break > except TypeError: > imp = int(input("How important is this task? 1-100 > ")) > if imp > 100: > imp = 100 > elif imp < 1: > imp = 1 > todoList.write("\"" + name + "\",\"" + desc + "\",\"" + str(imp) + > "\"") > print("Task written!") > try: > todoList = open('todo.txt', 'r+') > except IOError: > todoList = open('todo.txt', 'w') > for line in todoList: > tasks.append(line.strip()) > writeTask(todoList) > todoList.close() > > main = todo() > > Whenever I run this, I get the error: > > Traceback (most recent call last): > File "C:\Python33\todo.py", line 8, in > class todo(): > File "C:\Python33\todo.py", line 34, in todo > tasks.append(line.strip()) > NameError: name 'tasks' is not defined > > Indicating that __init__ hasn't run since that is the initialization for > tasks. I had always understood that __init__ was the equivalent of a > constructor, and should be run at the instantiation of any class. > That's not what it indicates, you should assume less and debug more. If you add a print statement in __init__, I can guarantee that you will see it executed. Go, try it now, don't assume I'm right ;) Now, the only thing that this error actually indicates is that "tasks" doesn't exist when writeTask is being executed. In both __init__ and writeTask, the "tasks" variable is function-local: it exists only for the duration of the function. What you want is to attach tasks to your object instance, which you do through "self". self is the reference to the current instance, much like the this pointer in Java or C++. So if you do: class Todo: def __init__(self): self.tasks = [] def write_task(self, task): # other code around here self.tasks.append(line.strip()) everything will be fine. HTH, Hugo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] func-question_y_n.py
Hi Mitya, Thank for your example of code, however at this time its well over my head and I think its best if I slowly work on a function that provided only what I need and then add to it IF it works into it. Yours appears to do a whole lot more then process a Yes/No from a question and re-ask the question if the user does not provide a yes or no. I will save your code for future use as I understand it more (smile) Sincerely in Christ, Christopher > I've recently made a couple of functions that do this in a more general > way. There are some usage examples at the end, including y/n input. The > difference between them is that the 2nd function adds more options. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] func-question_y_n.py
Hello Hugo, # Defines the start of a function and its options (question) def question_y_n(question): #1. Ask Question from user, user enters either Yes, No or whatever (anything that is not Yes or No) answer = input(question) # prompts the user and assigns the answer to var answer #2. If the user had entered anything but Yes then a while loop starts and becomes True (meaning it is not a Yes) so it must be either No or something else while(answer != "Yes"): #3. If the answer is anything but a No then the user is prompted with statement and then the question asked again if answer != "No": #4. Print statement and ask question again. print("Please enter Yes or No for your response!") answer = input(question) #5. It is assumed that if the answer was not a Yes in the while loop and it was not a No in the if statement than it is assumed the only other choice would be a No for the else statement. else: answer = "No" break return answer answer = question_y_n("You want a drink of water? :") print("Your answer to the question was ", answer) This code works and produces the results that I am looking for, however I know there is a better way to do it and now you have me thinking about this again. I just spent about 3 hours doing this code. I was thinking of combining the Yes and No into one check however I was having trouble finding resource of how to do mulitiy checks in a statement for while. thinking like this: def question_y_n(question): answer = input(question) while(answer != "Yes" Or "No"): #This is wrong code print("Please enter Yes or No for your response!") answer = input(question) or # This one does not have ability to loop intill a Yes or No is given so my gut tells me the one above is better or the one I have at this time. def question_y_n(question): answer = input(question) if answer == "Yes" OR "No": #this didn't work either for me break else print("Please enter Yes or No for your response!") answer = input(question) return answer Sorry for this layout, I myself was getting a little dizzy reading it. Thank you for your assistance! Sincerely in Christ, Christopher ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] __init__ doesn't seem to be running
I added the "self." to both the references to tasks and then I added the print statement to the __init__ function and I got the dreaded NameError of death: Traceback (most recent call last): File "C:\Python33\todo.py", line 6, in class todo: File "C:\Python33\todo.py", line 31, in todo self.tasks.append(line.strip()) NameError: name 'self' is not defined I then moved the entirety of the code that appeared outside of the functions but within the class into the writeTask function, this produced the longed after print statement and no errors, but was inappropriate for the task in hand. So I re-jiggled most of it into the __init__ method and left the call to writeTask outside of the class, passing in the argument main.todoList . This gave me the print statement (the init is running now!) but also this error: Traceback (most recent call last): File "C:\Python33\todo.py", line 34, in main.writeTask(main.todoList) AttributeError: 'todo' object has no attribute 'todoList' I fixed this with an attachment to self on the todoList object, but then got this error instead. Traceback (most recent call last): File "C:\Python33\todo.py", line 34, in main = todo() File "C:\Python33\todo.py", line 14, in __init__ for line in todoList: NameError: global name 'todoList' is not defined My code now looks something like this: class todo(): def __init__(self): self.tasks = [] print("Hello") try: self.todoList = open('todo.txt', 'r+') except IOError: self.todoList = open('todo.txt', 'w') for line in todoList: self.tasks.append(line.strip()) def writeTask(todoList): name = input("Please enter the task > ") desc = input("Please enter a short description (optional) > ") while True: try: imp = int(input("How important is this task? 1-100 > ")) break except TypeError: imp = int(input("How important is this task? 1-100 > ")) if imp > 100: imp = 100 elif imp < 1: imp = 1 todoList.write("\"" + name + "\",\"" + desc + "\",\"" + str(imp) + "\"") print("Task written!") main = todo() main.writeTask(main.todoList) It's recognising todoList as global now which is better than not being acknowledged at all, but why would it not be defined? (Sorry if this came up twice, wasn't sure whether or not I'd replied to all) On Fri, Mar 15, 2013 at 9:42 PM, Hugo Arts wrote: > On Fri, Mar 15, 2013 at 9:21 PM, Cameron Macleod < > cmacleod...@googlemail.com> wrote: > >> Hello everyone, I'm using Python 3.3 and am trying to write a simple >> to-do list program. I have a class which runs pretty much everything called >> todo and the __init__ method doesn't seem to be running. >> >> class todo(): >> def __init__(self): >> tasks = [] >> >> def writeTask(todoList): >> name = input("Please enter the task > ") >> desc = input("Please enter a short description (optional) > ") >> while True: >> try: >> imp = int(input("How important is this task? 1-100 > ")) >> break >> except TypeError: >> imp = int(input("How important is this task? 1-100 > ")) >> if imp > 100: >> imp = 100 >> elif imp < 1: >> imp = 1 >> todoList.write("\"" + name + "\",\"" + desc + "\",\"" + str(imp) >> + "\"") >> print("Task written!") >> try: >> todoList = open('todo.txt', 'r+') >> except IOError: >> todoList = open('todo.txt', 'w') >> for line in todoList: >> tasks.append(line.strip()) >> writeTask(todoList) >> todoList.close() >> >> main = todo() >> >> Whenever I run this, I get the error: >> >> Traceback (most recent call last): >> File "C:\Python33\todo.py", line 8, in >> class todo(): >> File "C:\Python33\todo.py", line 34, in todo >> tasks.append(line.strip()) >> NameError: name 'tasks' is not defined >> >> Indicating that __init__ hasn't run since that is the initialization for >> tasks. I had always understood that __init__ was the equivalent of a >> constructor, and should be run at the instantiation of any class. >> > > That's not what it indicates, you should assume less and debug more. If > you add a print statement in __init__, I can guarantee that you will see it > executed. Go, try it now, don't assume I'm right ;) > > Now, the only thing that this error actually indicates is that "tasks" > doesn't exist when writeTask is being executed. In both __init__ and > writeTask, the "tasks" variable is function-local: it exists only for the > duration of the function. What you want is to attach tasks to your object > instance, which you do through "self". self is the reference to the current > instance, much like the this pointer in Java or C++. So if you do: > > class Todo: > def __
Re: [Tutor] func-question_y_n.py
On 03/15/2013 06:09 PM, Christopher Emery wrote: -- Hugo said: 1. ask a question, receive an answer 2. if the answer is "Yes" or "No", return the answer 3. else, print a message and go back to step 1 Hello Hugo, # Defines the start of a function and its options (question) def question_y_n(question): #1. Ask Question from user, user enters either Yes, No or whatever (anything that is not Yes or No) answer = input(question) # prompts the user and assigns the answer to var answer #2. If the user had entered anything but Yes then a while loop starts and becomes True (meaning it is not a Yes) so it must be either No or something else while(answer != "Yes"): Hugo's function description is perfectly symmetric with regard to Yes & No. But you've changed that, both in your new description, and in your code. Why is the "while" checking only for "Yes" when it should be checking for either/both? I was thinking of combining the Yes and No into one check however I was having trouble finding resource of how to do mulitiy checks in a statement for while. thinking like this: def question_y_n(question): answer = input(question) while(answer != "Yes" Or "No"): #This is wrong code print("Please enter Yes or No for your response!") answer = input(question) or Do you understand about compound if/while expressions? You can combine boolean expressions with 'and' and 'or' . For example, if you had wanted to check for either 4 or 12, you might do something like: if myint == 4 or myint == 12: do something else: do something else -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] func-question_y_n.py
On 15/03/2013 22:09, Christopher Emery wrote: Hello Hugo, # Defines the start of a function and its options (question) def question_y_n(question): #1. Ask Question from user, user enters either Yes, No or whatever (anything that is not Yes or No) answer = input(question) # prompts the user and assigns the answer to var answer #2. If the user had entered anything but Yes then a while loop starts and becomes True (meaning it is not a Yes) so it must be either No or something else while(answer != "Yes"): Why the unneeded parenthesis? What about 'yes'? #3. If the answer is anything but a No then the user is prompted with statement and then the question asked again if answer != "No": What about 'no'? #4. Print statement and ask question again. print("Please enter Yes or No for your response!") answer = input(question) #5. It is assumed that if the answer was not a Yes in the while loop and it was not a No in the if statement than it is assumed the only other choice would be a No for the else statement. else: answer = "No" break return answer answer = question_y_n("You want a drink of water? :") print("Your answer to the question was ", answer) This code works and produces the results that I am looking for, however I know there is a better way to do it and now you have me thinking about this again. I just spent about 3 hours doing this code. I was thinking of combining the Yes and No into one check however I was having trouble finding resource of how to do mulitiy checks in a statement for while. thinking like this: def question_y_n(question): answer = input(question) while(answer != "Yes" Or "No"): #This is wrong code while answer not in ('yes', 'no'): print("Please enter Yes or No for your response!") answer = input(question) or # This one does not have ability to loop intill a Yes or No is given so my gut tells me the one above is better or the one I have at this time. def question_y_n(question): answer = input(question) if answer == "Yes" OR "No": #this didn't work either for me break else print("Please enter Yes or No for your response!") answer = input(question) return answer Sorry for this layout, I myself was getting a little dizzy reading it. Thank you for your assistance! Sincerely in Christ, Christopher -- Cheers. Mark Lawrence ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] __init__ doesn't seem to be running
On Fri, Mar 15, 2013 at 10:25 PM, Cameron Macleod < cmacleod...@googlemail.com> wrote: > I added the "self." to both the references to tasks and then I added the > print statement to the __init__ function and I got the dreaded NameError of > death: > > > Traceback (most recent call last): > File "C:\Python33\todo.py", line 6, in > class todo: > File "C:\Python33\todo.py", line 31, in todo > self.tasks.append(line.strip()) > NameError: name 'self' is not defined > > I must apologize. I did not notice you omitted it. In python, the "self" does *not* exist implicitly like "this" in Java or C++. In class methods, the first argument to a method is *always* the current instance, and python passes it in automatically. By convention, this is called self, but it could have any name. In other words, when you write this: main.writeTask(todoList) python actually interprets it like so: todo.writeTask(main, todoList) As you can see, the main instance object is the first argument to the method, which should be defined like this: def writeTask(self, todoList): # code here can use self.stuff To repeat, the name "self" is not special in Python, it's just that the first argument to every method called is always the current instance, and by convention this is always called "self" by programmers. You should add self to every method in a class, unless it is a @classmethod or @staticmethod, but those are relatively rare exceptions. HTH, Hugo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] __init__ argument
The program keeps telling me that the __init__ in Rock takes two arguments and only one is given. Ideas? The point of the game is to dodge falling rocks. Two more appear every time one reaches the bottom of the screen. # Avalanche, a dodging game # Written by Josh Wilkerson # Dodge falling rocks, two new rocks appear every time a rock hits the bottom. from livewires import games, color import random games.init(screen_width = 640, screen_height = 480, fps = 50) class Chef(games.Sprite): """ A chef controlled by the player to dodge falling rocks. """ image = games.load_image("chef.jpg") def __init__(self, y = 450): """ Initialize Chef object and create Text object for score. """ super(Chef, self).__init__(image = Chef.image, x = games.mouse.x, bottom = games.screen.height) self.score = games.Text(value = 0, size = 25, color = color.black, top = 5, right = games.screen.width - 10) games.screen.add(self.score) def update(self): """ Move to mouse position x. """ self.x = games.mouse.x if self.left < 0: self.left = 0 if self.right > games.screen.width: self.right = games.screen.width self.check_catch() def check_hit(self): """ Check if hit by rcok. """ for rock in self.overlapping_sprites: self.end_game() self.destroy() class Rock(games.Sprite): """ A rock which falls to the ground. """ image = games.load_image("rock.jpg") speed = 1 def __init__(self, x, y = 90): """ Initiate a rock object. """ super(Rock, self).__init__(image = Rock.image, x = x, y = y, dy = rock.speed) def update(self): """ Check if bottom edge has reached screen bottom. """ if self.bottom > games.screen.height: SPAWN = 2 Rock.SPAWN def handle_hit(self): """ Destroy self if hits chef. """ self.destroy() def end_game(self): """ End the game. """ end_message = games.Message(value = "Game Over", size = 90, color = color.red, x = games.screen.width / 2, y = games.screen.height / 2, lifetime = 5 * games.screen.fps, after_death = games.screen.quit) games.screen.add(end_message) class Dropper(games.Sprite): """ An invisible object that drops the rocks. """ def __init___(self, y = 55, speed = 2, odds_change = 200): """ Initialize the Dropper object. """ super(Dropper, self).__init__(x = games.screen.width / 2, y = y, dx = speed) self.odds_change = odds_change self.time_til_drop = 0 def update(self): """ Determines if direction needs to be reversed. """ if self.left < 0 or self.right > games.screen.width: self.dx = -self.dx elif random.randrange(self.odds_change) == 0: self.dx = -self.dx self.check_drop() def check_drop(self): """ Decreases countdown or drop rock and reset countdown. """ if self.time_til_drop > 0: self.time_til_drop -= 1 else: new_rock = Rock(x = self.x) games.screen.add(new_rock) # set buffer to approx 30% of rock height, regardless of pizza speed self.time_til_drop = int(new_rock.height * 1.3 / Rock.speed) + 1 def main(): """ Play the game. """ backround_image = games.load_image("backround.jpg", transparent = False) games.screen.backround = backround_image the_chef = Chef() games.screen.add(the_chef) the_rock = Rock() games.screen.add(the_rock) the_dropper = Dropper() games.screen.add(the_dropper) games.mouse.is_visible = False games.screen.event_grab = True gsmes.screen.mainloop() # start it up main() This is the error. Exception AttributeError: "'Rock' object has no attribute '_gone'" in > ignored Traceback (most recent call last): File "C:\Users\Joshua\Projects\Avalanche\Avalanche.py", line 129, in main() File "C:\Users\Joshua\Projects\Avalanche\Avalanche.py", line 117, in main the_rock = Rock() TypeError: __init__() takes at least 2 arguments (1 given) >>> ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] __init__ doesn't seem to be running
(By top-posting, you lost all the context. Next time, post your responses AFTER the part you're quoting. And don't just quote it all, only the part that's relevant.) On 03/15/2013 06:25 PM, Cameron Macleod wrote: I added the "self." to both the references to tasks and then I added the print statement to the __init__ function and I got the dreaded NameError of death: Traceback (most recent call last): File "C:\Python33\todo.py", line 6, in class todo: File "C:\Python33\todo.py", line 31, in todo self.tasks.append(line.strip()) NameError: name 'self' is not defined Every one of your methods should normally start with a 'self' parameter. You have one in __init__(), but you forgot it in writeTasks(). And your indentation of the original code is trashed, with a number of lines (starting with the try statement) that are NOT in the writeTask() method. Thus they're considered part of the class definition, and are interpreted in a very different way. Please capitalize the class name, so we won't be confused by the code -- I interpreted the above stacktrace as reporting a problem in the todo() method, when it's actually in the class itself because of the above indentation bug. I then moved the entirety of the code that appeared outside of the functions but within the class into the writeTask function, this produced the longed after print statement and no errors, but was inappropriate for the task in hand. So I re-jiggled most of it into the __init__ method and left the call to writeTask outside of the class, passing in the argument main.todoList . This gave me the print statement (the init is running now!) but also this error: Traceback (most recent call last): File "C:\Python33\todo.py", line 34, in main.writeTask(main.todoList) AttributeError: 'todo' object has no attribute 'todoList' I fixed this with an attachment to self on the todoList object, but then got this error instead. Traceback (most recent call last): File "C:\Python33\todo.py", line 34, in main = todo() File "C:\Python33\todo.py", line 14, in __init__ for line in todoList: NameError: global name 'todoList' is not defined My code now looks something like this: class todo(): def __init__(self): self.tasks = [] print("Hello") try: self.todoList = open('todo.txt', 'r+') except IOError: self.todoList = open('todo.txt', 'w') for line in todoList: self.tasks.append(line.strip()) def writeTask(todoList): that needs to be def writeTask(self, todoList): name = input("Please enter the task > ") desc = input("Please enter a short description (optional) > ") while True: try: imp = int(input("How important is this task? 1-100 > ")) break except TypeError: imp = int(input("How important is this task? 1-100 > ")) if imp > 100: imp = 100 elif imp < 1: imp = 1 todoList.write("\"" + name + "\",\"" + desc + "\",\"" + str(imp) + "\"") print("Task written!") main = todo() main.writeTask(main.todoList) That line is trying to access an attribute of the main object called todoList. Wouldn't it be much clearer if you just used self.todoList in this method, and NOT have such an argument. That way, the definition would be def writeTask(self): and the toplevel code would be: main = todo() main.writeTask() It's recognising todoList as global now which is better than not being acknowledged at all, but why would it not be defined? todoList isn't a global in any case. (Sorry if this came up twice, wasn't sure whether or not I'd replied to all) Please start over with a set of code that we can see in its entirety, and report an error traceback for that particular code. As this message appears now, some errors are in the earlier code, some in code we haven't seen, and some in the new code posted here. -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] func-question_y_n.py
On Fri, Mar 15, 2013 at 10:09 PM, Christopher Emery wrote: > > This code works and produces the results that I am looking for, > however I know there is a better way to do it and now you have me > thinking about this again. I just spent about 3 hours doing this > code. Yes! learning is happening :D I was thinking of combining the Yes and No into one check however I > was having trouble finding resource of how to do mulitiy checks in a > statement for while. > > thinking like this: > > def question_y_n(question): > answer = input(question) > while(answer != "Yes" Or "No"): #This is wrong code > print("Please enter Yes or No for your response!") > answer = input(question) > or > > This is an excellent thought! Nice work, this looks already much, much better and simpler than the previous version, don't you agree? The only problem of course is that you have some wrong code in it, but that's okay. The idea is correct, you just need to write it a little differently so it is valid python :) Dave already gave you the answer on how to combine multiple checks in one statement, with the "and" and "or", and Mark gave you what is called the "idiomatic" way, which is perhaps a little harder to read at first but really elegant once you get used to it. I'll put them both together down here: if a == 5 or a == 6: print("a is 5 or 6!") if a in (5, 6): print("a is 5 or 6!") The second way is a lot shorter, especially if you need to check many values. It uses the "in" operator, which allows you to check if a value is in a list (or more technically, a sequence. Any sequence like tuples, lists, strings, dictionaries, all support the "in" operator). But if you don't quite grasp it yet, the first way is fine too. NOTE: It's important not to confuse these two: # this doesn't work like you think it does if a == 1 or 0: # this is the right way if a == 1 or a == 0: the "or" and "and" operator can only connect *comparisons*, nothing else. The top if statement will be interpreted like this: if (a == 1) or (0): which basically means "execute the code below if "a equals 1" is True OR "the value 0" is True. That's not what you want, even though if you read it like it's English it sounds right (the lesson is, don't read code like it's English, because it isn't even close). You're almost to a working function that can accept any amount of possible answers, which is really nice. Keep it up! HTH, Hugo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] __init__ argument
On 03/15/2013 06:46 PM, Joshua Wilkerson wrote: The program keeps telling me that the __init__ in Rock takes two arguments and only one is given. Ideas? The point of the game is to dodge falling rocks. Two more appear every time one reaches the bottom of the screen. # Avalanche, a dodging game # Written by Josh Wilkerson # Dodge falling rocks, two new rocks appear every time a rock hits the bottom. from livewires import games, color import random games.init(screen_width = 640, screen_height = 480, fps = 50) class Chef(games.Sprite): """ A chef controlled by the player to dodge falling rocks. """ image = games.load_image("chef.jpg") def __init__(self, y = 450): """ Initialize Chef object and create Text object for score. """ super(Chef, self).__init__(image = Chef.image, x = games.mouse.x, bottom = games.screen.height) self.score = games.Text(value = 0, size = 25, color = color.black, top = 5, right = games.screen.width - 10) games.screen.add(self.score) This following update() is probably indented wrong. Currently it's a regular function, not a method, so having a paramter 'self' is just weird. If you want it to be part of the class, you'd better indent it to match the other defs. def update(self): """ Move to mouse position x. """ self.x = games.mouse.x if self.left < 0: self.left = 0 if self.right > games.screen.width: self.right = games.screen.width self.check_catch() def check_hit(self): """ Check if hit by rcok. """ for rock in self.overlapping_sprites: self.end_game() self.destroy() class Rock(games.Sprite): """ A rock which falls to the ground. """ image = games.load_image("rock.jpg") speed = 1 def __init__(self, x, y = 90): This defines a method that can take either two or three arguments. The third one has a default value. """ Initiate a rock object. """ super(Rock, self).__init__(image = Rock.image, x = x, y = y, dy = rock.speed) def update(self): """ Check if bottom edge has reached screen bottom. """ if self.bottom > games.screen.height: SPAWN = 2 Rock.SPAWN def handle_hit(self): """ Destroy self if hits chef. """ self.destroy() def end_game(self): """ End the game. """ end_message = games.Message(value = "Game Over", size = 90, color = color.red, x = games.screen.width / 2, y = games.screen.height / 2, lifetime = 5 * games.screen.fps, after_death = games.screen.quit) games.screen.add(end_message) class Dropper(games.Sprite): """ An invisible object that drops the rocks. """ def __init___(self, y = 55, speed = 2, odds_change = 200): """ Initialize the Dropper object. """ super(Dropper, self).__init__(x = games.screen.width / 2, y = y, dx = speed) self.odds_change = odds_change self.time_til_drop = 0 def update(self): """ Determines if direction needs to be reversed. """ if self.left < 0 or self.right > games.screen.width: self.dx = -self.dx elif random.randrange(self.odds_change) == 0: self.dx = -self.dx self.check_drop() def check_drop(self): """ Decreases countdown or drop rock and reset countdown. """ if self.time_til_drop > 0: self.time_til_drop -= 1 else: new_rock = Rock(x = self.x) games.screen.add(new_rock) # set buffer to approx 30% of rock height, regardless of pizza speed self.time_til_drop = int(new_rock.height * 1.3 / Rock.speed) + 1 def main(): """ Play the game. """ backround_image = games.load_image("backround.jpg", transparent = False) games.screen.backround = backround_image the_chef = Chef() games.screen.add(the_chef) the_rock = Rock() When creating a new instance of a class, there is an implied 'self' argument, and you supply no others. So you're missing the 'x' argument. It needs to get self & x, and you're only passing self. games.screen.add(the_rock) the_dropper = Dropper() games.screen.add(the_dropper) games.mouse.is_visible = False games.screen.event_grab = True gsmes.screen.mainloop() # start it up main() This is the error. Exception AttributeError: "'Rock' object has no attrib
Re: [Tutor] func-question_y_n.py
Hello Hugo, Mark, Dave, First thank you all greatly, you all have given me food for thought and bytes to chew! I now would like to say please don't take offense at what I say below, however because we are all people and this IS a learning list I would like to give feedback of the last three response I gotten. For Hugo: You have explained stuff clearly to me, that allowed me to learn without making feel like I should already know xyz when I am only beginning. Thank you for this! PLEASE continue this gentle but effective way of teaching. For Dave: As much as you have given me the answers I unfortunately didn't get to learn as much from this information as it felt like I was completely wrong and that I should of know better, this in turn makes people not learn, after all this is a list for learning. I have in a post or two did state that I was very new to python or for that fact any program language. I guess I need to write this in every email I send out. For Mark: Thank you for your answer at the end of your email. If you don't mind me stating for future can you explain things a little more so I may understand the why to your statement "WHy the unneeded parenthesis? What about 'yes'?" Do you mind explaining the unneeded part? I am VERY new to learning programming in general. Sincerely in Christ, Christopher ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] func-question_y_n.py
On 03/15/2013 05:47 PM, Christopher Emery wrote: Hi Mitya, > > Thank for your example of code, however at this time its well over my > head and I think its best if I slowly work on a function that provided > only what I need and then add to it IF it works into it. Yours > appears to do a whole lot more then process a Yes/No from a question > and re-ask the question if the user does not provide a yes or no. > > I will save your code for future use as I understand it more (smile) Ok, sorry if it was too much.. in short, the advantage is that it can accept yes/no but you can also specify any other pattern, e.g. to accept a number or a string that's not shorter or longer than specified, or accept a blank response; it uses regular expressions to match pattern: http://docs.python.org/3.3/library/re.html -m -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] func-question_y_n.py
On 15/03/2013 23:37, Christopher Emery wrote: Hello Hugo, Mark, Dave, For Mark: Thank you for your answer at the end of your email. If you don't mind me stating for future can you explain things a little more so I may understand the why to your statement "WHy the unneeded parenthesis? What about 'yes'?" Do you mind explaining the unneeded part? I am VERY new to learning programming in general. Sincerely in Christ, Christopher Why the unneeded parenthesis? Why bother typing something that isn't needed in Python? To me this is just clutter that further strains my aging eye sight. The following is perfectly valid Python. while answer != "Yes": Why not use it, apart from the fact that it won't match 'yes'? :) -- Cheers. Mark Lawrence ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Script to generate statements
On 15/03/13 19:42, Charles Leviton wrote: Given a list of DBRM members create a JCL which has a series of bind statements for each DBRM. Ah, the joys of JCL. I haven't read a JCL script in about 15 years! :-) This is the tack I took. I have 3 input files a_ contains the fixed part of the JCL b_ contains the template for the bind statement. c_ contains the list of DBRMs Yep, that's fine. This is the script I came up with...Would you critique it and let me know how I could have done it better? #create a series of bind statements fo = open('i:/text/jclout.txt', 'w') fi = open('i:/text/bindjclfirstpart.txt','rU') fibindjclvar = open('i:/text/bindjclvariable.txt','rU') filistofdbrms= open('i:/text/bindjcldbrmlist.txt','rU') varlines =[] You don't need this since the next line initialises the list anyway. Python rarely requires initialising to null values, you can usually initialise to the actual data directly. varlines = fibindjclvar.readlines() for line in fi: #write out all the lines in the first part of JCL fo.write(line) fo.write('\n') varline = '' Again you don't need this since you always initialise varline below. for dbrm in filistofdbrms: fo.write('\n') for index in range(0,9): if varlines[index].find('member') > 0: varline = varlines[index] + '('+ dbrm + ')' + ' -' else: varline = varlines[index] fo.write(varline) fo.close() fi.close() fibindjclvar.close() filistofdbrms.close() And that's all, the rest looks fine to me. PS. Note to Hugo. JCL = Job Control language. Its like a Unix shell script that specifically used to set up a programs runtime environment (how much disk, RAM, CPU it's allowed to consume, start/end times etc etc.) One of the most powerful things about a mainframe that makes them so much more robust than Unix boxes is the fine grained control offered by JCL... HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] func-question_y_n.py
On 15/03/13 23:37, Christopher Emery wrote: so I may understand the why to your statement " > WHy the unneeded parenthesis? Mark was pointing out that parentheses are not needed in a while statement. So why add them? They just add visual clutter. What about 'yes'?" And here he was alluding to the fact that your code requires a capitalised 'Yes', but in practice it should be OK to enter lower case, or even all caps, input too. ie. yes Yes YES should all be valid and yES, yeS and yEs won't be too bad either. The solution is usually to convert input to all lower (or upper) before checking its value. answer = input(question).lower() Now we can test for 'yes' regardless of what combination of case the user actually typed. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Script to generate statements
On 03/15/2013 08:53 PM, Alan Gauld wrote: On 15/03/13 19:42, Charles Leviton wrote: Given a list of DBRM members create a JCL which has a series of bind statements for each DBRM. Ah, the joys of JCL. I haven't read a JCL script in about 15 years! :-) Been over 40 years for me, so I may not remember it too well. PS. Note to Hugo. JCL = Job Control language. Its like a Unix shell script that specifically used to set up a programs runtime environment (how much disk, RAM, CPU it's allowed to consume, start/end times etc etc.) One of the most powerful things about a mainframe that makes them so much more robust than Unix boxes is the fine grained control offered by JCL... You even get to specify how many cylinders a file will occupy, so you don't run out of contiguous space. -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] __init__ argument
On 16/03/13 09:46, Joshua Wilkerson wrote: The program keeps telling me that the __init__ in Rock takes two arguments and only one is given. Ideas? Yes. You need to look at the arguments required when you construct a Rock() instance, and compare it to the arguments actually given. [snip irrelevant code] class Rock(games.Sprite): """ A rock which falls to the ground. """ image = games.load_image("rock.jpg") speed = 1 def __init__(self, x, y = 90): """ Initiate a rock object. """ Here you define the constructor (to be precise: actually the *initialiser*) for a Rock. It takes three arguments, the magic "self" argument that Python automatically provides, x, and an optional y argument. So when you create a Rock instance, the method *requires* two arguments: self and x. Since Python provides the self, you *must* provide an x. So let's see what you do: def main(): """ Play the game. """ [...] the_rock = Rock() You don't provide an x, and so Python complains that it expects two arguments but only receives one (the self argument that it provides for you). Traceback (most recent call last): File "C:\Users\Joshua\Projects\Avalanche\Avalanche.py", line 129, in main() File "C:\Users\Joshua\Projects\Avalanche\Avalanche.py", line 117, in main the_rock = Rock() TypeError: __init__() takes at least 2 arguments (1 given) Notice that the exception tells you exactly *where* the problem is, and *what* the problem is. The only thing you actually need think about about is that, being a method rather than an ordinary function, behind the scenes Python slips in a "self" argument, thus the "1 given" part. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Script to generate statements
On 16/03/13 06:42, Charles Leviton wrote: This is the script I came up with...Would you critique it and let me know how I could have done it better? #create a series of bind statements fo = open('i:/text/jclout.txt', 'w') fi = open('i:/text/bindjclfirstpart.txt','rU') fibindjclvar = open('i:/text/bindjclvariable.txt','rU') filistofdbrms= open('i:/text/bindjcldbrmlist.txt','rU') The comment appears to be irrelevant and/or misleading, although maybe that is just because I don't understand your terminology. You say you create a "series of bind statements", but you don't seem to do anything of the sort. You actually open four files instead. varlines =[] varlines = fibindjclvar.readlines() You don't need to pre-initialise a variable to an empty list before reading lines. for line in fi: #write out all the lines in the first part of JCL fo.write(line) fo.write('\n') varline = '' The above variable name is not helpful. "varline" -- what does it represent? It's very similar to "varlines" defined above, so much so that the first time I read it I thought you had overridden the same variable. Can you think of a more descriptive name for this? Also, again, there's no need to pre-initialise it. for dbrm in filistofdbrms: fo.write('\n') for index in range(0,9): Is this correct? You only care about the first nine lines of the fibindjclvar file? What if it has fewer than nine lines? What if it has more? By the way, it is normal to write that as range(9) rather than range(0, 9). if varlines[index].find('member') > 0: varline = varlines[index] + '('+ dbrm + ')' + ' -' else: varline = varlines[index] fo.write(varline) Since you never use the index except as a way of extracting a line from varlines, perhaps this snippet will be better: for dbrm in filistofdbrms: fo.write('\n') for line in varlines[:9]: # Process only the first 9 lines. if line.find('member') > 0: line += '('+ dbrm + ')' + ' -' fo.write(line) fo.close() fi.close() fibindjclvar.close() filistofdbrms.close() This bit is fine :-) -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Loop Exception Handles
I am trying to loop a simple exception. I tried to put a while loop, but I keep getting syntax issues. I also tried to alternatively use something on the lines of "while number != int" also with no avail. def main(): print("\t\tWelcome to Blackjack!\n") names = [] try: number = games.ask_number("How many players? (1 - 7): ", low = 1, high = 8) except (ValueError, TypeError): print("That is not a number!") number = games.ask_number("How many players? (1 - 7): ", low = 1, high = 8) continue for i in range(number): name = input("Enter player name: ") names.append(name) print()___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Loop Exception Handles
On 16 March 2013 05:08, Vincent Balmori wrote: > I am trying to loop a simple exception. I tried to put a while loop, but I > keep getting syntax issues. I also tried to alternatively use something on > the lines of "while number != int" also with no avail. It would help if you: a) didn't send HTML emails b) actually gave us the error message, as it says a lot about your error other than "syntax error". [snipped code] Since we can't see your games class, nor your error message, we can't really help you. -- best regards, Robert S. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Loop Exception Handles
On 16/03/2013 04:08, Vincent Balmori wrote: I am trying to loop a simple exception. I tried to put a while loop, but I keep getting syntax issues. I also tried to alternatively use something on the lines of "while number != int" also with no avail. Please help us to help you. What did your while loop look like and what were the syntax issues? Tell us precisely what your alternative was and what went wrong, syntax error, value error, power cut, atom bomb dropped? def main(): print("\t\tWelcome to Blackjack!\n") names = [] try: number = games.ask_number("How many players? (1 - 7): ", low = 1, high = 8) except (ValueError, TypeError): print("That is not a number!") number = games.ask_number("How many players? (1 - 7): ", low = 1, high = 8) continue This must be a syntax error as continue is only valid in a loop of some kind. Try (awful I know) something like number = 0 while not number: try: number = games.ask_number("How many players? (1 - 7): ", low = 1, high = 8) except (ValueError, TypeError): print("That is not a number!") for i in range(number): name = input("Enter player name: ") names.append(name) print() Assuming that you get your while loop to work correctly, how many times will the for loop above run if you enter 1? -- Cheers. Mark Lawrence ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor