Re: [Tutor] Returning multiple objects from a function
On 07/02/2012 10:23 PM, Alexander Q. wrote: > I understand the basics of tuples, but that formulation returned the > following error: > > Traceback (most recent call last): > File "C:\Users\Owner\Desktop\MIT\Sets\Set3.py", line 34, in > list4 = tuplesresult[1] > TypeError: 'NoneType' object is not subscriptable > > When I tried to assign "tuplesresult[1]" to the variable "list4" (after > assigning tuplesresult = mainFunc(), which is the name of the function that > returns the tuple in my program), the error occurred. That aside, is it all > right if I just code "return list1, list2" without the parens? In that > case, how would I access list1 and list2 when needed? That's no different: list1, list2 is a tuple of size 2. > Thanks for your help. > You top-posted, which loses all the context of the earlier messages. Please put your new message AFTER the part you're quoting Anyway, you never showed the function mainFunc(), but from the error traceback message, it didn't return anything, which means None. Chances are you have something like: def mainFunc(): if something: return 4, 12 And if the if fails, the function will return None. To fix that, make sure all paths through the function return a similar object, generally a tuple of the same size. -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Returning multiple objects from a function
I understand the basics of tuples, but that formulation returned the following error: Traceback (most recent call last): File "C:\Users\Owner\Desktop\MIT\Sets\Set3.py", line 34, in list4 = tuplesresult[1] TypeError: 'NoneType' object is not subscriptable When I tried to assign "tuplesresult[1]" to the variable "list4" (after assigning tuplesresult = mainFunc(), which is the name of the function that returns the tuple in my program), the error occurred. That aside, is it all right if I just code "return list1, list2" without the parens? In that case, how would I access list1 and list2 when needed? Thanks for your help. On Mon, Jul 2, 2012 at 4:11 PM, Walter Prins wrote: > On 2 July 2012 23:55, Alexander Q. wrote: > > Hello- I'm wondering how to access specific objects returned from a > function > > when that function returns multiple objects. > > > > For example, if I have "return(list1, list2, list 3)" within a function > > When you have: > return (list1, list2, list3) > > ... you're actually returning a single tuple object. Read about > tuples in the documentation. To access an item from a tuple you index > into it, e.g. > > tupleresult = myfunc() > x = tupleresult[0] > > ... for example > > Walter. > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Returning multiple objects from a function
On 02/07/12 23:55, Alexander Q. wrote: For example, if I have "return(list1, list2, list 3)" within a function "mainFunc()" that takes no arguments, how do I use list1, list2, and list3 outside of the function Just assign the result to 3 variables: L1,L2,L3 = mainFunc() This is just a special case of tuple unpacking which means you can do: a,b,c = 1,2,3 to set a=1, b=2, c=3 The function returns a tuple of values, so you unpack them into variables. Alternatively you can keep them as a tuple: values = mainFunc() and use indexing: print values[0], values[1], values[2] or iterate over them: for value in mainFunc(): print value Lots of options depending on what you want to do... HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Returning multiple objects from a function
On 2 July 2012 23:55, Alexander Q. wrote: > Hello- I'm wondering how to access specific objects returned from a function > when that function returns multiple objects. > > For example, if I have "return(list1, list2, list 3)" within a function When you have: return (list1, list2, list3) ... you're actually returning a single tuple object. Read about tuples in the documentation. To access an item from a tuple you index into it, e.g. tupleresult = myfunc() x = tupleresult[0] ... for example Walter. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Returning multiple objects from a function
Hello- I'm wondering how to access specific objects returned from a function when that function returns multiple objects. For example, if I have "return(list1, list2, list 3)" within a function "mainFunc()" that takes no arguments, how do I use list1, list2, and list3 outside of the function once they are returned by that function? Thank you. -Alex ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] sitecustomize
On 07/02/2012 03:17 PM, Ali Torkamani wrote: > Hi, > I'm absolutely newbie, and appreciate your help, I'm using Spyder, some > times it randomly get the following error: The first place I found Spyder was here: https://en.wikipedia.org/wiki/SPYDER which is an anti-aircraft system based partly on the Python-5 mssile. But presumably you mean: http://pypi.python.org/pypi/spyder > 'import sitecustomize' failed; use -v for traceback > > while, I'm not importing and have no idea what is importing it, site is automatically imported by Python during startup. It lets you customize things in a global way before starting your particular script. And one of the things it does it to import sitecustomize See this link: http://docs.python.org/library/site.html and also: http://www.doughellmann.com/PyMOTW/site/ My guess is that something's wrong with your Spyder installation, and you should check on their mailing list. But the first thing you might do is to add -v as your error message suggests. For some reason Spyder is hiding 3/4 of your error. -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] sitecustomize
On 7/2/2012 12:17 PM Ali Torkamani said... Hi, I'm absolutely newbie, and appreciate your help, I'm using Spyder, some times it randomly get the following error: 'import sitecustomize' failed; use -v for traceback This appears to be somewhat common as if you google for 'spyder sitecustomize' you'll get lots of hits and references. I'd start there -- it certainly doesn't seem to be a learning python issue. Emile while, I'm not importing and have no idea what is importing it, this happens even if my code is as simple as following: import sys import pdb #import traceback import numpy as np #import scipy as sp #import cmath class GaussianProcess(object): def __init__(self,data=None,data_mask=None): self.data,self.data_mask=data,data_mask if data==None and data_mask==None: self.GeneraterandomData(100,5,3,2) def GeneraterandomData(self,N,C,Lag,nUnknown): # N number of Samples, C: number of features, Lag: Number of autoregressions, nUnknown: number of unknown features at each time pdb.set_trace() self.data=np.random.rand(N,C) self.data_mask=np.ones((Lag,C)) self.data_mask[0,0:nUnknown]=0 return self.data,self.data_mask def main(argv=None): if argv==None: argv=sys.argv GP=GaussianProcess(); #print(GP.data,GP.data_mask) print("Done!") if __name__=="__main__": sys.exit(main()) Thanks, Ali ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python XML for newbie
> Yes, I personally think that (Mini)DOM should be locked away from beginners > as far as possible. Ok, I'm glad to hear that. I'll continue to work with ElementTree and lxml and see where it takes me. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] sitecustomize
Hi, I'm absolutely newbie, and appreciate your help, I'm using Spyder, some times it randomly get the following error: 'import sitecustomize' failed; use -v for traceback while, I'm not importing and have no idea what is importing it, this happens even if my code is as simple as following: import sys import pdb #import traceback import numpy as np #import scipy as sp #import cmath class GaussianProcess(object): def __init__(self,data=None,data_mask=None): self.data,self.data_mask=data,data_mask if data==None and data_mask==None: self.GeneraterandomData(100,5,3,2) def GeneraterandomData(self,N,C,Lag,nUnknown): # N number of Samples, C: number of features, Lag: Number of autoregressions, nUnknown: number of unknown features at each time pdb.set_trace() self.data=np.random.rand(N,C) self.data_mask=np.ones((Lag,C)) self.data_mask[0,0:nUnknown]=0 return self.data,self.data_mask def main(argv=None): if argv==None: argv=sys.argv GP=GaussianProcess(); #print(GP.data,GP.data_mask) print("Done!") if __name__=="__main__": sys.exit(main()) Thanks, Ali ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Simple text file processing using fileinput module. "Grabbing successive lines" failure
On 02/07/12 18:39, David Rock wrote: Essentially, your problem isn't with using fileinput, it's with how you handle each line that comes in. The immediate problem is with mis-using fileinput. But once you solve that you then have to deal with the other issues David raises. Once more I recommend the csv module... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Simple text file processing using fileinput module. "Grabbing successive lines" failure
On 02/07/12 15:03, Flynn, Stephen (L & P - IT) wrote: Whilst having a play around with reading in textfiles and reformatting them I > tried to write a python 3.2 script to read a CSV file, Best tool for csv files is the csv module, it covers most of the gotchas associated with such data. What I can't do is read the successive line to a short line in order to > append it onto the end of short line before writing the > entire amended line out. Maybe so but we can't help with that because you haven't shown us any code related to that issue... I'm still thinking about how to persuade the fileinput module fileinput is normally used when processing many similar files. Its not usually used when processing a single file. If you wanted to step onto the next file in the input list then fileinput would help there. But processing lines within the file is up to you. I get a traceback as I'm obviously not using fileinput.FileInput.readline() correctly. Nope, it doesn't look like it but you haven't posted enough code to be sure what is happening. But I'll take a guess... Traceback (most recent call last): File "C:\Documents and Settings\flynns\workspace\PipeSmoker\src\pipesmoker\pipesmoker.py", line 35, in nextLine = fileinput.FileInput.readline(args.file) File "C:\Python32\lib\fileinput.py", line 301, in readline line = self._buffer[self._bufindex] AttributeError: 'str' object has no attribute '_buffer' It looks like you are not creating an instance of the FileInput class. You are trying to use the methods directly. Thus the class tries to execute the call by using args as self. But args is a string not a FileInput instance and it therefore finds no _buffer attribute. Look at the documentation. The very first few lines show what you want: -- This module implements a helper class and functions to quickly write a loop over standard input or a list of files. If you just want to read or write one file see open(). The typical use is: import fileinput for line in fileinput.input(): process(line) --- Note the reference to processing a single file with open() and note the absence of FileInput in the example code. Further down it says: -- The class which implements the sequence behavior provided by the module is available for subclassing as well: class fileinput.FileInput([files[, inplace[, backup[, mode[, openhook]) Class FileInput is the implementation; its methods filename(), fileno(), lineno(), filelineno(), isfirstline(), isstdin(), nextfile() and close() correspond to the functions of the same name in the module. In addition it has a readline() method which returns the next input line, - So normally you don't need to use FileInput at all, unless you are creating some kind of specialized sub class version. But if you do use it you need to use it like any other class and create an instance. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Simple text file processing using fileinput module. "Grabbing successive lines" failure
* Flynn, Stephen (L & P - IT) [2012-07-02 15:03]: > Tutors, > > Can someone explain to me how I am supposed to make use of readline() > to grab the next line of a text file please? It may be that I should > be using some other module, but chose fileinput as I was hoping to > make the little routine as generic as possible; able to spot short > lines in tab separated, comma separated, pipe separated, ^~~^ > separated and anything else which my clients feel like sending me. There are a couple issues that you need to resolve. For starters, there is no guarantee that the successive line is actually part of the preceding line. It could very well be that the original line is simply truncated, in which case trying to append the following line would be incorrect. What I typically do in a case like this is use a flag variable and pull the offending line(s). So, you need to first determine the best course of action for resolving the inconsistency (eg, how do you verify the following line belongs with the preceding)? Try checking the line, if it's less than 13 then flag and store in a buffer and continue. The following line _should_ also error, in which case, you can try to resolve the two lines, or fail out if the criteria isn't met. Essentially, your problem isn't with using fileinput, it's with how you handle each line that comes in. -- David Rock da...@graniteweb.com pgpsm5eZpm6mp.pgp Description: PGP signature ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python XML for newbie
Peter Otten, 02.07.2012 09:57: > Sean Carolan wrote: >>> Thank you, this is helpful. Minidom is confusing, even the >>> documentation confirms this: >>> "The name of the functions are perhaps misleading" Yes, I personally think that (Mini)DOM should be locked away from beginners as far as possible. >> Ok, so I read through these tutorials and am at least able to print >> the XML output now. I did this: >> >> doc = etree.parse('computer_books.xml') >> >> and then this: >> >> for elem in doc.iter(): >> print elem.tag, elem.text >> >> Here's the data I'm interested in: >> >> index 1 >> field 11 >> value 9780596526740 >> datum >> >> How do you say, "If the field is 11, then print the next value"? The >> raw XML looks like this: >> >> >> 1 >> 11 >> 9780470286975 >> >> >> Basically I just want to pull all these ISBN numbers from the file. > > With http://lxml.de/ you can use xpath: > > $ cat computer_books.xml > > > > 1 > 11 > 9780470286975 > > > > $ cat read_isbn.py > from lxml import etree > > root = etree.parse("computer_books.xml") > print root.xpath("//datum[field=11]/value/text()") > $ python read_isbn.py > ['9780470286975'] > $ And lxml.objectify is also a nice tool for this: $ cat example.xml 108 1 2 Essential System Administration $ python Python 2.7.3 >>> from lxml import objectify >>> t = objectify.parse('example.xml') >>> for datum in t.iter('datum'): ... if datum.field == 2: ... print(datum.value) ... Essential System Administration >>> It's not impossible that this is faster than the XPath version, but that depends a lot on the data. Stefan ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Simple text file processing using fileinput module. "Grabbing successive lines" failure
On Mon, Jul 2, 2012 at 10:03 AM, Flynn, Stephen (L & P - IT) wrote: > Tutors, > > Whilst having a play around with reading in textfiles and reformatting them I > tried to write a python 3.2 script to read a CSV file, looking for any > records which were short (indicating that the data may well contain an > embedded CR/LF. I've attached a small sample file with a "split record" at > line 3, and my code. > > Call the code with > > Python pipesmoker.py MyFile.txt , > > (first parameter is the file being read, second parameter is the field > separator... a comma in this case) > > I can read the file in, I can determine that I'm looking for records which > have 13 fields and I can find a record which is too short (line 3). > > What I can't do is read the successive line to a short line in order to > append it onto the end of short line before writing the entire amended line > out. I'm still thinking about how to persuade the fileinput module to leap > over the successor line so it doesn't get processed again. > > When I run the code as it stands, I get a traceback as I'm obviously not > using fileinput.FileInput.readline() correctly. > > value of file is C:\myfile.txt > value of the delimiter is , > I'm looking for 13 , in each currentLine... > "1","000688 ","ABCD","930020854","34","0","1"," ","930020854 "," > ","0","0","0","0" > > "2","000688 ","ABCD","930020854","99","0","1"," ","930020854 "," > ","0","0","0","0" > > short line found at line 3 > Traceback (most recent call last): > File "C:\Documents and > Settings\flynns\workspace\PipeSmoker\src\pipesmoker\pipesmoker.py", line 35, > in > nextLine = fileinput.FileInput.readline(args.file) > File "C:\Python32\lib\fileinput.py", line 301, in readline > line = self._buffer[self._bufindex] > AttributeError: 'str' object has no attribute '_buffer' > > > Can someone explain to me how I am supposed to make use of readline() to grab > the next line of a text file please? It may be that I should be using some > other module, but chose fileinput as I was hoping to make the little routine > as generic as possible; able to spot short lines in tab separated, comma > separated, pipe separated, ^~~^ separated and anything else which my clients > feel like sending me. > Take a look at csvreader http://docs.python.org/library/csv.html#csv.reader. It comes with python, and according to the text near this link, it will handle a situation where EOL characters are contained in quoted fields. Will that help you? -- Joel Goldstick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Simple text file processing using fileinput module. "Grabbing successive lines" failure
Tutors, Whilst having a play around with reading in textfiles and reformatting them I tried to write a python 3.2 script to read a CSV file, looking for any records which were short (indicating that the data may well contain an embedded CR/LF. I've attached a small sample file with a "split record" at line 3, and my code. Call the code with Python pipesmoker.py MyFile.txt , (first parameter is the file being read, second parameter is the field separator... a comma in this case) I can read the file in, I can determine that I'm looking for records which have 13 fields and I can find a record which is too short (line 3). What I can't do is read the successive line to a short line in order to append it onto the end of short line before writing the entire amended line out. I'm still thinking about how to persuade the fileinput module to leap over the successor line so it doesn't get processed again. When I run the code as it stands, I get a traceback as I'm obviously not using fileinput.FileInput.readline() correctly. value of file is C:\myfile.txt value of the delimiter is , I'm looking for 13 , in each currentLine... "1","000688 ","ABCD","930020854","34","0","1"," ","930020854 "," ","0","0","0","0" "2","000688 ","ABCD","930020854","99","0","1"," ","930020854 "," ","0","0","0","0" short line found at line 3 Traceback (most recent call last): File "C:\Documents and Settings\flynns\workspace\PipeSmoker\src\pipesmoker\pipesmoker.py", line 35, in nextLine = fileinput.FileInput.readline(args.file) File "C:\Python32\lib\fileinput.py", line 301, in readline line = self._buffer[self._bufindex] AttributeError: 'str' object has no attribute '_buffer' Can someone explain to me how I am supposed to make use of readline() to grab the next line of a text file please? It may be that I should be using some other module, but chose fileinput as I was hoping to make the little routine as generic as possible; able to spot short lines in tab separated, comma separated, pipe separated, ^~~^ separated and anything else which my clients feel like sending me. -- Steve Flynn This email and any attachment to it are confidential. Unless you are the intended recipient, you may not use, copy or disclose either the message or any information contained in the message. If you are not the intended recipient, you should delete this email and notify the sender immediately. Any views or opinions expressed in this email are those of the sender only, unless otherwise stated. All copyright in any Capita material in this email is reserved. All emails, incoming and outgoing, may be recorded by Capita and monitored for legitimate business purposes. Capita exclude all liability for any loss or damage arising or resulting from the receipt, use or transmission of this email to the fullest extent permitted by law. "1","000688 ","ABCD","930020854","34","0","1"," ","930020854 "," ","0","0","0","0" "2","000688 ","ABCD","930020854","99","0","1"," ","930020854 "," ","0","0","0","0" "3","000695 ","ABCD","930610 085","34","0","1"," ","930610085 "," ","0","0","0","0" "4","000695 ","ABCD","930610085","99","0","1"," ","930610085 "," ","0","0","0","0" "5","000696 ","ABCD","930610086","34","0","1"," ","930610086 "," ","0","0","0","0" "6","000696 ","ABCD","930610086","99","0","1"," ","930610086 "," ","0","0","0","0" "7","000699 ","ABCD","930610087","34","0","1"," ","930610087 "," ","0","0","0","0" "8","000699 ","ABCD","930610087","99","0","1"," ","930610087 "," ","0","0","0","0" "9","000701 ","ABCD","930610088","34","0","1"," ","930610088 "," ","0","0","0","0" "10","000701 ","ABCD","930610088","99","0","1"," ","930610088 "," ","0","0","0","0" pipesmoker.py Description: pipesmoker.py ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python XML for newbie
Sean Carolan wrote: >> Thank you, this is helpful. Minidom is confusing, even the >> documentation confirms this: >> "The name of the functions are perhaps misleading" >> >>> But I'd start with the etree tutorial (of which >>> there are many variations on the web): > > Ok, so I read through these tutorials and am at least able to print > the XML output now. I did this: > > doc = etree.parse('computer_books.xml') > > and then this: > > for elem in doc.iter(): > print elem.tag, elem.text > > Here's the data I'm interested in: > > index 1 > field 11 > value 9780596526740 > datum > > How do you say, "If the field is 11, then print the next value"? The > raw XML looks like this: > > > 1 > 11 > 9780470286975 > > > Basically I just want to pull all these ISBN numbers from the file. With http://lxml.de/ you can use xpath: $ cat computer_books.xml 1 11 9780470286975 $ cat read_isbn.py from lxml import etree root = etree.parse("computer_books.xml") print root.xpath("//datum[field=11]/value/text()") $ python read_isbn.py ['9780470286975'] $ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Math Function and Python
On 02/07/12 05:21, Greg Nielsen wrote: models the acceleration of the object. Y is the acceleration and X is the current speed of the object. Y = -.01X^2 * 1.45X That's not the same as the formula you have implemented. it doesn't work. It's also in bold, so you can see it easily. if keys[pygame.K_UP] and self.dy < (15 + self.speedMod): if self.dy <= 0: /self.accelPoints += self.accelList[0]/ *#self.dy += 1* else: /self.accelPoints += self.accelList[self.dy]/ *#self.accelPoints += ((-.1 * (self.dy * self.dy)) + (1.45 * self.dy))* Are you sure the else is being executed? Have you tried inserting a print statement to check the value right after the block? I did a test, and for some reason, it seems like the output of the function is never saved into the self.accelPoints variable, because it always prints out as 0. If your dy is very close to zero the value of your formula will be very close to zero so accelPoints never increases. But you also commented out the dy increment line so dy never increases which migfht suggest the else never gets called?? Can you send us the actual code that fails rather than something else that nearly works? Its much easier to debug the thing that's actually broken that something that looks vaguely like it. outputs a double, but even when i make accelPoints a double (made it equal 0.01 instead of 0) it still didn't work. Provided they are both numbers Python will adapt. That's not likely to be the problem. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor