Re: [Tutor] Running a script in the background
Michael, I see you have several Windows answers, but it doesn't look as though you found quite what you were hoping for on OSX. My suggestion would be to take the script and run it through py2app, which will turn it into a stand-alone application which can then be added to your list of StartUp or LogIn applications. If you never request input or produce output, it will quite happily run in the background with no window and no menu (although by default there will be an icon in the dock). At that point it is so much a background application that the ONLY way you can quit it is via the Force Quit dialog. If you generate status or housekeeping print messages, they will show up in ~/Library/Logfiles. Py2app isn't particularly memory efficient, even a minimal application tends to run close to 9-10 Mbytes, but if it spends most of its time sleeping, it will use very little in the way of system resources. Good luck, Bill Thanks, Bill. That is definitely more of what I am looking for and actually found that through some googling. What I am confused about now, is what's really the difference between py2app and the python Build Applet? -- Michael J. Lewis ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Running a script in the background
Hi everyone, I am sorry to ask this when there are a lot of resources online regarding the subject, but I've spent the past two days trying to figure this out and I don't get it. I have a script that will run forever. Since it runs forever, I don't want to see the interpreter or command line. I want the program to run in the background so I don't see it at all. How can I do this? For some background, my script essentially check every x minutes to see if any files have been updated and then moves them to dropbox. I want to be able to do this on both OSX Mountain Lion and Windows 7. If need be, I can create two separate scripts to separate out the two OS's. Thanks! -- Michael J. Lewis ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Running a script in the background
For windows not sure but for osx just add an after the command. python myscript.py Thanks, but I know about that. I should have been more clear. What I want to do is have the script run in the background without even seeing the terminal. Adding the after the command will let do other things, but the terminal still needs to be open. Once the program is running, I don't want either the terminal or the interpreter displayed. Thanks again. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] re.search() help
Hi everyone, I am a bit confused on how one would ever use re.search(). It essentially tells me the location on (RAM?) if the pattern matches? What is the purpose of this? Can you give me a good example of where it would be useful? Thanks! re.search(*pattern*, *string*, *flags=0*)http://docs.python.org/library/re.html#re.search Scan through *string* looking for a location where the regular expression * pattern* produces a match, and return a corresponding MatchObjecthttp://docs.python.org/library/re.html#re.MatchObject instance. Return None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string. -- Michael J. Lewis mjole...@gmail.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] re.search() help
Message: 6 Date: Sun, 15 Apr 2012 08:48:10 +0100 From: Alan Gauld alan.ga...@btinternet.com To: tutor@python.org Subject: Re: [Tutor] re.search() help Message-ID: jmdufr$478$1...@dough.gmane.org Content-Type: text/plain; charset=ISO-8859-1; format=flowed On 15/04/12 08:10, Michael Lewis wrote: Hi everyone, I am a bit confused on how one would ever use re.search(). It essentially tells me the location on (RAM?) if the pattern matches? No it returns a MatchObject instance. You can then perform various operations on the MatchObject to, for example find the substring which actually matched. What is the purpose of this? So that you can find the section of a long string that first matches your regex. Why not use re.findall() for that? It seems like re.findall() can fill this need and I wouldn't need to use re.search()? Can you compare an example circumstance where one would be better suited than the other? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ -- Michael J. Lewis mjole...@gmail.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Re.findall()
mjole...@gmail.com wrote: Hi everyone, I am having trouble understanding re.findall(). I've read through the documentation and looked at at some examples online, but I still don't have a clear picture. I am going through pythonchallenge.com and I am on challenge 3. I've see. The answer to the problem, but I don't understand the pattern portion of re.findall(). What part don't you understand? Do you understand what a so-called regular expression is? Here's the pattern portion that I don't understand: re.findall([^A-Z]+[A-Z]{3}([a-z])[A-Z]{3}[^A-Z]+ What is going on here? The ^ means to apply this pattern from what I read. The first pattern and last pattern are in opposite order, meaning that it goes from [^A-Z]+[A-Z]{3} to [A-Z]{3}[^A-Z]+ - why does the pattern flip-flop? The first pattern starts as [^A-Z] but the last pattern end with [^A-Z]. Why do I need the + signs? Also, why does this ([a-z]) need the parenthesis? Regular expressions are like super-charged wildcards. In the DOS or Windows command.com or cmd.exe shell, you can use wildcards * and ? to match any characters, or a single character. In Linux and Macintosh shells, you have the same thing only even more so. I am familiar with wildcards, but I've mostly used * and nothing else. Regular expressions are a mini programming language for wildcards. For example, 'a.*z' is a pattern that matches any string starting with the letter 'a' and ending with the letter 'z'. Here's a more complicated example: 'm[aeiou]{1,2}n' This regular expression pattern, or regex, matches the letter 'm', followed by 1 or 2 vowels ('a', 'e', 'i', 'o', or 'u') in a row, followed by 'n'. So it will match moon or mean or moan or man, but not mpg or marvelous or men. You can learn more about regexes here: http://docs.python.org/library/re.html http://docs.python.org/howto/regex.html -- Steven mjole...@gmail.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Running scripts at login
Hi everyone, I am researching how to automatically run some of my scripts after I log into my Windows machine. I don't want to have to manually run the script or setup a windows task. The same way you run any Windows program on startup: Add the script to your startup programme group. What if I want to send the executable to someone and have their machine run the script at startup? Assume I don't have access to their machine to add the script to the startup program group. How can I make that happen? Big difference between your original question ... my Windows machine... and your present query ... access to their machine... This forum doesn't support system crackers. Oh, definitely not my intention - I can see how it came across that way though. For full disclosure, I wrote a script to check for new / move all my girlfriends pictures to dropbox. Nothing malicious intended. My apologies. -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Running scripts at login
On 05/04/12 05:59, Michael Lewis wrote: Hi everyone, I am researching how to automatically run some of my scripts after I log into my Windows machine. I don't want to have to manually run the script or setup a windows task. The same way you run any Windows program on startup: Add the script to your startup programme group. What if I want to send the executable to someone and have their machine run the script at startup? Assume I don't have access to their machine to add the script to the startup program group. How can I make that happen? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Running scripts at login
Hi everyone, I am researching how to automatically run some of my scripts after I log into my Windows machine. I don't want to have to manually run the script or setup a windows task. I'd like to have a piece of code that I can insert into my script that will allow it to run after I login. I found the piece by Alan G.; however, it deals with linux and I can't seem to find a good source for Windows machine: http://mail.python.org/pipermail/tutor/2010-July/077319.html Thanks for the help. -- Michael J. Lewis ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Permissions Error
Message: 1 Date: Mon, 26 Mar 2012 10:52:19 +1100 From: Steven D'Aprano st...@pearwood.info To: tutor@python.org Subject: Re: [Tutor] Permissions Error Message-ID: 4f6fafb3.4060...@pearwood.info Content-Type: text/plain; charset=ISO-8859-1; format=flowed Michael Lewis wrote: Hi everyone, If I've created a folder, why would I receive a permissions error when trying to copy the file. My source code is here: http://pastebin.com/1iX7pGDw The usual answer to why would I receive a permissions error is that you don't actually have permission to access the file. What is the actual error you get? Traceback (most recent call last): File C:\Python27\Utilities\copyfiles.py, line 47, in module copyfiles(srcdir, dstdir) File C:\Python27\Utilities\copyfiles.py, line 42, in copyfiles shutil.copy(srcfile, dstfile) File C:\Python27\lib\shutil.py, line 116, in copy copyfile(src, dst) File C:\Python27\lib\shutil.py, line 81, in copyfile with open(src, 'rb') as fsrc: IOError: [Errno 13] Permission denied: 'C:\\Users\\Chief Ninja\\Pictures\\testdir' I've noticed that the code runs if I use shutil.copyfiles instead of shutil.copy. Do you know why? I've also noticed that if I have a sub-directory, I receive a permission error. However, if I use os.walk, then my code runs if I have a sub-directory in my source directory. My problem then becomes that os.walk doesn't actually move the directory, but instead just moves the files within the sub-directory. Oddly, this code runs without permission error when I use shutil.copy unlike the above piece which raises an error when I use shutil.copy. However, if I use shutil.copyfile, I get the below error: (Do you know why?) Traceback (most recent call last): File C:/Python27/Homework/oswalk.py, line 41, in module copyfiles(srcdir, dstdir) File C:/Python27/Homework/oswalk.py, line 36, in copyfiles shutil.copyfile(srcfile, dstdir) File C:\Python27\lib\shutil.py, line 82, in copyfile with open(dst, 'wb') as fdst: IOError: [Errno 13] Permission denied: 'C:\\newtest' The code where I use os.walk is here: http://pastebin.com/1hchnmM1 When I check the properties/security of the file in question, the system says I have full control. This does not sound like a Python problem, but an operating system problem. What OS are you using? I am using Windows XP You should check the permissions on the folder, not just the file. Also, if you OS supports it, check any extended permissions and ACLs that might apply. Can you copy the file using another language, e.g. using powershell, bash or applescript? Also check that you are running the Python script as the same user you used when creating the file. I've checked the permissions on the folder and I have full control. I haven't yet checked extended permissions and ACL's etc, but will do so. Thanks! -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Error Handling
In the below block, why is the if statement e.errno != errno.EEXIST? Why can the errno be both before and after the .? import os, errno try: os.makedirs('a/b/c') except OSError, e: if e.errno != errno.EEXIST: raise -- Michael J. Lewis mjole...@gmail.com 415.815.7257 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Permissions Error
Hi everyone, If I've created a folder, why would I receive a permissions error when trying to copy the file. My source code is here: http://pastebin.com/1iX7pGDw When I check the properties/security of the file in question, the system says I have full control. Thanks. -- Michael Lewis ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Error handling
Hi everyone, I am having a bit of trouble understanding what is going on below. What does the e in except OSError, e: do? Any other help you can provide regarding errno would be extremely appreciated. I've done help() and dir() on it, but I am not really understanding what's going on with e.errno != errno.EEXIST: Thanks. import os, errno try: os.makedirs('a/b/c') except OSError, e: if e.errno != errno.EEXIST: raise I am in the process of writing a script to move files from one directory to another. I am supplying both the source and destination directories at runtime. I want to create the destination file on the fly; however, if it already exists, I want to handle that error/ignore that error. Also, if the the same file exists in both the source and destination directory, I'd like to override the one in the destination directory with the one in the source directory. I am having trouble with the error handling portion. Here is a pastebin for my source code: http://pastebin.com/EU578xQs ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Error handling
On Sat, Mar 24, 2012 at 3:51 PM, Colton Myers colton.my...@gmail.comwrote: I am having a bit of trouble understanding what is going on below. What does the e in except OSError, e: do? Any other help you can provide regarding errno would be extremely appreciated. I've done help() and dir() on it, but I am not really understanding what's going on with e.errno != errno.EEXIST: Basically, that `except` block is catching all exceptions of type OSError, and storing the exception in variable `e`. This variable does not have to be called `e`, but that's the most commonly-used variable name. Once you have the exception stored (in this case in the variable `e`), you can then see what type of exception, using the `errno` property of the exception. You can read about the different types here: http://docs.python.org/library/errno.html import os, errnotry: os.makedirs('a/b/c')except OSError, e: if e.errno != errno.EEXIST: raise In this particular section, it's catching any OSError, and then if it turns out that the error was File Exists, it is raising that exception again, to be either caught by an encapsulating try block, or which will bring the program to a halt with an exception shown by the interpreter. Is that the behavior you are going for? Any more confusion? Why wouldn't it be errno.e instead of e.errno? -- Colton Myers -- Michael J. Lewis mjole...@gmail.com 415.815.7257 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] question on self
Why do I have to use self.example when calling a method inside a class? For example: def Play(self): '''find scores, reports winners''' self.scores = [] for player in range(self.players): print print 'Player', player + 1 self.scores.append(self.TakeTurns()) I have another method called take turns (not shown for brevity purposes). When I want to call it, why can't I just call it like a function and use TakeTurns() instead of self.TakeTurns()? -- Michael J. Lewis ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Recognizing real numbers (bob gailer)
Hi everyone, I have some code where I import a file to use a module. That module that I import takes text and a multiplier, checks for any numbers in that text and will then multiply those numbers by the given multiplier. The imported module is below. I am getting the text from a file that I have which starts out as: .5 lb. butter 1.75 Cups Graham Cracker Crumbs 2.0 Cups Powder Sugar 1.0 Cups Peanut Butter 2.0 Cups Semi-sweet Chocolate Chips It seems that the .isdigit() function that I use doesn't recognize the .5 as a number and therefore doesn't multiply it. How can I get my code to recognize numbers such as .5, 1.75 as numbers? Wow - the requirements just changed. Up tilll now we were dealing with multiplying each digit. Now we have to parse out a string that represents a number with decimal places! I hope that we don't raise the oven temperature in the process. Well - this is part of my homework and the first question dealt with only multiplying each digit. the second part of the homework then asked to write a file that imported the file from the previous homework portion and utilized the multiplication function in that file. No oven temperature changes...I promise. Is it true that the number to multiply is always at the beginning of a line? If so that makes the job a lot easier. It's not true. The number can be anywhere in the text. Imported module: def MultiplyText(text, multiplier): '''Recieve a S int. For digits in S, multiply by multiplier and return updated S.''' return ' '.join(str(float(num) * multiplier) if num.isdigit() else num for num in text) Module doing the importing/opening/reading/creating a new file import Homework5_1 as multiply def DoubleDigits(file_name): '''Open file/read file/write new file that doubles all int's in the read file''' try: read_file = open(file_name) except IOError: return 'No such file.' new_file_name = file_name + '2' try: write_file = open(new_file_name, 'w') except IOError: read_file.close() return 'No such file to write to.' for line in read_file: new_line = line.split() new_line = ''.join(multiply.MultiplyText(new_line, 2)) write_file.write(new_line + '\n') read_file.close() write_file.close() def main(): DoubleDigits(raw_input('What file do you want to open? ')) if '__name__' == '__main__': print main() Output that is written to my file: Peanut Butter Bars Ingredients .5 lb. butter 1.75 Cups Graham Cracker Crumbs 4.0 Cups Powder Sugar 2.0 Cups Peanut Butter 4.0 Cups Semi-sweet Chocolate Chips Melt butter. Add graham cracker crumbs, peanut butter and sugar. Mix well and pat into sheet pan. Cover with melted chocolate. Refrigerate until semi-firm, then cut into squares. -- Michael J. Lewis ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Recognizing real numbers
On Wed, Feb 22, 2012 at 2:52 PM, Dave Angel d...@davea.name wrote: On 02/21/2012 10:00 PM, Michael Lewis wrote: Hi everyone, I have some code where I import a file to use a module. That module that I import takes text and a multiplier, checks for any numbers in that text and will then multiply those numbers by the given multiplier. The imported module is below. I am getting the text from a file that I have which starts out as: .5 lb. butter 1.75 Cups Graham Cracker Crumbs 2.0 Cups Powder Sugar 1.0 Cups Peanut Butter 2.0 Cups Semi-sweet Chocolate Chips It seems that the .isdigit() function that I use doesn't recognize the .5 as a number and therefore doesn't multiply it. How can I get my code to recognize numbers such as .5, 1.75 as numbers? Imported module: def MultiplyText(text, multiplier): '''Recieve a S int. For digits in S, multiply by multiplier and return updated S.''' return ' '.join(str(float(num) * multiplier) if num.isdigit() else num for num in text) Somehow, every other time I read that code I missed the for num in text phrase that was wrapped around by the mail. No worries - this list has been crazy helpful to me. I'm apologizing for my earlier remarks stating that this function would not work. i would clean up the variable names (text is a list, and num is a string), and the function comment states that you're multiplying individual digits). But since it works, it's a good base to start with for your floating point question. Easiest answer is to write a function that does check if a string is a valid float, the same as num.isdigit() (lousy names also occur in the standard library) does for int. The new function would be easiest to write with a try/except form. Take a string as a formal parameter, try to float() it in a try block, and if it succeeds, return True. It'd be convenient if there were such a method in str, but since there isn't, you'd have to change num.isdigit() to isfloat(num). Have you gotten to try/except in your class yet? We have. I actually have a function written in my imported file to check if a string is a valid float, but I didn't use it because I also have raw_input in that same function, which I don't want. I'll rework the imported function to remove the raw_input and put that in a function by itself so I can utilize the valid float try/except that I've already written. -- DaveA -- Michael J. Lewis mjole...@gmail.com 415.815.7257 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Compiled Python File
First, thanks to everyone who helped me out regarding my Recognizing real numbers post. I gained a lot of knowledge over the past two days! I've noticed that after I execute some of my .py files, a Compiled Python File is automatically saved to my directory. This doesn't happen for every file that I execute though. Why is that? Thanks! -- Michael J. Lewis ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Writing to a file/changing the file name
Hi everyone, I have a program where I open a file (recipe.txt), I read that file and write it to another file. I am doing some multiplying of numbers in between; however, my question is, when I name the file I am writing to, the file extension is changed, but the file name is not. What am I doing wrong? Code: import Homework5_1 as multiply def MultiplyNumbersInFile(file_name, multiplier): '''Open file/read file/write new file that doubles all int's in the read file''' try: read_file = open(file_name) except IOError: print I can't find file: , file_name return new_file_name = file_name + '2' try: write_file = open(new_file_name, 'w') except IOError: read_file.close() print I can't open file: , new_file_name return for line in read_file: new_line = line.split() new_line = ''.join(multiply.MultiplyText(new_line, multiplier)) write_file.write(new_line + '\n') read_file.close() write_file.close() def main(): file_name = raw_input('What file do you want to open? ') multiplier = multiply.GetUserNumber() MultiplyNumbersInFile(file_name, multiplier) if __name__ == '__main__': main() What I am doing in IDLE: What file do you want to open? recipe.txt Enter a multiplier: 2 The file that is actually created in my directory is still named recipe; however, the file type is now TXT2 File. How do I make it so I am updating the file name to recipe2 instead of the file type? -- Michael J. Lewis ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Recognizing real numbers
Hi everyone, I have some code where I import a file to use a module. That module that I import takes text and a multiplier, checks for any numbers in that text and will then multiply those numbers by the given multiplier. The imported module is below. I am getting the text from a file that I have which starts out as: .5 lb. butter 1.75 Cups Graham Cracker Crumbs 2.0 Cups Powder Sugar 1.0 Cups Peanut Butter 2.0 Cups Semi-sweet Chocolate Chips It seems that the .isdigit() function that I use doesn't recognize the .5 as a number and therefore doesn't multiply it. How can I get my code to recognize numbers such as .5, 1.75 as numbers? Imported module: def MultiplyText(text, multiplier): '''Recieve a S int. For digits in S, multiply by multiplier and return updated S.''' return ' '.join(str(float(num) * multiplier) if num.isdigit() else num for num in text) Module doing the importing/opening/reading/creating a new file import Homework5_1 as multiply def DoubleDigits(file_name): '''Open file/read file/write new file that doubles all int's in the read file''' try: read_file = open(file_name) except IOError: return 'No such file.' new_file_name = file_name + '2' try: write_file = open(new_file_name, 'w') except IOError: read_file.close() return 'No such file to write to.' for line in read_file: new_line = line.split() new_line = ''.join(multiply.MultiplyText(new_line, 2)) write_file.write(new_line + '\n') read_file.close() write_file.close() def main(): DoubleDigits(raw_input('What file do you want to open? ')) if '__name__' == '__main__': print main() Output that is written to my file: Peanut Butter Bars Ingredients .5 lb. butter 1.75 Cups Graham Cracker Crumbs 4.0 Cups Powder Sugar 2.0 Cups Peanut Butter 4.0 Cups Semi-sweet Chocolate Chips Melt butter. Add graham cracker crumbs, peanut butter and sugar. Mix well and pat into sheet pan. Cover with melted chocolate. Refrigerate until semi-firm, then cut into squares. -- Michael J. Lewis ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] __name__=='__main__'
Hi everyone, I am having some trouble understanding how to use __name__== '__main__'. Can you please give me some insight? Also, to use this, it needs to be within a function? Do you typically just throw it in your very last function or create a separate function just for this? I at first put it outside and after all my functions but got the error below and then put it inside my last function and the program ran. (side note, I have an error in my return for MultiplyText that I am still trying to work out, so you can ignore that part). Code: '''homework 5_1''' def MultiplyText(text, multiplier): '''Recieve a S. For digits in S, multiply by multiplier and return updated S.''' for num in text: return ''.join(str(int(num) * multiplier) if num.isdigit() else num for num in text) def GetUserInput(): '''Get S multiplier. Test multiplier.isdigit(). Call MultiplyText(text, multiplier)''' while True: text = raw_input('Enter some text: ') multiplier = raw_input('Enter a multiplier: ') try: multiplier.isdigit() break except ValueError: continue new_text = MultiplyText(text, multiplier) return new_text if __name == '__main__': print GetUserInput() Error I got when __name == ' __main__' was outside of any function: Traceback (most recent call last): File C:/Python27/Homework/Homework5_1.py, line 24, in module if __name == '__main__': NameError: name '__name' is not defined -- Michael J. Lewis ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tutor Digest, Vol 96, Issue 83
On Mon, Feb 20, 2012 at 6:46 PM, Michael Lewis mjole...@gmail.com wrote: I at first put it outside and after all my functions but got the error below That's the right place for it, you just spelled it wrong. and then put it inside my last function and the program ran. That's not the right place for it. Your program ran, but only because nothing ever called your GetUserInput() function any more. Now I am confused. I fixed the spelling and put it outside all my functions; however, the code now runs WITHOUT me explicitly importing it. def MultiplyText(text, multiplier): '''Recieve a S int. For digits in S, multiply by multiplier and return updated S.''' return ' '.join(str(int(num) * multiplier) if num.isdigit() else num for num in text) def GetUserInput(): '''Get S multiplier. Test multiplier.isdigit(). Call MultiplyText(text, multiplier)''' text = raw_input('Enter some text: ') while True: multiplier = raw_input('Enter a multiplier: ') try: multiplier = int(multiplier) break except ValueError: continue return MultiplyText(text.split(), multiplier) if __name__ == '__main__': GetUserInput() Traceback (most recent call last): ? File C:/Python27/Homework/Homework5_1.py, line 24, in module ? ? if __name == '__main__': NameError: name '__name' is not defined It needs to be spelled __name__ -- that's two underscores on each side. -- Jerry ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] __name__=='__main__'
Thanks. I did end up catching those, but to be fair to all the others, I did ask that they ignore that issue as I was still working through it on my own. On Mon, Feb 20, 2012 at 4:55 PM, bob gailer bgai...@gmail.com wrote: No one else has caught another problem. I comment on it below: On 2/20/2012 6:46 PM, Michael Lewis wrote: Hi everyone, I am having some trouble understanding how to use __name__== '__main__'. Can you please give me some insight? Also, to use this, it needs to be within a function? Do you typically just throw it in your very last function or create a separate function just for this? I at first put it outside and after all my functions but got the error below and then put it inside my last function and the program ran. (side note, I have an error in my return for MultiplyText that I am still trying to work out, so you can ignore that part). Code: '''homework 5_1''' def MultiplyText(text, multiplier): '''Recieve a S. For digits in S, multiply by multiplier and return updated S.''' for num in text: return ''.join(str(int(num) * multiplier) if num.isdigit() else num for num in text) This will fail, as multiplier is a string. def GetUserInput(): '''Get S multiplier. Test multiplier.isdigit(). Call MultiplyText(text, multiplier)''' while True: text = raw_input('Enter some text: ') multiplier = raw_input('Enter a multiplier: ') try: multiplier.isdigit() multiplier.isdigit() returns True or False. It will not raise an exception! break except ValueError: continue new_text = MultiplyText(text, multiplier) return new_text if __name == '__main__': print GetUserInput() To fix both problems replace multiplier.isdigit() with multiplier = int(multiplier) -- Bob Gailer 919-636-4239 Chapel Hill NC -- Michael J. Lewis mjole...@gmail.com 415.815.7257 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] __name__=='__main__'
Now that I am better understanding '__name__'=='__main__', I need to get advice on one last part. Since you put this in the file as an if statement, some instruction must come after. What do you suggest putting after this statement/is that piece of code ever put into action? In my example below, I've done a few tests like putting a print statement under '__name__'=='__main__' and it isn't printed. I am not sure what to put in this code block. def MultiplyText(text, multiplier): '''Recieve a S int. For digits in S, multiply by multiplier and return updated S.''' return ' '.join(str(int(num) * multiplier) if num.isdigit() else num for num in text) def GetUserInput(): '''Get S multiplier. Test multiplier.isdigit(). Call MultiplyText(text, multiplier)''' text = raw_input('Enter some text: ') while True: multiplier = raw_input('Enter a multiplier: ') try: multiplier = int(multiplier) break except ValueError: continue return MultiplyText(text.split(), multiplier) if '__name__' == '__main__': GetUserInput() ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] '__name__' == '__main__'
I am back to being confused. I just tried running the module without first importing it, and it worked just fine. How do I do this properly to where the module only runs if I import it? Code: def MultiplyText(text, multiplier): '''Recieve a S int. For digits in S, multiply by multiplier and return updated S.''' return ' '.join(str(int(num) * multiplier) if num.isdigit() else num for num in text) def GetUserInput(): '''Get S multiplier. Test multiplier.isdigit(). Call MultiplyText(text, multiplier)''' text = raw_input('Enter some text: ') while True: multiplier = raw_input('Enter a multiplier: ') try: multiplier = int(multiplier) break except ValueError: continue return MultiplyText(text.split(), multiplier) if __name__ == '__main__': GetUserInput() What I did in IDLE: GetUserInput() Enter some text: 4 times Enter a multiplier: 2 '8 times' -- Michael J. Lewis mjole...@gmail.com 415.815.7257 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] tabbed output
I am having a weird issue. I have a print statement that will give me multiple outputs separated by a tab; however, sometimes there is a tab between the output and sometimes there is not. It seems sort of sporadic. My code is below and two sample outputs are below that (one that works how I expect, and the other showing the issue (tab separation not occurring between all pieces of the output) What is going on? def CheckNames(): names = [] for loop in range(1,4): while True: name = raw_input('''Name #%s: ''' %(loop)) if name not in names: names.append(name) break print '%s is already in the data. Try again.' %(name) sorted_names = sorted(names) for element in list(sorted_names): print 'Hurray for %s!\t' %(element), Sample Output1: Name #1: mike Name #2: bret Name #3: adam Hurray for adam!Hurray for bret! Hurray for mike! Sample Output2(there is a tab between output 2 3, but not 1 2): Name #1: abe Name #2: alan Name #3: adam Hurray for abe! Hurray for adam! Hurray for alan! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] repeat a sequence in range
I am trying to repeat a certain sequence in a range if a certain even occurs. Forgive me for not pasting my code; but I am not at the machine where it's saved. Basically, I want to get user input and append that input to a list only if the input is not already in the list. I want to do this x amount of times, but if the user input is already in the list, then I want to repeat that step in range(x). At the prompt, I want to ask the user for: Name 1: Name 2: Name 3: etc but if the user input for Name 3 was the same as the user input for Name 2, then I want to ask the user again for Name 3 instead of continuing to Name 4. How can I do this? -- Michael J. Lewis mjole...@gmail.com 415.815.7257 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Character Buffer Object Error
On Thu, Feb 9, 2012 at 2:43 PM, bob gailer bgai...@gmail.com wrote: Always reply-all so a copy goes to the tutor list. On 2/8/2012 11:04 PM, Michael Lewis wrote: Thanks Bob, Thanks for what if you did not follow my suggestions? I partially followed your suggestions by getting rid of str.replace(old, new[, count]) and new_output = ' '.join(user_input). But I also wanted to try to get this to work without simply copying your code. Your code is still pretty buggy. I don't think I made my intentions clear. I don't wont to increment each digit. I want to find each number (for example, if the str contains 436, I don't want to interpret that as 4, 3, 6 - I instead want to interpret that as 436, which is why I created a list and then joined back into a string afterwards. Please test it by running it, seeing that the result is not correct, then try the desk checking. I don't see how this is not correct, because my input was I got 432 when I counted, but Jim got 433 which is a lot for only 6 cats, or were there 12 cats? And my output was: I got 433 when I counted, but Jim got 434 which is a lot for only 7 cats, or were there 13 cats? The below code is what I came up with without using your suggestion. On a scale, how novice is mine compared to what you offered? I am curious because I want to know if I should have come up with your solution instead of what I did come up with. def AlterInput(user_input): '''search for nums in str and increment/append, return new string''' new_output = [] for num in user_input: if not num.isdigit(): new_output.append(num) else: num.isdigit() new_num = int(num) new_num += 1 new_output.append(str(new_num)) return ' '.join(new_output) def GetUserInput(): '''Get a string from the user and pass it''' user_input = '''I * got 432 when I counted, but Jim got 433 which is a lot for only 6 cats, or were there 12 cats?''' return AlterInput(user_input.split()) Your code: return ' '.join(str(int(num)+1) if num.isdigit() else num for num in user_input) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tutor Digest, Vol 96, Issue 26
On Tue, Feb 7, 2012 at 10:57 AM, tutor-requ...@python.org wrote: Send Tutor mailing list submissions to tutor@python.org To subscribe or unsubscribe via the World Wide Web, visit http://mail.python.org/mailman/listinfo/tutor or, via email, send a message with subject or body 'help' to tutor-requ...@python.org You can reach the person managing the list at tutor-ow...@python.org When replying, please edit your Subject line so it is more specific than Re: Contents of Tutor digest... Today's Topics: 1. Re: Backspace Escape Sequence; \b (Peter Otten) 2. Re: Backspace Escape Sequence; \b (Steven D'Aprano) 3. Re: Question on how to do exponents (Alan Gauld) 4. Re: Question on how to do exponents (Steven D'Aprano) 5. Re: Backspace Escape Sequence; \b (Alan Gauld) 6. (no subject) (Debashish Saha) 7. confusion with else command (Debashish Saha) 8. Re: Question on how to do exponents (Sarma Tangirala) -- Message: 1 Date: Tue, 07 Feb 2012 18:41:12 +0100 From: Peter Otten __pete...@web.de To: tutor@python.org Subject: Re: [Tutor] Backspace Escape Sequence; \b Message-ID: jgrnmj$g41$1...@dough.gmane.org Content-Type: text/plain; charset=ISO-8859-1 Garland W. Binns wrote: Could someone please tell me a common or semi-frequent scenario in which a person would use a backspace escape sequence? Does $ python -c 'print this is b\bbo\bol\bld\bd' | less qualify? If you are using (e. g.) Linux this technique is used to show some text in boldface when you type something like help(str) in Python's interactive interpreter. -- Message: 2 Date: Wed, 08 Feb 2012 05:18:35 +1100 From: Steven D'Aprano st...@pearwood.info To: tutor@python.org Subject: Re: [Tutor] Backspace Escape Sequence; \b Message-ID: 4f316afb.7040...@pearwood.info Content-Type: text/plain; charset=ISO-8859-1; format=flowed Peter Otten wrote: Garland W. Binns wrote: Could someone please tell me a common or semi-frequent scenario in which a person would use a backspace escape sequence? Does $ python -c 'print this is b\bbo\bol\bld\bd' | less qualify? If you are using (e. g.) Linux this technique is used to show some text in boldface Gah, that has got to be the ugliest hack in the universe. I don't think that is guaranteed to work everywhere. less supports the \b trick, but the Python interactive interpreter doesn't support it directly. -- Steven -- Message: 3 Date: Tue, 07 Feb 2012 18:29:49 + From: Alan Gauld alan.ga...@btinternet.com To: tutor@python.org Subject: Re: [Tutor] Question on how to do exponents Message-ID: jgrqit$80s$1...@dough.gmane.org Content-Type: text/plain; charset=ISO-8859-1; format=flowed On 07/02/12 16:54, Sarma Tangirala wrote: Is is better to use pow() against **? I suspect ** will be faster since it doesn't have the function call overhead. But I haven't tried timing it. Feel free to do some tests and find out. Let us know how you get on! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ -- Message: 4 Date: Wed, 08 Feb 2012 05:31:07 +1100 From: Steven D'Aprano st...@pearwood.info To: tutor@python.org Subject: Re: [Tutor] Question on how to do exponents Message-ID: 4f316deb.3070...@pearwood.info Content-Type: text/plain; charset=ISO-8859-1; format=flowed Sarma Tangirala wrote: Is is better to use pow() against **? Advantages of ** - it is shorter to type x**y vs pow(x, y) - being an operator, it is slightly faster than calling a function - you can't monkey-patch it Disadvantages of ** - being an operator, you can't directly use it as a function-object - it can't take three arguments - hard to google for ** - you can't monkey-patch it Advantages of pow() - it is a function, so you can pass it around as an object - three argument form - easy to call help(pow) to see documentation - easy to google for pow - can be monkey-patched Disadvantages of pow() - a tiny bit slower due to the function call - slightly longer to type - can be monkey-patched Weigh up the advantages and disadvantages of each, and make the call which is better for you. (My preference is to use the ** operator.) -- Steven -- Message: 5 Date: Tue, 07 Feb 2012 18:42:09 + From: Alan Gauld alan.ga...@btinternet.com To: tutor@python.org Subject: Re: [Tutor] Backspace Escape Sequence; \b Message-ID: jgrra2$ec8$1...@dough.gmane.org Content-Type: text/plain; charset=UTF-8; format=flowed On 07/02/12 17:19, Garland W. Binns wrote: Could someone please tell me a common or semi-frequent scenario in which a person would use a backspace escape sequence? Do you mean backspace specifically or do you really mean backslash? In other words
[Tutor] Character Buffer Object Error
I want to find all digits in a string and then increment those digits by 1 and then return the same string with the incremented digits. I've tried the following code, but I am getting the following error. How do I do this properly? def AlterInput(user_input): print user_input new_output = '' for index, char in enumerate(user_input): if char.isdigit(): new_char = int(char) new_char += 1 new_output = ' '.join(user_input) new_output.replace(char, new_char) print new_output def GetUserInput(): '''Get a string from the user and pass it''' user_input = '''I got 432 when I counted, but Jim got 433 which is a lot for only 6 cats, or were there 12 cats?''' AlterInput(user_input.split()) Traceback (most recent call last): File C:/Python27/Homework/Homework 4_1.py, line 25, in module GetUserInput() File C:/Python27/Homework/Homework 4_1.py, line 23, in GetUserInput AlterInput(user_input.split()) File C:/Python27/Homework/Homework 4_1.py, line 15, in AlterInput new_output.replace(char, new_char) TypeError: expected a character buffer object Thanks. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Lists/raw_input
I want to prompt the user only once to enter 5 numbers. I then want to create a list out of those five numbers. How can I do that? I know how to do it if I prompt the user 5 different times, but I only want to prompt the user once. Thanks. -- Michael ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Importing libraries
Why don't I have to import str or list to access their attributes like I do with the math or random or any other library? -- Michael J. Lewis mjole...@gmail.com 415.815.7257 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] ASCII Conversion
I am trying to do a simple test but am not sure how to get around ASCII conversion of characters. I want to pass in y have the function test to see if y is an integer and print out a value if that integer satisfies the if statement. However, if I pass in a string, it's converted to ASCII and will still satisfy the if statement and print out value. How do I ensure that a string is caught as a ValueError instead of being converted? def TestY(y): try: y = int(y) except ValueError: pass if y -1 or y 1: value = 82 print value else: pass -- Michael J. Lewis mjole...@gmail.com 415.815.7257 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Rounding Error
I am trying to round a float to two decimals, but I am getting the following error: Traceback (most recent call last): File pyshell#23, line 1, in module PaintingProject() File C:/Python27/Homework/Labs/Lab 03_5.py, line 42, in PaintingProject print 'That will cost you $%f.' %(round(5.6523),2) TypeError: not all arguments converted during string formatting Basically, I am writing a program to ask a user how many square feet they need to paint. I then calculate how many cans of paint they need and will also show the total purchase price. I've tried this two ways, and the first way I am semi-successful meaning that my output is rounding but it displays a number of zero's after the number rounds. The second way, I am getting the error mentioned above. What am I doing wrong? How can I do this better? (note, for the sake of brevity, I only show the code in question and not the whole program). total = PRICE_PER_CAN * cans + (PRICE_PER_CAN * cans * TAX) total = round(total,2) print 'For %d square feet, you\'ll need %d cans of paint.' %(square_feet, cans) print 'That will cost you $%f.' %(total) total = PRICE_PER_CAN * cans + (PRICE_PER_CAN * cans * TAX) print 'For %d square feet, you\'ll need %d cans of paint.' %(square_feet, cans) print 'That will cost you $%f.' %(round(total),2) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Rounding Error
Update I am trying to round a float to two decimals. Basically, I am writing a program to ask a user how many square feet they need to paint. I then calculate how many cans of paint they need and will also show the total purchase price. I've tried this two ways, and both ways I am semi-successful meaning that my output is rounding but it displays a number of zero's after the number rounds. How can I make the zero's stop displaying? total = PRICE_PER_CAN * cans + (PRICE_PER_CAN * cans * TAX) total = round(total,2) print 'For %d square feet, you\'ll need %d cans of paint.' %(square_feet, cans) print 'That will cost you $%f.' %(total) total = PRICE_PER_CAN * cans + (PRICE_PER_CAN * cans * TAX) print 'For %d square feet, you\'ll need %d cans of paint.' %(square_feet, cans) print 'That will cost you $%f.' %round(total,2) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Error Checking/Defensive Programming
Hi everyone, I am new to python and have a noob question. Is it generally better to use try/except/else statements or if/elif/else? Or, is there a time and place for each? For a simple example, assume I want a user to enter a number 1) try: number = float(input('enter a number: ') except ValueError: print('enter a number.') else: print('you entered a number') *OR* * * 2) number = float(input('enter a number: ') if number =0 or 0: print('you entered a number') else: print('enter a number.') Thanks for the help. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor