[Tutor] Using the TIME module to extract a semi-random number
- Original Message - Message: 1 Date: Wed, 16 Sep 2009 23:19:39 -0400 From: Kent Johnson To: Laurii Cc: tutor@python.org Subject: Re: [Tutor] Using the time module to extract a semi-random number Message-ID: <1c2a2c590909162019l364b516cifcd2e0befe2ad...@mail.gmail.com> Content-Type: text/plain; charset=ISO-8859-1 On Wed, Sep 16, 2009 at 6:43 PM, Laurii wrote: The exercise to modify a number guessing program from a fixed number "number = 78" to using the time module and use the seconds at the time the program is used to be the number. (i.e. if the clock on your computer says 7:35:25 then it would take the 25 and place it in "number". time.localtime().tm_sec will give you the number of seconds as an integer without any conversions. Kent -- Message: 2 Date: Thu, 17 Sep 2009 10:50:11 +0200 From: Patrick Sabin To: Tutor@python.org Subject: Re: [Tutor] Using the time module to extract a semi-random number Message-ID: <4ab1f843.1060...@gmail.com> Content-Type: text/plain; charset=ISO-8859-1; format=flowed Laurii wrote: Hello all, I am currently reading through the Tutorial for Non-Programers by Josh Cogliati. I have had great success until now. The exercise to modify a number guessing program from a fixed number "number = 78" to using the time module and use the seconds at the time the program is used to be the number. (i.e. if the clock on your computer says 7:35:25 then it would take the 25 and place it in "number". You can either use: import time number = int(time.strftime("%S")) or use real pseudo-random numbers: import random number = random.randint(0,59) The latter looks clearer to me. Thank you everyone for your help. Even just the examples you have posted have been easier to understand than the python documentation. One last question on the TIME module: Is there one version of these examples that is not portable to other systems? I read something about some functions not working on other systems and I would like to ensure that the programs that I write are completely portable. Thanks again, Katt ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Super class
As I am a beginner I am constantly assimilating new python code and vocabulary associated with it. Could someone please explain to me what a super class is, its importance and what level of python programming it is(beginner,intermediate,advanced programming technique)? This would greatly help me decide whether to try and wrap my brain around it or just skip the message. Thank you in advance, Katt___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] What is Curses and why do they call it that.
Hello all, In my search for ways to change the color of text printed to the screen I came across discussions about curses. Some documentation indicate it as a module that will translate commands to control screen output. Is this right? Also, why do they call it curses? Thanks in advance, Katt ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] First line of a python program
Hello all, Numerous times I see the following as the first line of a python program: #! /usr/bin/python What is this for or do for the program? Thanks in advance, Katt ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Shebang (#!) in the first line of a python script
From: "Mark K. Zanfardino" To: Katt Cc: tutor@python.org Subject: Re: [Tutor] First line of a python program In computing, a shebang (also called a hashbang, hashpling, pound bang, or crunchbang) refers to the characters "#!" when they are the first two characters in a text file. In a Unix-like operating system, the program #! /usr/bin/python If you want to execute this script, you need to run the Python interpreter and tell it to load the script file and run it for you: $ /usr/bin/python myscript You could just set your script to be executable (by setting the right permission bits) and then you can run it as a command without naming python yourself: $ myscript Okay. So if I were to place the following in my Windows XP py v.2.6.2 : $ (name of python script) Then as long as python was in my path I would be able to type the name of the script like a Dos batch file (ex: lowertoupper.py or lowertoupper) instead of having to type python lowertoupper.py? And it will run as normal? Thanks also to Steve W. Thanks in advance, Katt ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Curses - What does it do and why is it called this?
From: Steve Willoughby To: Katt The name is a humorous reference to the "cursor" on the screen which this package controls for the application, moving it around (and curses even Now I understand. Makes sense. If "Curses" is for UNIX what would I use on a Windows XP system using Python 2.6.2? Thanks to all for the help. Being new to python I am confused by some of the vocabulary that is being used. Thanks also to Luke P. and Mark Z. for your responses Katt ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Changing text colors on WinXP py2.6.2
Hello All, Is it possible to change text color on a WinXP system by just using the Ansi escape codes. I have tried, but it just shows the start and end text of the code, but it doesn't change the color. I have tried placing the following before and aft the variable I wish to change: print "\x1B[31;46m",variable,"[0m" print "\033[31;46m",variable,"[0m" In both cases no change has happened. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Shebang (#!) in the first line of a python script
Message: 2 Date: Tue, 13 Oct 2009 06:24:42 -0400 From: Dave Angel To: Alan Gauld Cc: tutor@python.org, Katt Subject: Re: [Tutor] Shebang (#!) in the first line of a python script Message-ID: <4ad4556a.2020...@ieee.org> Content-Type: text/plain; charset=ISO-8859-1; format=flowed Alan Gauld wrote: "Katt" wrote Okay. So if I were to place the following in my Windows XP py v.2.6.2 : $ (name of python script) Then as long as python was in my path I would be able to type the name of the script like a Dos batch file (ex: lowertoupper.py or lowertoupper) instead of having to type python lowertoupper.py? And it will run as normal? The shebang line does nothing on Windows, it is just a comment. Windows uses the file extension so, provided you end the file in .py, you can just type in the name of the script and Windows will use the file association to find the interpreter. As Alan says, the default shells in Windows ignore the shebang line. So unless you have a custom shell installed, you need to understand the Windows pattern. They have another mechanism, which involves two registry entries and an environment variable. The registry entries can easily be manipulated using the utility programs assoc.exe and ftype.exe. However, as long as you have a single Python installation, these are probably already setup for you. If you have more than one Python version installed, you might need to use ftype to switch which one is your default. As long as you're using this mechanism, python.exe does *not* have to be on your PATH. The full path location of python.exe is set up by ftype. You may want your script(s) to be on your PATH of course. The environment variable is used to avoid the need to type the extension. This is *not* set up by default in the Python installation, at least in my experience. But you can easily do it yourself. The environment variable PATHEXT has a list of extensions that it will search for. Mine looks like: PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.PY;.PYW Yours probably doesn't yet have the last two entries, and the others might be somewhat different as well. With .py in this variable, you can type lowertoupper instead of lowertoupper.py DaveA You were right. I did not have .PY/.PYW in my PATHEXT. I have put it in as suggested. I do have python.exe in my path so that should take care of things. Messing around with the windows registry isn't something I want to tackle just yet so I will save that for later. Thank you for your help, Katt ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Changing colors using WinXP py2.6.2
Message: 3 Date: Tue, 13 Oct 2009 11:34:15 +0100 From: Tim Golden Cc: tutor@python.org Subject: Re: [Tutor] Changing text colors on WinXP py2.6.2 Message-ID: <4ad457a7.5030...@timgolden.me.uk> Content-Type: text/plain; charset=ISO-8859-1; format=flowed Katt wrote: Is it possible to change text color on a WinXP system by just using the Ansi escape codes. I have tried, but it just shows the start and end text of the code, but it doesn't change the color. No. ANSI escapes don't work on Windows. Depending on where you want to go, you can look at the win32console module [1] of the pywin32 package [2] or Fredrik Lundh's console [3] module or Chris Gonnerman's wconio [4]. TJG [1] http://timgolden.me.uk/pywin32-docs/win32console.html [2] http://sourceforge.net/projects/pywin32/ [3] http://effbot.org/zone/console-index.htm [4] http://newcenturycomputers.net/projects/wconio.html Thanks Tim G. and Alan G. I will check these four options out. Hopefully they won't be to difficult to incorporate into my beginner level programming :) Thanks to all for your help. It definitely makes a difference having this great support. Katt ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] PyWin32 - Library of functions to interact with windows?
Hello all, I am currently using WinXP and python 2.6.2 I just installed PyWin32 v214 for python 2.6 from the following link: http://sourceforge.net/projects/pywin32/files/pywin32/Build%20214/pywin32-214.win32-py2.6.exe/download Installation seemed to go good as it walked me through while locating my python directory and checking my path. I tried to first to download/save and then run it, but encountered an error and it would not install. When I went back to the link and then clicked "run" instead of save the installation worked. Now I find myself scratching my head and saying to myself: "now what?" Your probably thinking - Dive into the documentation, Search the web, Ask questions. I have looked a bit at the documentation. It definitely seems to believe that I am already a seasoned programmer. Searching the web I have found a lot of general information or overly specific with no way to narrow my search to what I am looking for. I am not sure, but it seems very difficult just to search for a way to change the color of my text. Don't get me wrong. I don't want someone to hand me some code snippet of what I need. I am just looking for an interpreter to translate from computer scientist to beginner. Thus I am hopeful that Asking questions will yield information that I can understand. I am not saying that there is anything wrong with what I have found. I am only saying that my comprehension is not there yet to that level. Looking at the included compiled documentation I think I found what I am looking for. Please let me know if I am incorrect. Searching under "change the color" revealed several topics. I singled out win32gui.SetTextColor. This brought me to the topic "win32api.RGB" and shows the next line as "int = RGB(red,green,blue). Question 1: Did I locate the correct function that I need to use in order to change the color of text within a print ""? Question 2: In order to use this would I just import it? (ie - from win32api import RGB) Question 3: If the above 2 are correct is it just a matter of doing the following: print "The remaining number of apples is: "RGB(red),number_apples The above print statement would yield just the number_apples variable in red text. Thanks in advance, Katt ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Changing the color of text in the windows shell (WinXP/python 2.6.2)
Hello All, Message: 4 Date: Wed, 14 Oct 2009 18:38:31 +0100 From: "Alan Gauld" To: tutor@python.org Subject: Re: [Tutor] PyWin32 - Library of functions to interact with windows? "Katt" wrote Now I find myself scratching my head and saying to myself: "now what?" Good question. Why did you download and install it? Did you have a specific need or did it just seem like a good idea at the time? I installed the pywin32 as to use the color changing capacity. Except for the Pythonwin editor which is far superior to IDLE IMHO. Definitely have a play with that. Actually I am using "Programmer's Notepad" to create my python scripts. HTH, Thanks both to Alan G. and Scott N. and Kent J. for your responses. I think that I will eventually learn all aspects of python programming (if I am lucky). So I will pursue all three types of changing color. First I will try WConio, next to be followed by EasyGUI, and last as Scott has pointed out the more difficult pywin32. Below please find my first basic attempt at using the WConio: code from WConio import textcolor apples_left = 5 print "There are",(textcolor(4)),apples_left,(textcolor(7)),"left in the basket." - The output works, but there is one snag. I think that I am leaving something out because it has the word "None" on both sides of the variable. There are None 5 None left in the basket. I tried both textcolor(4 | 0) and textcolor (4,0). The first has no change and the second has an error: --- Traceback (most recent call last) File "changecolor.py", line 6, in print "There are",(textcolor(4,0)),apples_left,(textcolor(7,0)),"left in the basket." SyntaxError: invalid syntax --- Could someone let me know what I am missing? Thanks in advance, Katt ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Changing the text color in the WinXP dos shell (WinXP/py2.6.2)
Date: Thu, 15 Oct 2009 08:11:11 +0100 From: "Alan Gauld" To: tutor@python.org Subject: Re: [Tutor] Changing the color of text in the windows shell (WinXP/python 2.6.2) Message-ID: "Katt" wrote lucky). So I will pursue all three types of changing color. First I will try WConio, next to be followed by EasyGUI, EasyGUI won;t help change colour, it is just a way of making a command line script act like a GUI - by popping up dialog boxes to capture input and dsplay messages. It replaces raw_input and print with dialogs. Got that. I remeber in the old world of BBS's creating ANSI screens for the WWIV software. This shouldn't be any different just in a different language. code from WConio import textcolor apples_left = 5 print "There are",(textcolor(4)),apples_left,(textcolor(7)),"left in the basket." - The output works, but there is one snag. I think that I am leaving something out because it has the word "None" on both sides of the variable. The textcolor() function returns None. so you need to keep it out of your print statement:. This means you need to split your print into multiple separate statements. (This will also be true for the pywin32 version) print "There are", textcolor(4) print apples_left, textcolor(7) print "left in the basket." The way I'd handle thus is to create a function which takes a list of tuples as input, with each tuple containing the string and its colour: def colorPrint(strings): for string in strings: textcolor(string[1]) print string[0], colorPrint([("There are", 0),(str(apples_left),4),("left in the basket.",7),("\n",0) Thank you for the code snippet. At first when I tried this code it was printing correctly and following up with an error. It was just because the end of the statement was missing the extra ]) at the end. Then after that I was wondering why the phrase "There are" was invisible. Realized that was because the color number was 0. That was very helpful. Thanks again, Katt ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] PyWin32 - Library of functions to interact with windows
Message: 4 Date: Thu, 15 Oct 2009 09:35:30 +0100 From: Tim Golden Cc: tutor@python.org Subject: Re: [Tutor] PyWin32 - Library of functions to interact with windows? Message-ID: <4ad6ded2.5040...@timgolden.me.uk> Content-Type: text/plain; charset=ISO-8859-1; format=flowed Katt wrote: Hello all, I am currently using WinXP and python 2.6.2 I just installed PyWin32 v214 for python 2.6 from the following link: [... snip lots of advice from other people ...] Hi, Katt. Thanks for posting back over here. I must admit, I hadn't realised you were posting to the tutor list when I answered your question originally. (I subscribe to several Python lists and they come into the same mailbox). I rather assumed you were an experienced programmer who just wanted this snippet of win32 info. I'd have been a bit more explanatory if I'd realised. No harm done. No I can't imagine just asking for the code. I mean how would I learn anything. I would rather struggle, then post the code that I was trying and get nudged in the right direction. You learn more from your failures than your successes. It looks like you've got some useful advice from other people which will hopefully take you somewhere, but some more general advice: it's always a good idea to explain what you're trying to Yes, I got some great advice. I also like the fact that everyone tries to point you in the right direction versus just giving you code. That helps me as a beginner in providing me with new exercises which you don't find to much of in the tutorials. Thanks for the advice. I will try to be more verbose in the future in what I am trying to do so I don't come off as an experienced programmer trying to snag some free code. Btw, I am just learning on my own not through any classes. So far I have learned alot from two of the five tutorials that I have read so far(Josh Cogliati's: Non-Programmer's Tutorial for Python and Alan Gauld's: Tutor - May 27, 2007). Good luck and keep posting back here with questions if you have them You bet. When I finish the date reminder program that I am working on I will be asking about working with the EasyGUI and the pywin32. Thanks again, Katt ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Most pythonic input validation
Message: 3 Date: Thu, 15 Oct 2009 16:50:57 +0100 From: Rich Lovely To: Wayne Werner Cc: "tutor@python.org" Subject: Re: [Tutor] Most pythonic input validation Message-ID: Content-Type: text/plain; charset=windows-1252 2009/10/15 Wayne Werner : Hi, I'm writing a text based menu and want to validate the user input. I'm giving the options as integers, and I want to make sure the user enters a proper value. Here's what I've got so far:?http://pastebin.com/m1fdd5863 I'm most interested in this segment: ?? ?while True: ?? ? ? ?choice = raw_input(prompt) ?? ? ? ?if valid_choice(choice, 0, len(options)-1): ?? ? ? ? ? ?break ?? ?return choice Is that the most pythonic way of validating? Is there a better way? As an aside, in the valid_choice function I know I could do: if not choice in range(min, max) but I figured a comparison would probably be the better choice, correct? Thanks, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn?t. - Primo Levi ___ Tutor maillist ?- ?tu...@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor The most pythonic way would be to use a try except block: while True: choice = raw_input(prompt) try: options[int(choice)] except (KeyError, IndexError, TypeError): print "Invalid input, try again." continue return choice Also, did you want to convert choice to an int at some point? You appear to be comparing it to a number in valid_choice(), but it will be passed out of the method as a str. Hence I've added a conversion to int, and I'm catching KeyError (for dicts), IndexError (for lists), and TypeError, for when int(choice) fails. This is a principle called "It's Easier to Ask Forgiveness than Permission" (EAFP), which is one of the pythonic principles. Hope that helps. -- Rich "Roadie Rich" Lovely As I am a new programmer I am specifically trying to pay attention to when you guys discuss making thing more python like. I am a bit confused though on a couple things in this code. Probably since I have not dealt with it as of yet. The first is the while statement. I have made a successful menu selection but my while statement is: while prompt != 0: 0 of course meaning exit. Does "while True:" mean the same? Second is the input statement. Could you not just put choice = int(raw_input(prompt)) instead of using two different statements? Or is it that my example will return as string? The third is the "try" statement. How is this different from the "for" loop or "if" loop? The fourth is except (KeyError, IndexError, TypeError): why do you check for three different types of errors? Thanks in advance, Katt ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Understanding what the code does behind the scenes
Message: 3 Date: Thu, 15 Oct 2009 08:11:11 +0100 From: "Alan Gauld" To: tutor@python.org Subject: Re: [Tutor] Changing the color of text in the windows shell (WinXP/python 2.6.2) Message-ID: Content-Type: text/plain; format=flowed; charset="iso-8859-1"; reply-type=response The textcolor() function returns None. so you need to keep it out of your print statement:. This means you need to split your print into multiple separate statements. (This will also be true for the pywin32 version) print "There are", textcolor(4) print apples_left, textcolor(7) print "left in the basket." The above code is very easy to understand when looking at it, but from what I see of other programmers this would not be as pythonic. The way I'd handle thus is to create a function which takes a list of tuples as input, with each tuple containing the string and its colour: def colorPrint(strings): for string in strings: textcolor(string[1]) print string[0], In the above function please let me know if I am correct in my interpretation. The first line of course would be the defining of the function and puting something in the parenthesis indicates that you will be passing a value to this function. The second line says that for each string in the colorPrint statement check to see what the color code is. The third line says that if it detects a ",#" to change it to a color based on the textcolor function in the WConio module. The fourth line puzzles me though. I think it says that when the textcolor returns the zero that it doesn't print the None? I am not sure though. Could you let me know if I have the right idea? Thanks in advance, Katt ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tutorials and How important is pseudocode
Message: 7 Date: Fri, 16 Oct 2009 13:54:37 +0100 From: "Alan Gauld" To: tutor@python.org Subject: Re: [Tutor] PyWin32 - Library of functions to interact with windows Message-ID: Content-Type: text/plain; format=flowed; charset="iso-8859-1"; reply-type=response "Katt" wrote and Alan Gauld's: Tutor - > May 27, 2007). Oops, thats the old Freenet version. The most recent one(with a few bug fixes etc) is as per my .sig... Thanks Alan G. I got the new version now. I will go back to the beginning and step through it again. Also, out of curiousity what does everyone think of using pseudocode? Once when I was in a programming class the teacher had us first write the program in pseudocode (writing the code in english) before we actually used real code to create the program. Thanks again, Katt ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Testing for empty list
Wayne wrote: Hi, I think I recall seeing this here, but I wanted to make sure I'm correct. Is the best way to test for an empty list just test for the truth value? I.e. mylist = [1,2,3] while mylist: print mylist.pop() Thanks, Wayne My take is simple: Use the above form if you *know* that mylist is in fact a list. If you don't know its type for sure (the name is a clue, but not conclusive ;-) ) then use a more specific test. In your case, you know it's a list, or least something that supports pop(). So your form should be great. DaveA Hello all, Just a newbie question, but when would you test for an empty list? Is it part of a code error detection or an error check to make sure that there is user input? Couldn't you just use something like: while len(mylist) > 0: continue program else: print "mylist is empty or is my lack of python knowledge preventing me from seeing the meaning of the question? Thanks in advance, Katt ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Reading information from a text file into a list of lists (WinXP/py2.6.2)
Hello all, Currently I am working on a program that reads text from a text file. I would like it to place the information int a list and inside the information would have sublists of information. The text file looks like this: "Old Test","2009_10_20" "Current Test","2009_10_25" "Future Test","2009_11_01" I am trying to get the list of lists to look like the following after the information is read from the text file: important_dates = [["Old Test","2009_10_20"],["Current Test",2009_10_25"],["Future Test","2009_11_01"]] What I currently have is: def read_important_dates(): print "\nReading text file into program: important.txt" text_file = open("important.txt", "r") dates = text_file.readlines() text_file.close() print dates # read_important_dates() When it gets to print dates I see the following: [ ' "Old Test","2009_10_20"\n', ' "Current Test",2009_10_25"\n', ' "Future Test","2009_11_01" ' ] Does it look this way because I am using the "print"? Or do I still need to add the inner [ ] and strip out the \n and '? If I add brackets to the text file I am reading from my output looks like this: ['["Old Test","2009_10_20"]\n', '["Current Test",2009_10_25"]\n', '["Future Test","2009_11_01"]'] The program in which I am reading the information into reads a list of lists in which I am trying to simulate when reading from the text file mentioned above. Which acomplishes the in list's brackets, but still leaves the \n and the ' characters. I have tried line.strip() to remove the \n and ' characters, but get the following error: Reading text file into program: important.txt Traceback (most recent call last): File "fileio.py", line 9, in read_important_dates() File "fileio.py", line 6, in read_important_dates line.strip() NameError: global name 'line' is not defined If I try the following to split dates into another list called important_dates I receive a different error: -code-- def read_important_dates(): print "\nReading text file into program: reminders.txt" text_file = open("important", "r") dates = text_file.readlines() text_file.close() important_dates = dates.split() print dates print important_dates # read_important_dates() ----- error--- Reading text file into program: important.txt Traceback (most recent call last): File "fileio.py", line 10, in read_important_dates() File "fileio.py", line 6, in read_important_dates important_dates = dates.split() NameError: 'list' object has no attribute 'split' -- All help is appreciated, Thanks in advance, Katt ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Retrieving information from a plain text file (WinXP/py2.6.2/Beginner)
uot;) #][ Could someone explain to me why my read_reminders function retrieves the information, but cannot process that information? When I try and run the program I get the following error message: Reading text file into program: reminders.txt [['Reminder1,2010_10_15'], ['Reminder2,2010_11_01'], ['Reminder3,2010_11_15']] Traceback (most recent call last): File "reminders.py", line 182, in print reminders NameError: name 'reminders' is not defined Thanks in advance for your help, Katt ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Retrieving information from a plain text file(WinXP/py2.6.2/Beginner)
in to me why my read_reminders function retrieves the information, but cannot process that information? When I try and run the program I get the following error message: Reading text file into program: reminders.txt [['Reminder1,2010_10_15'], ['Reminder2,2010_11_01'], ['Reminder3,2010_11_15']] Traceback (most recent call last): File "reminders.py", line 182, in print reminders NameError: name 'reminders' is not defined Thanks in advance for your help, Katt ___ Tutor maillist - Tutor@python.org #]---[Main Program]---[ reminders = read_reminders() This is the item that I was forgeting. Originally I tried to use the "return" in my function, but left out what I was returning. However if I did not notice this one line I would have continued to be stuck. I guess I thought all you would have to do is call the function and it would know to make the return information into a global list. === It appears you did not return the list of reminders that you extracted in the "read_reminders" function, but simply printed them from inside that function. Yes, originally I did this to find out how python would read the information. Kind of an error check type thing. called "reminders", you should be able to access the list in your global namespace. If I hadn't paid attention to the end of Vince's post I would have not understood this as I am unfamiliar with some of the vocabulary (i.e.: global namespace). Also, on a side note, you can greatly improve the readability of your code by using the triple-quote style for multi-line docstrings inside functions (rather than the hash comment marks). I tend to use hash marks for one-line/inline comments, since they can really become an eyesore (at least IMHO) when used too liberally. Also, Python's whitespace and code formatting conventions can handle a lot of the "documentation" for you. For instance, module imports are typically always performed at the top of a script, so it's reasonable to expect that others reading your code will understand you're importing some modules. Much of this spelled out in PEP's 8 (style guide) and 257 (doc strings): http://www.python.org/dev/peps/pep-0008/ http://www.python.org/dev/peps/pep-0257/ I will make sure to check these out soon so that my comments are more readable. == (Looks like maybe you hijacked another thread, instead of just creating a new message, with new topic, for the list) Sorry, about that. I got lazy and just replied to a tutor message I had in my inbox. Will make sure not to let that happen again. Once you get that sorted out, another bug that's already apparent is that you're trying to split the line on quotes, when it uses commas between fields on each line. Missed that one. Once I changed this everything clicked into place. Thank you Alan G.,Vince S., Serdar T., and Dave A. for your help. I don't think I woud have got this on my own. It is true that sometimes you can't see the answer when it is staring you in the face. Thanks again, Katt ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Change a text string from a list and change it into an integer number.(WinXP/py2.6.2/Beginner)
Hello all, I was wondering if it was possible to split a string that is seperated by the "_" character and changing the text into an integer? My current code is as follows: date = "cyear_11_05" date2 = date.split("_") check_year = date2[0] if check_year == "cyear": year = localtime().tm_year else: year = int(date2[0]) print year So my goal here is for python to check at the value of "date". If the value of "date[0]" is cyear then I want it to get the current year from the computer. If the value of date[0] is a number then I want to just change it into an integer. Currently the above code does not work unless I change the "if" statement to say: "if check_year == "c". Did I do the slice incorrectly? I thought that when you take the first location (0) of a list then it would take the "cyear" in stead of just the "c". All input is appreciated. Thanks in advance, Katt ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tutor Digest, Vol 69, Issue 21 - Change a text string from a list and change it into an integer(WinXP/py2.6.2/Beginner)
First I want to thank the following people for your help: Wayne W., Shashwat A., and Alan G. I appreciate the input/criticism as I continually learn more and more. It seems that I am not sure if I am posting correctly to the right thread and am not sure if it has to do with the fact that I am getting the posts in a Digest manner. Let me know if you have any suggestions. Now back to message at hand: Message: 3 Date: Thu, 5 Nov 2009 21:34:31 -0600 From: Wayne Werner To: Katt Cc: tutor Subject: Re: [Tutor] Change a text string from a list and change it into an integer number.(WinXP/py2.6.2/Beginner) Currently the above code does not work unless I change the "if" statement to say: "if check_year == "c". It works correctly for me. Try modifying your code: date = "cyear_11_05" date2 = date.split("_") check_year = date2[0] print check_year what does that do for you? -Wayne For me it prints to the screen the following : cyear Message: 4 Date: Fri, 6 Nov 2009 09:06:02 +0530 From: Shashwat Anand To: Katt Cc: tutor Subject: Re: [Tutor] Change a text string from a list and change it into an integer number.(WinXP/py2.6.2/Beginner) What do you want to say exactly ? is 'cyear' an integer ? let's say date1 = "1984_11_05" Here cyear is just part of a text string which would be in the following: "cyear_11_05" My goal(which recent I accomplished with the help of Shashwat A.'s function) was: 1. Split the string into a list. [cyear,11,5] 2. If date0 == "cyear" then it would replace cyear with the current year based on the computer's date. Then it would change this information into an integer and return it. 3. If date0 != "cyear" it would then change the number into an integer and return the information. find code that I used below at end of this message. Then of course you can change it to an integer using following list-comprehension, date1 = "1984_11_05" date1_list = [int(i) for i in date1.split("_")] date1_list [1984, 11, 5] or alternatively, date1_list_alternate=map(int,date1.split("_")) date1_list_alternate [1984, 11, 5] I am still learning how to work with list comprehensions so I appreciate the multiple examples using the "for" and "map" choices. also your code seems to work on my system. date = "cyear_11_05" date2 = date.split("_") check_year = date2[0] if check_year == "cyear": year = localtime().tm_year else: year = int(date2[0]) print year Found that I had not imported localtime from time. It worked once I discovered this little oversight. Message: 5 Date: Fri, 6 Nov 2009 09:27:46 +0530 From: Shashwat Anand To: Katt Cc: tutor Subject: Re: [Tutor] Change a text string from a list and change it into an integer number.(WinXP/py2.6.2/Beginner) import time def katt(d): date0 = d.split("_")[0] if date0 == "cyear": return int(time.strftime("%Y")) else: return int(date0) print katt("cyear_11_05") print katt("1984_11_05") http://codepad.org/RBjKmNcA Hope this helps ! Thanks this helps. I actually changed it a little so that I could include it into another function rather than its own seperate function. My code is as follows: if year_check == "cyear": year = int(strftime("%Y")) else: year = int(year_check) if month_check == "cmonth": month = int(strftime("%m")) else: month = int(month_check) I of course made sure to include the strftime in my import calls. I may change the int(strftime("%Y")) for localtime().tm_year because I think I heard it returns the value as an integer, but will have to experiment. Thanks again for the inspiration on this section of code. Thanks again to all. Katt ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor