Re: [Tutor] Meaning of %g ?
>> in Python. I must do some tests with gcc to see what it does >> with %g, it may be the wierd behaviour is coming from there. Tried it and get the same behaviour. Tried the Borland C++ compiler and got the same behaviour. Tried my MIX K&R compiler and - it didn't work! - it's a pure DOS application and XP barfed... Oh well! So it looks like Python is consistent with the norm for C compilers on PCs at least. I tried looking up the ANSI standard to see what it said but couldn't find a clear statement there either. And finally, the most precise statement seemed to come from the Linux printf man page: -- The double argument is converted in style f or e (or F or E for G conversions). The precision specifies the number of significant digits. If the precision is missing, 6 digits are given; if the precision is zero, it is treated as 1. Style e is used if the exponent from its conversion is less than -4 or greater than or equal to the precision. Trailing zeros are removed from the fractional part of the result; a decimal point appears only if it is followed by at least one digit. - At this point I'll setytle for Python doing the "normal" thing with %g but for me not to use it because I can't see that behaviour being very useful! Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Raw Bits! (Control characters ahoy!)
Hi Doug, Have you looked at the struct module which provides tools for encoding binary values into byte streams and decoding byte streams into binary data. However if you only need to inject some hex codes into a string you can use the chr() function, this works even for unprintable characters like control sequences. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld - Original Message - From: "doug shawhan" <[EMAIL PROTECTED]> To: Sent: Monday, April 17, 2006 10:40 PM Subject: [Tutor] Raw Bits! (Control characters ahoy!) I am in the middle of a project that requires me to send and retrieve information from a machine connected to a serial port. My problems are these: 1. I cannot send control characters 2. I cannot read data streaming from the serial port I have been doing fine with: os.system("echo '5' >/dev/tty00") os.system("echo '8' >/dev/tty00") and the like to the remote machine, but I need to be able to send control characters the same way to scroll through menus. I have tried pyserial and pexpect with mixed (mostly horrible) results (not the fault of the module builders!), thus far the simple act of echoing the strings to the serial port is the only reliable method I have found. Reading from the serial port has also been problematic. I find that simply opening the port /dev/tty00 file and using readlines(), read() or whatever gives me empty strings or lists. Pbth. So first: how should I go about adding the hex escape sequences (\x0a and \x50) to the above strings in their raw form? second: what method should I use to read a raw stream from the serial port for a given period? I have looked carefully at the neat and tidy miniterm.py example in the pyserial examples directory, and see how one can continuously read via a thread from the port, but have not been able to replicate it thus far. Any help whatsoever would be great! I'm beginning to feel a little lightheaded. Thanks! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Alan Gauld Tutorial - OOP
Hi, I am reading Alan's tut and have stuck on the OOP chapter. What does he mean by, | Objects are collections of data and functions that operate on that |data. These are bound together so that you can pass an object from one |part of your program and they automatically get access to not only the |data attributes but the operations that are available too. What are exactly "data attributes" and what "operations" is he referring to? With warm regards, -Payal ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] functions in Python
On Mon, Apr 17, 2006 at 10:31:04AM -0700, Danny Yoo wrote: > One view that's common is the idea that a function is a box that takes > an input and returns an output: Thanks a lot for the detailed help. Well, I have now got atleast basics of functions, will be doing some more reading on it in next few days. Thanks again. With warm regards, -Payal ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] My Name is John and I copy and paste
Hi, Thanks for all the help so far on my database questions. I have now developed a program that reads in info from a csv file and updates already existing records in my database. I have enclosed the code below. The good news is that it is working. However, I used copy and paste and amended the text to write the code and it seems rather longwinded. Is there a quicker/better way to write the code below? path = "c:/test/import.csv" import mx.ODBC import mx.ODBC.Windows import csv reader = csv.reader(open(path,"rb")) for row in reader: db = mx.ODBC.Windows.DriverConnect('DSN=vfp') c = db.cursor() c.execute('UPDATE cost_grid SET cost_1 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[3]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET rrp_1 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[4]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET ie_rrp_1 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[5]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET cost_2 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[6]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET rrp_2 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[7]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET ie_rrp_2 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[8]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET cost_3 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[9]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET rrp_3 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[10]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET ie_rrp_3 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[11]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET cost_4 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[12]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET rrp_4 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[13]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET ie_rrp_4 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[14]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET cost_5 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[15]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET rrp_5 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[16]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET ie_rrp_5 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[17]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET cost_6 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[18]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET rrp_6 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[19]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET ie_rrp_6 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[20]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET cost_7 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[21]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET rrp_7 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[22]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET ie_rrp_7 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[23]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET cost_8 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[24]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET rrp_8 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[25]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET ie_rrp_8 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[26]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET cost_9 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[27]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET rrp_9 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[28]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET ie_rrp_9 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[29]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET cost_10 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[30]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET rrp_10 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[31]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET ie_rrp_10 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[32]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET cost_11 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[33]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET rrp_11 = ? where cost_grid_id = ? and finish_dro = ?', ( float(row[34]), row[0], float(row[2]))) c.execute('UPDATE cost_grid SET ie_rrp_11 = ? where cost_grid_
Re: [Tutor] Tutor Digest, Vol 26, Issue 56
Quoting [EMAIL PROTECTED]: > 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 > [EMAIL PROTECTED] > > You can reach the person managing the list at > [EMAIL PROTECTED] > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > >1. Changing lists in place (Paul D. Kraus) >2. Re: Changing lists in place (Paul D. Eden) >3. Re: Changing lists in place (Bob Gailer) >4. Re: Meaning of %g ? (Terry Carroll) >5. Re: Changing lists in place (Kent Johnson) >6. Re: Tutor Digest, Vol 26, Issue 55 (Carroll, Barry) >7. Re: Changing lists in place (Paul D. Eden) >8. Re: functions in Python (Alan Gauld) >9. Raw Bits! (Control characters ahoy!) (doug shawhan) > > > -- > > Message: 1 > Date: Mon, 17 Apr 2006 14:02:37 -0400 > From: "Paul D. Kraus" <[EMAIL PROTECTED]> > Subject: [Tutor] Changing lists in place > To: tutor@python.org > Message-ID: > <[EMAIL PROTECTED]> > Content-Type: text/plain; charset="iso-8859-1" > > I have a list that I want to change in a for loop. It changes in the loop > but the changes are not persistant outside of the loop. > I thought lists were mutuable objects so I am a bit confused. > > Sample Code > #!/usr/bin/env python > """ Testing lists """ > > mylist = [ 'One', ' two', ' three ' ] > print mylist > for element in mylist: > element = element.strip() > print "<>" + element + "<>" > print mylist > > > Sample Output > ['One', ' two', ' three '] > <>One<> > <>two<> > <>three<> > ['One', ' two', ' three '] > -- next part -- > An HTML attachment was scrubbed... > URL: > http://mail.python.org/pipermail/tutor/attachments/20060417/b1d0ae57/attachment-0001.html > > -- > > Message: 2 > Date: Mon, 17 Apr 2006 11:11:44 -0700 > From: "Paul D. Eden" <[EMAIL PROTECTED]> > Subject: Re: [Tutor] Changing lists in place > To: [EMAIL PROTECTED] > Cc: tutor@python.org > Message-ID: <[EMAIL PROTECTED]> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Lists are mutable, you are right. > > But the code you gave does not change the list. It changes the variable > element which is separate from the list myList. > > If you want to change the list try something like this: > > mylist = [ 'One', ' two', ' three ' ] > print mylist > newlist = [] > for element in mylist: > element = element.strip() > newlist.append(element) > print "<>" + element + "<>" > print newlist > > OR > > mylist = [ 'One', ' two', ' three ' ] > print mylist > mylist = [element.strip() for element in mylist] > for element in mylist: > print "<>" + element + "<>" > print mylist > > Paul > > Paul D. Kraus wrote: > > I have a list that I want to change in a for loop. It changes in the > > loop but the changes are not persistant outside of the loop. > > I thought lists were mutuable objects so I am a bit confused. > > > > Sample Code > > #!/usr/bin/env python > > """ Testing lists """ > > > > mylist = [ 'One', ' two', ' three ' ] > > print mylist > > for element in mylist: > > element = element.strip() > > print "<>" + element + "<>" > > print mylist > > > > > > Sample Output > > ['One', ' two', ' three '] > > <>One<> > > <>two<> > > <>three<> > > ['One', ' two', ' three '] > > > > > > > > > > ___ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > -- > > Message: 3 > Date: Mon, 17 Apr 2006 11:17:18 -0700 > From: Bob Gailer <[EMAIL PROTECTED]> > Subject: Re: [Tutor] Changing lists in place > To: [EMAIL PROTECTED] > Cc: tutor@python.org > Message-ID: <[EMAIL PROTECTED]> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Paul D. Kraus wrote: > > I have a list that I want to change in a for loop. It changes in the > > loop but the changes are not persistant outside of the loop. > > I thought lists were mutuable objects > They are. > > so I am a bit confused. > > > > Sample Code > > #!/usr/bin/env python > > """ Testing lists """ > > > > mylist = [ 'One', ' two', ' three ' ] > > print mylist > > for element in mylist: > element is a variable to which the successive items in mylist are > assigned. element has no "magic" connection to the list. > > element = element.strip() > In order to change a list item you must do something like: > mylist[itemIndex] = element.strip() > > So you need both the item's value and its position in the list. That's > what enumer
Re: [Tutor] Python programmer needs to learn Java
> I am seeking book recommendations or preferrably online tutorials > to help me learn Java. The only online resources I recommend for Java are: 1) Bruce Eckel's Thinking in Java and 2) The official Sun tutorial The only book I've found that I like is: O'Reilly Learning Java The Java in a Nutshell is a useful reference too. > I came from Visual Basic 6 to Python and had little problems > which is why I love Python. With that background you should have little difficulty with Java conceptually., except that Javba uses classes for everythjing and because of that relies hevily on class methods(statics) to mimic functions in VB/Python Otherwise the pain is mainly in the rigours of strict static typing and getting to know the huge class library. Have fun, Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Alan Gauld Tutorial - OOP
> I am reading Alan's tut and have stuck on the OOP chapter. > What does he mean by, > > | Objects are collections of data and functions that operate on that > |data. These are bound together so that you can pass an object from one > |part of your program and they automatically get access to not only the > |data attributes but the operations that are available too. > > What are exactly "data attributes" and what "operations" is he referring > to? I mean the data and the functions that are used to create an object. As the definition above states, objects are collections of data and the functions that operate on the data. Another name for a function inside an object is "operation", and as you'll discover the most common name of all is "method" Any time you see a word in italics in my tutor it means I'm introducing a new technical term. Thus attributes and operations being italicised tells you that these are jargon terms for the data and functions just mentioned. You have already met objects back in the Raw Materials topic and also in strings and files. (Strings and Files are predefined objects in Python) . The OOP topic tells you how to create your own object types, or classes. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python programmer needs to learn Java
> Greetings. > I am seeking book recommendations or preferrably online tutorials > to help me learn Java. _Head First Java_ Alan ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tutor Digest, Vol 26, Issue 56
- Original Message - From: <[EMAIL PROTECTED]> Subject: Re: [Tutor] Tutor Digest, Vol 26, Issue 56 Please don't reply to the digest message, we get all of the digest plus your question tagged on at the end! >> >> End of Tutor Digest, Vol 26, Issue 56 >> * >> > I want to build a function which will reverse my input sentance.if i try > to > use the rervese it does not work here is my function: > > def reversor(): > for i in string(a): What is string(a)? Indeed, what is a? string is not a built in function in Python. Do you mean str(a)? str(a) will attempt to convert a to a string. It would be better to pass a string into the function as a parameter. > l=[] This creates an empty list, l > if a==string: > l.reversed(a) This says that if 'a' equals string (which you show to be some kind of function object) then call l.reversed(a) There is no method of a list called reversed(), there is one called reverse() but it doesn't have a parameter. And it reverses the list which in this case is empty. > print l So you print an empty list. Did you try to run the code? What error did you get? What did you think the code was doing? What did you expect to happen? Armed with this information we might be able to help you solve your problem. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] My Name is John and I copy and paste
John CORRY wrote: > Thanks for all the help so far on my database questions. I have now > developed a program that reads in info from a csv file and updates > already existing records in my database. I have enclosed the code > below. The good news is that it is working. However, I used copy and > paste and amended the text to write the code and it seems rather > longwinded. Is there a quicker/better way to write the code below? Hi John, What you need here is a loop. Have you learned about for loops? Here is a short example to get you started. Any Python tutorial will tell you more. In [1]: rows = [ ['row1', 0], ['row2', 55], ['row3', 23] ] In [2]: for row in rows: ...: print row[0], row[1] ...: ...: row1 0 row2 55 row3 23 Kent > path = "c:/test/import.csv" > > import mx.ODBC > > import mx.ODBC.Windows > > import csv > > reader = csv.reader(open(path,"rb")) > > for row in reader: > > db = mx.ODBC.Windows.DriverConnect('DSN=vfp') > > c = db.cursor() > > c.execute('UPDATE cost_grid SET cost_1 = ? where cost_grid_id = ? > and finish_dro = ?', ( float(row[3]), row[0], float(row[2]))) > > c.execute('UPDATE cost_grid SET rrp_1 = ? where cost_grid_id = ? and > finish_dro = ?', ( float(row[4]), row[0], float(row[2]))) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Tutor projects
Hi there, This list is great! I really like the aspect of mentor-mentee relationship. Ok, I have been programming in various languages for many many years, and here is my dilemna. I jump into a huge project such as Zope or Mambo (php side) and spend a couple of weeks on it, get frustrated, and give up. What I am requesting is an interesting project that is good for the intermediate level hacker, and somebody to assist me when I run into a problem. Any takers? -Tino ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] pyexpat
I am working for the Python Wikipediabot Framework (http://www.sourceforge.net/pywikipedia). A user noted me to an apparent deadlock in the XML parsing. I tried to get to the actual parsing code to see what went wrong. The furthest I get, however, is in the feed() method of the class ExpatParser in expatreader.py. There is a line there: self._parser.Parse(data, isFinal) self._parser, as I have found, is an object of the class pyexpat.xmlparser, but I have no idea about where to fine pyexpat. Can anyone help me further? -- Andre Engels, [EMAIL PROTECTED] ICQ: 6260644 -- Skype: a_engels ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] pyexpat
Andre Engels wrote: > I am working for the Python Wikipediabot Framework > (http://www.sourceforge.net/pywikipedia). A user noted me to an > apparent deadlock in the XML parsing. I tried to get to the actual That's pretty surprising, I wouldn't expect the parser to use any locks. Can you say more about the deadlock? > parsing code to see what went wrong. The furthest I get, however, is > in the feed() method of the class ExpatParser in expatreader.py. There > is a line there: > > self._parser.Parse(data, isFinal) > > self._parser, as I have found, is an object of the class > pyexpat.xmlparser, but I have no idea about where to fine pyexpat. Can > anyone help me further? pyexpat is written in C, you have to look at the Python source code. Download the source tarball or browse the Subversion repository online; pyexpat.c is here: http://svn.python.org/view/python/trunk/Modules/pyexpat.c?rev=45449&view=auto pyexpat is itself a wrapper around expat which is here: http://svn.python.org/view/python/trunk/Modules/expat/ Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Alan Gauld Tutorial - OOP
On Tue, Apr 18, 2006 at 11:19:32AM +0100, Alan Gauld wrote: > I mean the data and the functions that are used to create an object. > As the definition above states, objects are collections of data and > the functions that operate on the data. Another name for a function > inside an object is "operation", and as you'll discover the most > common name of all is "method" Thanks for the prompt response. My real problem is that there is no place inside a tutorial where all the terms like object, data, method, operation, attributes are explained on a single page *with* one small example of each. I am *really* confused when they occur now. I found this place a better help http://www.devshed.com/c/a/Python/Object-Orientation-in-Python/ I want something like this. e.g. Alan when I read your tut for OOP, I don't get what you mean by data, variable, and object and difference between them. Thanks again. With warm regards, -Payal ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] functions in Python
Payal Rathod wrote: On Mon, Apr 17, 2006 at 05:42:05PM +0100, Steve Nelson wrote: When you define a function, you are writing a block of code which you can ask to perform a task. The task may be simple, and not require any additional information, or it may be more complex and need information. What is the difference between, def f(x): ... return x ... f(4) 4 def f(x): ... print x ... f(4) 4 Both give same results. So, why return statement is needed? With warm regards, -Payal ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor New at this but the f(x) with the return statement passes the value back to be used in something. The one with the print statement just prints it. Correct me if I am wrong experts def f(x): x = x + 1; return x def g(x): x=x + 1; print x; >>> bob = 5 + f(5) >>> print bob bob =Traceback (most recent call last): File "", line 1, in ? TypeError: unsupported operand type(s) for +: 'int' and 'NoneType' 5 + g(5) begin:vcard fn:Eric Walker n:Walker;Eric org:Micron Technologies email;internet:[EMAIL PROTECTED] title:EDA Applications Engineer tel;work:208-368-2573 version:2.1 end:vcard ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] pyexpat
2006/4/18, Kent Johnson <[EMAIL PROTECTED]>: > Andre Engels wrote: > > I am working for the Python Wikipediabot Framework > > (http://www.sourceforge.net/pywikipedia). A user noted me to an > > apparent deadlock in the XML parsing. I tried to get to the actual > > That's pretty surprising, I wouldn't expect the parser to use any locks. > Can you say more about the deadlock? I have found some more, and there is not a deadlock... Just the thing is going damn slow on this specific text, not sure why. Thanks anyway. -- Andre Engels, [EMAIL PROTECTED] ICQ: 6260644 -- Skype: a_engels ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Olle-Olla
Hi All, Is it possible to replace the print statement with one of mine function ? Is it any extra reason why print isn't similar to the functions I can make with def ? >>> def olle(dummy): print 'olle:', dummy ... >>> def olla(dummy): print 'olla:', dummy ... >>> olle('Hopp') olle: Hopp >>> olla('Hopp') olla: Hopp >>> olle = olla >>> olle('Hopp') olla: Hopp >>> print = olle Traceback ( File "", line 1 print = olle ^ SyntaxError: invalid syntax In reality, I would like to replace the print in my PyCrust app with the log.write() function. janos juhasz ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Alan Gauld Tutorial - OOP
> I want something like this. e.g. Alan when I read your tut for OOP, I > don't get what you mean by data, variable, and object and difference > between them. Those terms were all explained back in the Raw Materials section since they are fundamental building blocks of programming. Have you read through the basics section of the tutor or are you simply picking topics of intrest? You can do that with the advanced topics like OOP etc but only if you have already understood the basics section. Otherwise there will be a lot of jargon that is not explained. I dedicate a lot of the introductory topics to explaining and defining the fundamental building blocks. If you have not done so I really reconmmend you read the two topics: 1) What is Programming 2) The Raw Materials These are both fairly essential reading. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] GUI
All, I want to create a GUI, and I downloaded the pyQT stuff. Ok, now that I am reading my but off trying to figure out how to use this thing and learn python at the same time, I read some stuff about having to purchase licenses. For commercial development, who do I need to contact for licensing? Thanks Python Newbie ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] My Name is John and I copy and paste
John CORRY wrote: > > Hi, > > > > Thanks for all the help so far on my database questions. I have now > developed a program that reads in info from a csv file and updates > already existing records in my database. I have enclosed the code > below. The good news is that it is working. However, I used copy and > paste and amended the text to write the code and it seems rather > longwinded. Is there a quicker/better way to write the code below? > > > > path = "c:/test/import.csv" > > import mx.ODBC > > import mx.ODBC.Windows > > import csv > > reader = csv.reader(open(path,"rb")) > > for row in reader: > > db = mx.ODBC.Windows.DriverConnect('DSN=vfp') > > c = db.cursor() > > c.execute('UPDATE cost_grid SET cost_1 = ? where cost_grid_id = ? > and finish_dro = ?', ( float(row[3]), row[0], float(row[2]))) > > c.execute('UPDATE cost_grid SET rrp_1 = ? where cost_grid_id = ? > and finish_dro = ?', ( float(row[4]), row[0], float(row[2]))) > > c.execute('UPDATE cost_grid SET ie_rrp_1 = ? where cost_grid_id = > ? and finish_dro = ?', ( float(row[5]), row[0], float(row[2]))) > When I see "repeated columns" I think the database is not fully normalized. If this were my database I'd have a table with columns named cost, rrp, ie_rrp, cost_grid_id, finish_dro, and a column to distingush the 20 cases. A little more work up front, but a lot easier to work with once it is set up. The recommendation to do this in a loop is the answer regardless of the data model. [snip] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Quick networking question
Hi Everybody, I am writing a script to do some simple networking. When I do a close on the socket and exit the program, I getting a time wait on the port, and the port can''t be utilized again until the time wait disappears. How do I get port to shut down and be able to reuse that port? Thanks,Tino ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Alan Gauld Tutorial - OOP
On Tue, Apr 18, 2006 at 03:29:28PM +0100, Alan Gauld wrote: > Have you read through the basics section of the tutor or are you > simply picking topics of intrest? You can do that with the advanced No, I read the tutorial from start. I am not understanding how data, objects, attributes etc. are related to each other. I am really curious, why didn't you make the whole tutorial Python only. As you Python people say - python is a language to teach programming, why unnecessary stuff about Vbscript or Javascript? Is there any page which tell me how do I read the tutorial, I mean I don't want to learn Vbscript or Javascript, what do I do then, am I supposed to skip those parts? With warm regards, -Payal ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Alan Gauld Tutorial - OOP
> No, I read the tutorial from start. I am not understanding how data, > objects, attributes etc. are related to each other. That is back in the Raw Materials section. And objects are then expanded in the OOP topic. > I am really curious, why didn't you make the whole tutorial Python only. Because learning only one programming language makes for more limited programmers in my experience. It is much better to understand the underlying concepts that apply in every language and thus become a "programmer" who can learn and use any language than to become a "Python Programmer" who is afraid to use other languages because it would take too long to learn them. It says pretty much the same on the intro page under the heading "Why Python?". That having been said I do not expect the reader to actually type in all the examples for all 3 languages. Pick one, type in the examples in that language and read the others for comparison. I thought I said that explicitly in the tutor but i can't find it anywhere so should probably add it! (Thanks for picking that up!) > Is there any page which tell me how do I read the tutorial, I mean I > don't want to learn Vbscript or Javascript, what do I do then, am I > supposed to skip those parts? There will soon be a paragraph on the Getting Started page to say what I did above... In fact its there now! :-) Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] wanted exercises in python
Hi, As I mentioned I have been reading Python a lot in last 2 months but lack of examples and coding is not getting me anywhere. Can someone give me some exercises or I can try them myself (pythonchallenge.com please excuse). I am reading Alan's tut now and covered Basis set and regex from advanced set, so please give me exercises based on those topics i.e. don't tell me to code a http client or a GUI based program in Python :) With warm regards, -Payal ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] functions in Python
> New at this but the f(x) with the return statement passes the value back > to be used in something. The one with the print statement just prints > it. Correct me if I am wrong experts > def f(x): > x = x + 1; > return x > > def g(x): > x=x + 1; > print x; Hi Eric, Yes, you've got it. Just as a side note: no semicolons needed. *wink* Best of wishes to you! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] wanted exercises in python
If you have some programming experience already in another language you may want to try the examples in http://www.diveintopython.org/toc/index.html Paul Payal Rathod wrote: > Hi, > As I mentioned I have been reading Python a lot in last 2 months but > lack of examples and coding is not getting me anywhere. Can someone give > me some exercises or I can try them myself (pythonchallenge.com please > excuse). I am reading Alan's tut now and covered Basis set and regex > from advanced set, so please give me exercises based on those topics > i.e. don't tell me to code a http client or a GUI based program in > Python :) > > With warm regards, > -Payal > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] pyexpat
On Tue, 18 Apr 2006, Andre Engels wrote: > 2006/4/18, Kent Johnson <[EMAIL PROTECTED]>: >> Andre Engels wrote: >>> I am working for the Python Wikipediabot Framework >>> (http://www.sourceforge.net/pywikipedia). A user noted me to an >>> apparent deadlock in the XML parsing. I tried to get to the actual >> >> That's pretty surprising, I wouldn't expect the parser to use any locks. >> Can you say more about the deadlock? > > I have found some more, and there is not a deadlock... Just the thing is > going damn slow on this specific text, not sure why. Thanks anyway. Hi Andre, H Can you send a link to the text that's causing performance issues? It might be possible that someone here might isolate the performance problem. (Hey, it happened before with BeautifulSoup... *grin*) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Olle-Olla
> Is it possible to replace the print statement with one of mine function ? Hi Janos, Yes; there are a set of reserved "keywords" that Python does not allow to be rebound as something else. It's a particular consequence of the way Python's language grammar is parsed. You'll want to watch out for keywords. Here they are: http://docs.python.org/ref/keywords.html If you avoid using them as variable names, you should be fine. Best of wishes! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] wanted exercises in python
Well, these are from a Ruby group but I don't see any reason why you couldn't do them in Python. http://www.rubyquiz.com Look through their quiz's, might find something fun to try. -Andy "Be who you are and be that well." - Saint Francis de Sales On 4/18/06, Payal Rathod <[EMAIL PROTECTED]> wrote: > Hi, > As I mentioned I have been reading Python a lot in last 2 months but > lack of examples and coding is not getting me anywhere. Can someone give > me some exercises or I can try them myself (pythonchallenge.com please > excuse). I am reading Alan's tut now and covered Basis set and regex > from advanced set, so please give me exercises based on those topics > i.e. don't tell me to code a http client or a GUI based program in > Python :) > > With warm regards, > -Payal > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Quick networking question
On Tue, 18 Apr 2006, Tino Dai wrote: > I am writing a script to do some simple networking. When I do a > close on the socket and exit the program, I getting a time wait on the > port, and the port can''t be utilized again until the time wait > disappears. How do I get port to shut down and be able to reuse that > port? Hi Tino, Ah! You may want to take a look at some sample use of networking in the SocketServer: http://svn.python.org/view/python/trunk/Lib/SocketServer.py?rev=39194&view=markup In particular, take a look at: def server_bind(self): """Called by constructor to bind the socket. May be overridden. """ if self.allow_reuse_address: self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind(self.server_address) If we're using SocketServer class to build your socket servers, we set the allow_reuse_address attribute to True (See: http://www.python.org/doc/lib/node536.html) If we're building server sockets from scratch, we'll want to do that magic line: socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) right before binding the socket to the address. Best of wishes! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Tutorial on bitwise Python?
Can anyone point me to a tutorial on bit manipulations (testing and setting) in Python? I'm very clear on the concepts (in a previous lifetime, I used to do systems programming in IBM System/3x0 assembler), but weak on how some things would be approached in Python, and need an orientation. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Alan Gauld Tutorial - OOP
> Thanks for the prompt response. My real problem is that there is no > place inside a tutorial where all the terms like object, data, method, > operation, attributes are explained on a single page *with* one small > example of each. I am *really* confused when they occur now. I found The _Head First Java_ book explains it this way: Attributes are what an object KNOWS. Methods are what an object can DO. Alan ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] functions in Python
On Tue, 18 Apr 2006, Danny Yoo wrote: > Just as a side note: no semicolons needed. *wink* Yesterday, I tested something with a two-line perl program. I could not for the life of me see why I was getting a syntax error. It was only after 15 minutes of looking up red herrings that it finally dawned on me that, back in Perlland, semicolons are required. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python programmer needs to learn Java
On Tue, 18 Apr 2006, Justin Ezequiel wrote: > I am seeking book recommendations or preferrably online tutorials > to help me learn Java. If you already know a language "Just Java" (now titled "Just Java 2") by Peter van der Linden is very good. It's intended for people who are moving from C to Java, but I think it would be very workable for Python-to-Java, too. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Olle-Olla
János Juhász wrote: > Hi All, > > Is it possible to replace the print statement with one of mine function ? > > In reality, I would like to replace the print in my PyCrust app with the > log.write() function. Best: Use a good editor to change your print statements to log.write() Not so good: Replace sys.stdout with something that intercepts write() calls and sends them to the log. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] GUI
> I want to create a GUI, and I downloaded the pyQT stuff. Any reason why you must use PyQt? Not that it's a bad toolkit but there is less expertise in using it so unless you already use it from another language - like C++ - its going to be a lot harder to learn than Tkinter or wxPython which are the two most commonly used GUI tookits. Both Tkinter and wxPython are free, Tkinter comes with Python, wxPython is a searate download. wxPython tends to look nicer and has some fancier widgets. You pays yer money etc... > read some stuff about having to purchase licenses. > For commercial development, who do I need to contact for licensing? TrollTech own Qt, their licensing arrangements seem a tad complex to me. Try their web site. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] wanted exercises in python
> As I mentioned I have been reading Python a lot in last 2 months but > lack of examples and coding is not getting me anywhere. Can someone give > me some exercises or I can try them myself There are a few suggestions in the last topic of my tutor - Refernces etc... But the best place to find stuff for beginners is the Useless Python web site. The new site didn't have much last time I looked buyt the old site (linked from the new one) has a lot of stuff, albeit slightly confusingly laid out. http://www.uselesspython.com/pythonchallenge.html Despite the URL this has nothing to do with the Python Challenge game web site. HTH, Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Olle-Olla
> Is it possible to replace the print statement with one of mine function ? No precisely because the print statement is a statement (or more accurately a command) not a function. But of course you can create your own print *function*, just call it a slightly different name - printit(), or display(), or logit(), or somesuch. > Is it any extra reason why print isn't similar to the functions I can make > with def ? Guido's call. Guido has intimated that he thinks this was one of his (few) mistakes in building Python. > In reality, I would like to replace the print in my PyCrust app with the > log.write() function. You will need to do a search/replace of all print statements with your new function, but its doable. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] GUI
Alan Gauld wrote: >> I want to create a GUI, and I downloaded the pyQT stuff. > > > Any reason why you must use PyQt? > > Not that it's a bad toolkit but there is less expertise in using it so > unless you already use it from another language - like C++ - its going > to be a lot harder to learn than Tkinter or wxPython which are the two > most commonly used GUI tookits. > > Both Tkinter and wxPython are free, Tkinter comes with Python, > wxPython is a searate download. wxPython tends to look nicer and has > some fancier widgets. You pays yer money etc... > >> read some stuff about having to purchase licenses. For commercial >> development, who do I need to contact for licensing? > > > TrollTech own Qt, their licensing arrangements seem a tad complex to me. > Try their web site. > > Alan G. > > Ok, If I can get it for free, I might as well go with say wxPython. Thanks ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Help Entry !!!
Hi !!! Friends, i nedd process Data Entry in python Example Entry = 20 Result = 20*10 This Result in Windows (Tkinter) How do you do Think !!! Regards Cesar Exmaple from Tkinter import * class MyDialog: def __init__(self, parent): top = self.top = Toplevel(parent) Label(top, text="Valor").pack() self.e = Entry(top) self.e.pack(padx=5) b = Button(top, text="OK", command=self.ok) b.pack(pady=5) def ok(self): print "value is", self.e.get() self.top.destroy() root = Tk()root.update()d = MyDialog(root)root.wait_window(d.top) New Yahoo! Messenger with Voice. Call regular phones from your PC and save big.___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] creating a tab delim file
Hi group, I asked similar questions in the past. I am unable to get to the crux of this problem so that I can solve on my own. apologies for my ignorance. The problem: I have 50 tab delim files. Each file has 500 rows and 50 columns. I have to read the first column of each file. Repeat the same for 50 files and write a tab delim text file containing 500 rows and 50 columns. code that works through half of the problem: import glob files = glob.glob('*.proc') for each in files: f = open(each,'r') da = f.read().split('\n') dat = da[:-1] for m in dat: mycol = m.split('\t')[0] .. >From here I am blanked out. Although I can extract the first column from each file:I have no idea how to store each list. thought 1. Create an empty string and join each by a tab. ## mycol = '' for m in dat: mycol = m.split('\t')[0] mstr = '\t'.join(mycol) how can i append the data from second file to that string. could tutors help me with this situation. Thanks srini __ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Olle-Olla
Andre Engels wrote: > 2006/4/18, Kent Johnson <[EMAIL PROTECTED]>: >> János Juhász wrote: >>> Hi All, >>> >>> Is it possible to replace the print statement with one of mine function ? >>> >>> In reality, I would like to replace the print in my PyCrust app with the >>> log.write() function. >> Best: Use a good editor to change your print statements to log.write() > > Even better: Use a good editor to change your print statements to > myprint() and then def myprint() to be log.write(). This has the > advantage that if (for example) you want prints later to be "usually > log.write() but if redFlagHighestWarning is True, then both > log.write() and print()", you don't need to go through all this again, > but just have to change myprint(). Or use the logging module, which lets you make changes like this by editing a config file. I usually set it up so that INFO level and higher messages go to a console or GUI panel, and all messages go to a rollover file. Very handy. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tutorial on bitwise Python?
> Can anyone point me to a tutorial on bit manipulations (testing and > setting) in Python? Look at the sidebar in my OS topic. It covers using bitmasks to test the bits set by the file stat functions. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] creating a tab delim file
On 18 Apr 2006, [EMAIL PROTECTED] wrote: > The problem: > > I have 50 tab delim files. Each file has 500 rows and > 50 columns. > > I have to read the first column of each file. Repeat > the same for 50 files and write a tab delim text file > containing 500 rows and 50 columns. > > code that works through half of the problem: > > import glob > > files = glob.glob('*.proc') > > > for each in files: > f = open(each,'r') > da = f.read().split('\n') > dat = da[:-1] > for m in dat: > mycol = m.split('\t')[0] > .. You don't need to read the whole file at once. You can read individual lines from a file with: f = open('name') for line in f: # do something with line I'll show you a different solution for your problem; if you don't understand it ask (I try to explain it). --8<---cut here---start->8--- import glob filehdls = [file(f) for f in glob.glob('*.proc')] out = open('reordered.prc', 'w') col_1 = [f.readline().split('\t')[0] for f in filehdls] while col_1[0]: out.write('\t'.join(col0)) out.write('\n') col_1 = [f.readline().split('\t')[0] for f in filehdls] out.close() for f in filehdls: f.close() --8<---cut here---end--->8--- filehdls is a list of file handles. col_1 is a list of the values of column 1 of each of the files. How does it work? f.readline().split('\t')[0] Read it from left to right. First we call readline() which reads the next line from file or returns the empty string if it reached the end of the file. Then we call split('\t') on the string returned from readline(). This returns a list of strings obtained from splitting the string at each tab. Then we take the first element from thew list (index 0) since we are only interested in column 1. We do this for every file in the list of file handles. The while loop runs as long as the first element in our list of columns is not false (at eof we get here an empty string which counts as false). We join the columns with a tab, write that string to our output file and write a newline to that file. Then we try to read the next line. The above will only work if all files have equal length. Karl -- Please do *not* send copies of replies to me. I read the list ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Version of a .pyc file
I want like to write a script to scan all of the .pyc on my pythonpath to find out if they were built with Python 2.3 or 2.4. How can I tell if a .pyc file was built with 2.3 or 2.4? Thanks, Don. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] unit testing raw_input()
Hi all- Suppose I had a function like the following: def y_n(prompt="Answer yes or no"): while True: answer = raw_input(prompt) if answer in ['y', 'Y', 'yes']: print "You said yes!" break elif answer in ['n', 'N', 'no']: print "You said no!" break else: print "%s is an invalid answer."%answer How could I go about to write an automated test for it? André ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Version of a .pyc file
On Tue, 18 Apr 2006, Don Taylor wrote: > How can I tell if a .pyc file was built with 2.3 or 2.4? There's a "Magic Number" in the first 2 or 4 bytes, (depending on whether you consider the \r\n part of the MN). >>> f = open("pycfile.pyc", "rb") >>> magictable = {'\x3b\xf2\r\n': "2.3", '\x6d\xf2\r\n' : "2.4"} >>> magic = f.read(4) >>> release = magictable.get(magic,"unknown") >>> print "Python release:", release Python release: 2.4 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unit testing raw_input()
On Tuesday 18 April 2006 23:34, Andre Roberge wrote: > Hi all- > > Suppose I had a function like the following: > > [ function that interacts with the outside world ] ... > How could I go about to write an automated test for it? You create a mock for raw_input, put the above code inside a module and rebind raw_input in the module before calling your function. ie: (CONTENTS of y_n.py) def y_n(prompt="Answer yes or no"): while True: answer = raw_input(prompt) if answer in ['y', 'Y', 'yes']: print "You said yes!" break elif answer in ['n', 'N', 'no']: print "You said no!" break else: print "%s is an invalid answer."%answer (END CONTENTS of y_n.py) You can even create and test a mock in the command line interpreter, so here's a quick example: >>> import y_n # Import the module >>> def raw_input_mock(prompt): # create a mock ... return "y" ... >>> y_n.raw_input = raw_input_mock # rebind the name inside the module >>> y_n.y_n() # Run, this now calls our mock instead of the real raw_input You said yes! To my mind this is generally useful for testing error conditions with complex modules (select & socket spring to mind). To do this properly with your module, it makes more sense for your function to return strings, which would allow you to directly test the result. Alternatively you could wrap print in a function and then mock that instead. The key thing about a mock is that it simply provides the results you want. If it's important *how* the mock was called (eg you're testing correct use of a library), your mock could append parameters to a list for later comparision. Eg >>> mocktrace = [] >>> def raw_input_mock(prompt): # create a mock ... mocktrace.append((prompt,)) ... return "y" ... As I say though, this sort of thing is (IME) often more about testing the correct usage of something. Regards, Michael. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unit testing raw_input()
On Tue, 18 Apr 2006, Andre Roberge wrote: > Suppose I had a function like the following: > > def y_n(prompt="Answer yes or no"): >while True: >answer = raw_input(prompt) >if answer in ['y', 'Y', 'yes']: >print "You said yes!" >break >elif answer in ['n', 'N', 'no']: >print "You said no!" >break >else: >print "%s is an invalid answer."%answer > > How could I go about to write an automated test for it? Hi Andre, One way to do this is to parameterize y_n() a little more to make it more amendable to unit testing. If we look at y_n(), we'd say that "raw_input()" is a free variable in here --- its meaning comes from the outside environment as part of builtins. We can change this by making it an explicit parameter: def y_n(prompt="Answer yes or no", raw_input=raw_input): while True: answer = raw_input(prompt) if answer in ['y', 'Y', 'yes']: print "You said yes!" break elif answer in ['n', 'N', 'no']: print "You said no!" break else: print "%s is an invalid answer."%answer Looks a little funny. *grin* But now we can hardcode particular inputs by sending y_n() a mock "raw_input" that returns precooked values. ### def yes1_raw_input(prompt): return "y" def yes2_raw_input(prompt): return "Y" def yes3_raw_input(prompt): return "yes" def yes4_raw_input(prompt): return "YES" ### And then we can use these as part of our test case: y_n(raw_input=yes1_raw_input) We can also parameterize output in the same way. Right now, the function is printing out the answer. Testing printed output is a little harder in Python without fiddling around with stdout, but we can also make this also a parameter of the function: ### def y_n(prompt="Answer yes or no", raw_input=raw_input, output=sys.stdout): while True: answer = raw_input(prompt) if answer in ['y', 'Y', 'yes']: print >>output, "You said yes!" break elif answer in ['n', 'N', 'no']: print >>output, "You said no!" break else: print >>output, "%s is an invalid answer."%answer ### Now we can inject our own output string that we can use to test what has happened: ## pseudocode import StringIO test_output = StringIO.StringIO() y_n(raw_input = yes4_raw_input, output = test_output) assertEquals("You said yes!", test_output.getvalue()) Does this make sense so far? y_n() in its original form might not be in the right shape to make it easy to test, but we can turn it into a form that is more easily testable. Good luck! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python programmer needs to learn Java
> The only online resources I recommend for Java are: > 1) Bruce Eckel's Thinking in Java and > 2) The official Sun tutorial > > The only book I've found that I like is: > O'Reilly Learning Java > > The Java in a Nutshell is a useful reference too. > Thanks Alan. Will check these out ASAP. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] encode
Hi again folks, I wonder if we can check the encoding of text in one text file. user is free to encode the file whether Latin1, utf-8, ANSI... Any ideas? Thx da ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python programmer needs to learn Java
> If you already know a language "Just Java" (now titled "Just Java 2") by > Peter van der Linden is very good. Thanks Terry. Will surely check this out. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] encode
On Wed, 2006-04-19 at 10:10 +0700, kakada wrote: > Hi again folks, > > I wonder if we can check the encoding of text in one text file. > user is free to encode the file whether Latin1, utf-8, ANSI... > Any ideas? def decode_file(filepath): '''Order of codecs is important. ASCII is most restrictive to decode - no byte values > 127. UTF8 is next most restrictive. There are illegal byte values and illegal sequences. LATIN will accept anything since all 256 byte values are OK. The final decision still depends on human inspection. ''' buff = open(filepath,'rb').read() for charset in (ASCII,UTF8,LATIN,): try: unistr = buff.decode(charset,'strict') except UnicodeDecodeError: pass else: break else: unistr,charset = u'',None return unistr, charset Also note that the unicode character u'\ufffd' represents an error placeholder. It can be decoded from UTF8 inputs and reflects earlier processing problems. DO NOT USE THIS CODE BLINDLY. It simply offers a reasonable, first cut where those are the likely encodings. It is impossible to distinguish the various LATINx encodings by simply looking at bits. All 8 bit bytes are valid, but their meanings change based on the encoding used. > > Thx > > da > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] encode
On Wed, 19 Apr 2006, kakada wrote: > I wonder if we can check the encoding of text in one text file. user is > free to encode the file whether Latin1, utf-8, ANSI... In the general case, this is difficult, and "solving" it might be worse than not. See: http://www.joelonsoftware.com/articles/Unicode.html It is much better if you don't have to guess the file type: that's exactly the point of adding "document type" metadata to a document. If you can explain your situation more more --- why you're guessing document types --- we might be able to offer a different approach. Best of wishes to you! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unit testing raw_input()
> Suppose I had a function like the following: # def y_n(prompt="Answer yes or no"): while True: answer = raw_input(prompt) if answer in ['y', 'Y', 'yes']: print "You said yes!" break elif answer in ['n', 'N', 'no']: print "You said no!" break else: print "%s is an invalid answer."%answer > How could I go about to write an automated test for it? Create a data file with all of the inputs you need and use input redirection to run it. Assuming its called y_n.py: $ python y_n.py y_n.out This is the easiest way of testing interactive programs. This has limitations for unit testing if you have more than one function per module however, in that case you need to write a driver module that imports yours and takes as a first input the function you want to test... In Python the driver can sit inside the if __name__ == __main__ stanza Alan G ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Olle-Olla
Dear All, Thanks your answers about why I can't redifne the print. I just wanted to play with Python dynamic possibilities. I wanted to replace function in a loaded module instead of create an inherited class and using that. It was easier to try it with print. Alan Gauld wrote: > Guido's call. Guido has intimated that he thinks this was one > of his (few) mistakes in building Python. It is funny, I tried to redefine the only function, that is not a function but a keyword :) Thanks for Alan, Danny, Gabriel, Kent János Juhász ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor