From amitsaha.in at gmail.com Tue Oct 1 00:26:03 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Tue, 1 Oct 2013 08:26:03 +1000 Subject: [Tutor] Easiest framework for web development? In-Reply-To: <5249413C.3050100@gmx.com> References: <5249413C.3050100@gmx.com> Message-ID: On Mon, Sep 30, 2013 at 7:15 PM, wrote: > Hi > > Which of the available Python frameworks is the EASIEST to learn for a > NEWBIE who needs to do *basic* web development? (only the *most basic* web > functionality will be needed) Only the *most basic* web functionality won't need you to use a Python web framework. It needs HTML and CSS and some Javascript at best. Now, I am sure you want more. You will get various answers, but I found Flask (http://flask.pocoo.org/) to be very easy to start with. I had no clue of any web frameworks when I started with it and found it very easy to get started with. The documentation is one of the best I have come across for any open source project. So, it should help you get started fairly easily. Although the quickstart guide: http://flask.pocoo.org/docs/quickstart/ has more than the basics, but it's a good idea to go through it as much as you can and experiment on your own. Hope that helps. -Amit -- http://echorand.me From alan.gauld at btinternet.com Tue Oct 1 00:36:31 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 30 Sep 2013 23:36:31 +0100 Subject: [Tutor] Easiest framework for web development? In-Reply-To: <5249413C.3050100@gmx.com> References: <5249413C.3050100@gmx.com> Message-ID: On 30/09/13 10:15, vitsen at gmx.com wrote: > Which of the available Python frameworks is the EASIEST to learn for a > NEWBIE who needs to do *basic* web development? (only the *most basic* > web functionality will be needed) The cgi module in the standard library is easy to learn if you only want *basic* functionality. But you will likely outgrow it fairly soon. Once you get beyond that you are into a labyrinth of options with every user having their own framework preference. The only way to see what suits you is to try them - or at least read thru some quick start guides or watch some YouTube videos. They all do pretty much the same things so it doesn't really make a lot of difference which you choose. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From ramit.prasad at jpmorgan.com.dmarc.invalid Tue Oct 1 00:40:58 2013 From: ramit.prasad at jpmorgan.com.dmarc.invalid (Prasad, Ramit) Date: Mon, 30 Sep 2013 22:40:58 +0000 Subject: [Tutor] Easiest framework for web development? In-Reply-To: <5249413C.3050100@gmx.com> References: <5249413C.3050100@gmx.com> Message-ID: <5B80DD153D7D744689F57F4FB69AF474187A4A8C@SCACMX008.exchad.jpmchase.net> vitsen at gmx.com wrote: > Sent: Monday, September 30, 2013 4:16 AM > To: tutor at python.org > Subject: [Tutor] Easiest framework for web development? > > Hi > > Which of the available Python frameworks is the EASIEST to learn for a > NEWBIE who needs to do *basic* web development? (only the *most basic* > web functionality will be needed) > > Could you please provide links to any relevant tutorials for learning > such a Python-based web framework? (again, possibly the easiest tutorial) > > Thanks > > Vit I have not tried most of the frameworks but I perused a Flask tutorial the other day that I seemed like a good fully-featured start. http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world A few other micro frameworks to look at are Bottle, CherryPy, Pyramid (previously Pylons), and web2py--there are many other options. You may also want to read what is on the Python website regarding various frameworks. https://wiki.python.org/moin/WebProgramming Interesting summary (not sure how accurate it is): http://www.sixfeetup.com/blog/4-python-web-frameworks-compared ~Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From vitsen at gmx.com Tue Oct 1 01:04:37 2013 From: vitsen at gmx.com (vitsen at gmx.com) Date: Tue, 01 Oct 2013 01:04:37 +0200 Subject: [Tutor] Easiest framework for web development? In-Reply-To: <5B80DD153D7D744689F57F4FB69AF474187A4A8C@SCACMX008.exchad.jpmchase.net> References: <5249413C.3050100@gmx.com> <5B80DD153D7D744689F57F4FB69AF474187A4A8C@SCACMX008.exchad.jpmchase.net> Message-ID: <524A0385.3090502@gmx.com> Are those simple web frameworks you mentioned to be found pre-installed on commercial hosting servers? I am asking because I would like to avoid having to install one myself. The ideal solution would be a Python-based web framework that is commonly supported (pre-installed) on commercial web hosting servers. I guess that Django would probably be one such framework, but then it belongs to another category, being very large and complex. I was thinking of simple/minimalistic web frameworks, like the ones you mentioned earlier. Any of those are to be found pre-installed on hosting servers? From steve at pearwood.info Tue Oct 1 03:25:59 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 1 Oct 2013 11:25:59 +1000 Subject: [Tutor] Creating To Do List Program - Question In-Reply-To: References: Message-ID: <20131001012558.GD7989@ando> On Mon, Sep 30, 2013 at 12:43:57AM +0100, Alan Gauld wrote: > On 29/09/13 21:42, Rafael Knuth wrote: > > >iteration. I know my program is super cheesy & primitive, but I don?t > >care, it does what I expect it to do, > > Really? You wrote a program that printed out a different > program to the one you ran and that's what you wanted? > It doesn't do anything about creating a ToDo list. > It doesn't even bring you any closer to creating a ToDo list. Ah, no I think I see what Rafael is trying to do! I remember those old BASIC listings from the 1970s where the first thing the program did was print out a page and a half of introductory text telling you what the program did and what commands to give to operate it. I reckon that's what he is doing. > >Welcome World's Most Geeky To Do List Program I don't think that word "Geeky" means what you think it means. It doesn't mean "incomplete". It's a bit much to claim the crown of World's Most Geeky program when you haven't actually written the program yet. That's like announcing that you are now Boxing Heavyweight Champion of the World after ordering a pair of boxing gloves online. > >G E E K L I S T 1 . 0 > > > >If you want to add items to the list, enter: > > > >text_file = open("ToDoList.txt", "w") > >text_file.write("add your item here ") > >text_file.write("add action item here ") > >text_file.write("you get the point, right?") > >text_file.close() And quite frankly, this is a rubbish to-do-list program. It relies on the user *writing the code for you*. A better design would be something like this: open "ToDoList.txt" print first three items print last item add "wash car" add "feed the cat" save add "return book to library" save remove item 2 print items 5-20 remove items 3-12, 17 save print all items Now that would be a cool todo list program that people could use! And an excellent programming challenge. It would require you to learn about reading and writing files, keeping information in memory, using a REPL (Read/Eval/Print Loop), and writing a parser for human-readable commands. Now *that's* geeky! -- Steven From steve at pearwood.info Tue Oct 1 03:27:25 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 1 Oct 2013 11:27:25 +1000 Subject: [Tutor] Creating To Do List Program - Questions In-Reply-To: <15c830b9-ae9a-4b75-9d87-85ab8dc9a422@email.android.com> References: <15c830b9-ae9a-4b75-9d87-85ab8dc9a422@email.android.com> Message-ID: <20131001012725.GE7989@ando> On Mon, Sep 30, 2013 at 12:19:15PM +0200, Dominik George wrote: > Plonk! Oh that's harsh, especially for a beginners list. -- Steven From steve at pearwood.info Tue Oct 1 03:32:33 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 1 Oct 2013 11:32:33 +1000 Subject: [Tutor] Creating To Do List Program - Question In-Reply-To: References: Message-ID: <20131001013232.GF7989@ando> On Mon, Sep 30, 2013 at 01:12:49PM +0200, Rafael Knuth wrote: > Hej there, > > @Alan @Joel: > I didn't know that pouring corn on newbies is the purpose of a tutor > mailing list. The word you want is "scorn", not corn. > I do not understand why you don't consider what I wrote not a program > ("Hello World!" in a more elaborate form), as the user is actually > able to a list, to write to and reads from it (in a very primitive > manner though). Can anyone explain? Your program doesn't do any work at all. It might as well be a blog post, or a post-it note stuck to the side of the computer with instructions. Now that's fine. If you want to teach other people how to program, telling them to write code like: textfile = open("ToDoList.txt", "r") textfile.write("Thing to do\n") textfile.close() is a perfectly legitimate thing to do. But that's not *programming*. You haven't written a to-do list program, you have written instructions for somebody else to save a to-do list. -- Steven From steve at pearwood.info Tue Oct 1 03:57:24 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 1 Oct 2013 11:57:24 +1000 Subject: [Tutor] Creating To Do List Program - Question In-Reply-To: References: Message-ID: <20131001015724.GG7989@ando> On Mon, Sep 30, 2013 at 01:30:55PM +0200, Rafael Knuth wrote: > I am still hoping that I will get some feedback from anyone on that > list that will help me make a tiny little next step. Be bold! Be adventurous! You don't need baby steps, this is not like climbing Mount Everest without oxygen! If you write a rubbish piece of code, just delete it and nobody but you will know. The first secret of programming is that programming shouldn't happen until quite late in the process. First you have to decide what your program should do. On a piece of paper, write down what you want your to-do list program to do: - should it have a single ToDo list? - or allow the user to specify their own custom list? - or maybe even use multiple lists at once? For the first version, I recommend that you stick with the first option, a single, hard-coded ToDo list. Actually, for the *very* first version, I recommend you don't even have a ToDo list, but just pretend to have one. What else should your program do? - It should manage opening and saving the list for the user. Otherwise, what is the point? - The user should be able to give commands to print the list, add items, remove items, ask for help, and quit. What else? That's probably plenty. That's already quite a lot for a beginner to deal with, so let's not get *too* far ahead. Now that you have an idea of what your program should do, let's think about the design: - Your program should automatically open the ToDo list and read the items into memory, ready to be operated on. - Then it should wait for the user's commands. - Not just a single command, but it should *repeatedly* wait for the next command. - When it sees a command, it should run that command, then wait for the next one. - Until the user tells it to quit or exit, then it should quit. Now, in my opinion, I think the most critical part here is the part where your program waits for commands. I think you should start with that, and not actually worry about the ToDo list part. To get you started, here's a way to have Python wait for you to type a command: # Using Python 3 command = input("Enter a command >>> ") command = command.strip().lower() if command == "exit" or command == "quit": print("Bye now!") elif command == "print" print("Printing all the things!") elif command == "add" print("Adding all the stuff!") else: print("I'm sorry, I don't understand that command.") That piece of code starts by waiting for the user to type something. It then converts it to lowercase and removes any unnecessary spaces at the start and end. Then it pretends to do something useful based on that command. It actually doesn't, it just prints a message, but actually doing something useful will follow later. And then it is done. Your mission, if you choose to accept it, is to start with the above snippet of code and put it inside a loop so that after each command, the program automatically waits for the next command. The tools you will need to solve this problem are: * Loops Python has two sorts of loops, for-loops and while-loops. In this case, while-loops are more useful. * Some way to get out of the loop. There are lots of ways of doing this, in this case I suggest the tool you want it the "break" statement. Have a go at that, and come back if you need help or when you're done. -- Steven From steve at pearwood.info Tue Oct 1 04:04:51 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 1 Oct 2013 12:04:51 +1000 Subject: [Tutor] Creating To Do List Program - Question In-Reply-To: References: Message-ID: <20131001020451.GH7989@ando> On Mon, Sep 30, 2013 at 03:00:08PM +0200, Rafael Knuth wrote: > I mean, my giant print > statement was really ridiculous to say the least but it did what I > wanted the program to do - adding items to the To Do List and printing > that list. But no it didn't! It just *printed* stuff you wanted to do, it didn't actually do them. That's like the difference between writing down the sentence: Today I went to the store and bought milk. and *actually* going to the store and buying milk. > > Are you using Python 3.3, under Windows? > > Python 3.0 under Windows. If you have the opportunity to upgrade, I strongly recommend that you use Python 3.3 instead. It is much better than older 3.x versions, and 3.0 in particular is buggy and not officially supported any longer. > I worked with text files yet, I have to admit I haven't worked with > binary files though - and I don't know yet what they are. But I will > figure that out. Technically, *all* files are binary files. That just means that they are stored on the disk as zeroes and ones. But when people talk about "text files" and "binary files", what they usually mean is "files where we interpret those zeroes and ones as code for letters of the alphabet" and "files where we interpret those zeroes and ones as code for numbers." There's a bit more to it than that, but it will do to start. -- Steven From akleider at sonic.net Tue Oct 1 05:16:49 2013 From: akleider at sonic.net (Alex Kleider) Date: Mon, 30 Sep 2013 20:16:49 -0700 Subject: [Tutor] sqlite3 COMMIT directive Message-ID: <673eeed8f58ad938359eba03c5697ff8@sonic.net> I'm just beginning to enter into the field of database and SQLite in particular. Python 2.7 on Ubuntu The problem code is a class method defined as follows: def insert(self, DataBase=DataBase, Table=Table): """ Insert instance of ClassMate into . """ con = sqlite3.connect(DataBase) with con: cur.execute("""INSERT INTO %s VALUES (NULL, '%s', '%s', '%s', '%s', '%s', '%s');""" % \ (Table, self.first, self.last, self.partner, self.address, self.phone, self.email, ) ) try: cur.execute("COMMIT;") except: pass And the problem = \ """ If the 'cur.execute("COMMIT;")' statement is left by itself, outside of a "try/except" clause, I get an error with the following trace back: " Traceback (most recent call last): File "./uwomeds68.py", line 119, in go_on.insert() File "./uwomeds68.py", line 64, in insert cur.execute("COMMIT;") sqlite3.OperationalError: cannot commit - no transaction is active " Without the COMMIT, there's no error but the data doesn't get added to the data base. """ I've been reading about the COMMIT directive but apart from its relationship with ROLLBACK, I haven't been able to figure out how it is relevant to my problem here. Any advice/explanation would of course be appreciated. Alex Kleider From nik at naturalnet.de Tue Oct 1 07:33:32 2013 From: nik at naturalnet.de (Dominik George) Date: Tue, 01 Oct 2013 07:33:32 +0200 Subject: [Tutor] sqlite3 COMMIT directive In-Reply-To: <673eeed8f58ad938359eba03c5697ff8@sonic.net> References: <673eeed8f58ad938359eba03c5697ff8@sonic.net> Message-ID: <9cd6b0f1-e464-454e-bbf0-cd547cd968ac@email.android.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA512 Hi, >sqlite3.OperationalError: cannot commit - no transaction is active That means that you have to execute "BEGIN TRANSACTION" before using atomic commits. http://www.sqlite.org/lang_transaction.html http://sqlite.org/transactional.html >I've been reading about the COMMIT directive but apart from its >relationship with ROLLBACK, I haven't been able to figure out how it is > >relevant to my problem here. It isn't. What is relevant is whether you use transactions or not. - -nik -----BEGIN PGP SIGNATURE----- Version: APG v1.0.8-fdroid iQFNBAEBCgA3BQJSSl6rMBxEb21pbmlrIEdlb3JnZSAobW9iaWxlIGtleSkgPG5p a0BuYXR1cmFsbmV0LmRlPgAKCRAvLbGk0zMOJSUPB/9bNtMNiXOf+k8mrVRr6+NC XBVMcSrXHIKbdojYthPNF7kT5DjVoEzvHPIwL01b+V7metjTA58FUGbE2CHP+0Ho Ydr60MlXt5VhqOYLHy7KF3nZ6mkutcLGhSJzncdhYeYZG9QSk3W1Z7/eyPLs3Pzk 77Y6NjF/b7R47ey4dXfalJbkE2TGyVVixPzVaLutXIIPqXQdLracqlPa/jen0esK j210UjCkMY/stlqEG0ADLX0PlNvyVYxuB/t70mRegj8GqX4txtOMDlJaasNJavkT J2niBAw3ftW04qpJjJgnvdxTnw0YgW7+rqhm6/1gvLsPopnKStYp3NAFvXuidI1U =L3tk -----END PGP SIGNATURE----- From alan.gauld at btinternet.com Tue Oct 1 09:49:07 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 01 Oct 2013 08:49:07 +0100 Subject: [Tutor] Creating To Do List Program - Question In-Reply-To: <20131001012558.GD7989@ando> References: <20131001012558.GD7989@ando> Message-ID: On 01/10/13 02:25, Steven D'Aprano wrote: > Ah, no I think I see what Rafael is trying to do! I remember those old > BASIC listings from the 1970s where the first thing the program did was > print out a page and a half of introductory text telling you what the > program did and what commands to give to operate it. I reckon that's > what he is doing. A light bulb moment! Rafael, how are you running your program? If you are running it from the Python >>> prompt then what Steven says makes sense and what you are trying to do makes sense too. And its the wrong way to go about things. What I think you are trying to do is print out a list of Python commands that your user can type into the >>> prompt. Is that right? If so that is the source of the apparently severe comments you've received. That's not how to run a Python program. The >>> prompt is only for experimenting with Python, not for running programs. We were assuming that you were typing the code into a file (called, say, ToDo.py) and running that by double clicking it in Explorer. Windows then starts Python in the background and it executes the code in ToDo.py. That way the user never has to type in any Python code. They just respond to prompts that you create. Now, maybe I've misread the situation but if I'm right it would explain why you were creating a big print statement and how you got the "program" to do something. Can you clarify exactly how you create and run your program? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Tue Oct 1 10:03:11 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 01 Oct 2013 09:03:11 +0100 Subject: [Tutor] sqlite3 COMMIT directive In-Reply-To: <673eeed8f58ad938359eba03c5697ff8@sonic.net> References: <673eeed8f58ad938359eba03c5697ff8@sonic.net> Message-ID: On 01/10/13 04:16, Alex Kleider wrote: > And the problem = \ > """ > If the 'cur.execute("COMMIT;")' statement is left by itself, outside of a > "try/except" clause, I get an error with the following trace back: > " > Traceback (most recent call last): > File "./uwomeds68.py", line 119, in > go_on.insert() > File "./uwomeds68.py", line 64, in insert > cur.execute("COMMIT;") > sqlite3.OperationalError: cannot commit - no transaction is active You don't normally need to use COMMIT when programming SQLite from Python, the database starts and ends transactions automatically from within the execute() function. You only need to manually commit if you manually create the transaction using BEGIN... > Without the COMMIT, there's no error but the data doesn't get added to > the data base. That suggests that you are opening the wrong database file or you have a permissions problem or there is some other error. But you should not need a COMMIT. BTW. I notice you are using an implicit cursor within the with block. Now while that may work, my personal preference is for explicit variables, I just find it keeps the code clearer to explicitly create the cursor rather than have a variable appear in my code with no definition. It's OK in short snippets but as the code gets bigger it can get confusing. But that's just my own preference... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Tue Oct 1 10:11:35 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 01 Oct 2013 09:11:35 +0100 Subject: [Tutor] sqlite3 COMMIT directive In-Reply-To: References: <673eeed8f58ad938359eba03c5697ff8@sonic.net> Message-ID: On 01/10/13 09:03, Alan Gauld wrote: > BTW. I notice you are using an implicit cursor within the with block. > Now while that may work, my personal preference is for explicit > variables, ... Actually I'm not sure how it is working. I've just read the docs again and it seems to me that your code should be referencing 'con' not 'cur'. That may be part of the problem... >> con = sqlite3.connect(DataBase) >> with con: >> cur.execute("""INSERT INTO %s VALUES >> (NULL, '%s', '%s', '%s', '%s', '%s', '%s');""" % \ >> (Table, self.first, self.last, self.partner, >> self.address, self.phone, self.email, ) ) HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From i.sheeha at gmail.com Tue Oct 1 10:08:00 2013 From: i.sheeha at gmail.com (Ismar Sehic) Date: Tue, 1 Oct 2013 10:08:00 +0200 Subject: [Tutor] soappy, soap, xml ..fuss Message-ID: hello, it's me again with my stubborn soap and xml request.please take a look at this code and the output, just tell if i'm missing something - i don't get it. ---- > code > ''' > Created on 30.09.2013 > > @author: i.sehic > ''' > import SOAPpy > from xml.etree.ElementTree import Element, SubElement, tostring > import pprint > > class HotelbedsRequests(): > > def __init__(self): > self.wsdlFile = 'http://testapi.interface-xml.com/appservices > /ws/FrontendService?wsdl' > self.server = SOAPpy.WSDL.Proxy(self.wsdlFile) > > def sendPriceRequest(self, adults, children_, hotel = "", room = "", > board = ""): > > header = """""" > > root = Element('soapenv:Envelope', {"soapenv:encodingStyle":" > http://schemas.xmlsoap.org/soap/encoding/", "xmlns:soapenv":" > http://schemas.xmlsoap.org/soap/envelope/", "xmlns:xsi":" > http://www.w3.org/2001/XMLSchema-instance" }) > body = SubElement(root, "soapenv:Body") > getrequest = SubElement(body, "hb:getHotelValuedAvail", > {"xmlns:hb":"http://axis.frontend.hydra.hotelbeds.com", > "xsi:type":"xsd:string"}) > getavailrp = SubElement(getrequest, "HotelValuedAvailRQ", > {"echoToken":"DummyEchoToken", "sessionId":"DummySessionId", "xmlns":" > http://www.hotelbeds.com/schemas/2005/06/messages", "xmlns:xsi":" > http://www.w3.org/2001/XMLSchema-instance", "xsi:schemaLocation":" > http://www.hotelbeds.com/schemas/2005/06/messagesHotelValuedAvailRQ.xsd"}) > language = SubElement(getavailrp, "Language") > language.text = "ENG" > credentials = SubElement(getavailrp, "Credentials") > user = SubElement(credentials, "User") > user.text = "xxxxxxxxxxxx" > pw = SubElement(credentials, "Password") > pw.text = "xxxxxxxxxxxx" > paginationdata = SubElement(getavailrp, "PaginationData", > {"pageNumber":'1'}) > checkin = SubElement(getavailrp, "CheckInDate", > {"date":"20130814"}) > checkout = SubElement(getavailrp, "CheckOutDate", > {"date":"20130819"}) > desti = SubElement(getavailrp, "Destination", {"code":"PMI", > "type": "SIMPLE"}) > occupancylist = SubElement(getavailrp, "OccupancyList") > occupancyhotel = SubElement(occupancylist, "HotelOccupancy") > roomcount = SubElement(occupancyhotel, "RoomCount") > roomcount.text = "1" > occu = SubElement(occupancyhotel, "Occupancy") > adult = SubElement(occu, "AdultCount") > adult.text = str(adults) > #adult.text = str(adult) > children = SubElement(occu, "ChildCount") > children.text = str(children_) > #children.text = str(children) > > > xmlstring = header + tostring(root) > pprint.pprint(xmlstring) > > > print self.server.methods.keys() > > self.server.getHotelValuedAvail(xmlstring) > callInfo = self.server.methods['getHotelValuedAvail'] > > print callInfo.inparams > print callInfo.inparams[0].name > print callInfo.inparams[0].type > > print callInfo.outparams > print callInfo.outparams[0].name > print callInfo.outparams[0].type > > > def readHotelPriceResponse(self): > pass > > > > HotelbedsRequests().sendPriceRequest(2, 1) > ----->output: /usr/lib/pymodules/python2.6/SOAPpy/wstools/XMLSchema.py:2871: > DeprecationWarning: object.__init__() takes no parameters > tuple.__init__(self, args) > ' soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" > xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi=" > http://www.w3.org/2001/XMLSchema-instance"> xmlns:hb="http://axis.frontend.hydra.hotelbeds.com" > xsi:type="xsd:string"> sessionId="DummySessionId" xmlns=" > http://www.hotelbeds.com/schemas/2005/06/messages" xmlns:xsi=" > http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" > http://www.hotelbeds.com/schemas/2005/06/messagesHotelValuedAvailRQ.xsd">ENGxxxxxxxx pageNumber="1" /> date="20130819" /> />121' > [u'purchaseConfirm', u'getHotelCategoryList', u'getZoneGroupList', > u'getPurchaseList', u'getHotelRoomTypeGroupList', u'purchaseCancel', > u'getTicketValuation', u'getCountryList', u'getHotelBoardGroupList', > u'getPurchaseDetail', u'serviceAdd', u'getHotelDetail', > u'cancelProtectionAdd', u'getIncomingOfficeList', u'purchaseFlush', > u'getTicketCountryList', u'getCarCountryList', u'cancelProtectionRemove', > u'getCarValuedAvail', u'getTicketDetail', u'getCancelProtectionAvail', > u'serviceRemove', u'getCarInfoSet', u'getIncomingOfficeDetail', > u'getHotelBoardList', u'getDestinationGroupList', > u'getHotelCategoryGroupList', u'getHotelList', u'getTransferValuedAvail', > u'getHotelValuedAvail', u'getTicketAvail', u'getTicketClassificationList', > u'getTransferCountryList', u'getHotelCountryList'] > Traceback (most recent call last): > File "soappy.py", line 71, in > HotelbedsRequests().sendPriceRequest(2, 1) > File "soappy.py", line 54, in sendPriceRequest > self.server.getHotelValuedAvail(xmlstring) > File "/usr/lib/pymodules/python2.6/SOAPpy/Client.py", line 470, in > __call__ > return self.__r_call(*args, **kw) > File "/usr/lib/pymodules/python2.6/SOAPpy/Client.py", line 492, in > __r_call > self.__hd, self.__ma) > File "/usr/lib/pymodules/python2.6/SOAPpy/Client.py", line 363, in __call > config = self.config) > File "/usr/lib/pymodules/python2.6/SOAPpy/Client.py", line 187, in call > r.endheaders() > File "/usr/lib/python2.6/httplib.py", line 904, in endheaders > self._send_output() > File "/usr/lib/python2.6/httplib.py", line 776, in _send_output > self.send(msg) > File "/usr/lib/python2.6/httplib.py", line 735, in send > self.connect() > File "/usr/lib/python2.6/httplib.py", line 716, in connect > self.timeout) > File "/usr/lib/python2.6/socket.py", line 514, in create_connection > raise error, msg > socket.error: [Errno 110] Connection timed out > what could cause this socket error?and what is this Deprecation Warning?i don't get it anymore, i tried all the possible ways - with simple http request i get an internal server error [500].i wrote an email to the people at hotelbeds services 7 days ago, still waiting for the reply.how do i make this API, i cannot get simple xml request through. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Tue Oct 1 10:25:14 2013 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 01 Oct 2013 09:25:14 +0100 Subject: [Tutor] sqlite3 COMMIT directive In-Reply-To: References: <673eeed8f58ad938359eba03c5697ff8@sonic.net> Message-ID: <524A86EA.6000701@timgolden.me.uk> On 01/10/2013 09:03, Alan Gauld wrote: > You don't normally need to use COMMIT when programming SQLite from > Python, the database starts and ends transactions automatically from > within the execute() function. You only need to manually commit if you > manually create the transaction using BEGIN... Not so, I'm afraid. If you want autocommit, you need to send an isolation_level of None to the .connect function. If you don't, the database will rollback any uncommitted transactions on exit. The code below will only output (1,) as that value was committed. The later row is lost when the cursor/db closes. import os, sys import sqlite3 dbname = "no-commit.db" if os.path.exists(dbname): os.unlink(dbname) db = sqlite3.connect(dbname) q = db.cursor() q.execute("CREATE TABLE test(a INT)") q.execute("INSERT INTO test(a) VALUES (1)") db.commit() q.execute("INSERT INTO test(a) VALUES (2)") q.close() db.close() db = sqlite3.connect(dbname) q = db.cursor() for row in q.execute("SELECT * FROM test").fetchall(): print(row) q.close() db.close() From breamoreboy at yahoo.co.uk Tue Oct 1 10:40:07 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 01 Oct 2013 09:40:07 +0100 Subject: [Tutor] sqlite3 COMMIT directive In-Reply-To: <673eeed8f58ad938359eba03c5697ff8@sonic.net> References: <673eeed8f58ad938359eba03c5697ff8@sonic.net> Message-ID: On 01/10/2013 04:16, Alex Kleider wrote: > try: > cur.execute("COMMIT;") > except: > pass > > And the problem = \ > """ > If the 'cur.execute("COMMIT;")' statement is left by itself, outside of a > "try/except" clause, I get an error with the following trace back: > " > Traceback (most recent call last): > File "./uwomeds68.py", line 119, in > go_on.insert() > File "./uwomeds68.py", line 64, in insert > cur.execute("COMMIT;") > sqlite3.OperationalError: cannot commit - no transaction is active > " > As you've already had some sound advice I'd just like to point out that a bare except is considered bad form, e.g. it would mask any attempt to use CTRL-C to halt a rouge program that's inadvertantly gone into an infinite loop. An obvious one to use here could be the given sqlite3.OperationalError. Common problems that are caught include NameError, IndexError and ScrewedUpCompletelyError :) -- Cheers. Mark Lawrence From wprins at gmail.com Tue Oct 1 11:42:57 2013 From: wprins at gmail.com (Walter Prins) Date: Tue, 1 Oct 2013 10:42:57 +0100 Subject: [Tutor] soappy, soap, xml ..fuss In-Reply-To: References: Message-ID: Hi, On 1 October 2013 09:08, Ismar Sehic wrote: > hello, it's me again with my stubborn soap and xml request.please take a > look at this code and the output, just tell if i'm missing something - i > don't get it. > >> File "/usr/lib/python2.6/socket.py", line 514, in create_connection >> raise error, msg >> socket.error: [Errno 110] Connection timed out >> > > what could cause this socket error? > You're getting a generic socket error. This implies the website/web service might be down, or that the address you're using to contact it is in fact incorrect. (Or, your computer might not be connected to the internet, but I'm pretty sure that's not the problem here ;) ) > and what is this Deprecation Warning? > It's some sort of internal deprecation warning in SOAPpy, you can probably ignore it for now. > i don't get it anymore, i tried all the possible ways - with simple http > request i get an internal server error [500].i wrote an email to the people > at hotelbeds services 7 days ago, still waiting for the reply.how do i make > this API, i cannot get simple xml request through. > You're still messing with manually constructing XML requests to feed to the SOAP service. Don't do that. The entire point of libraries like SOAPpy and ZSI is to mostly shield your from all the XML under the hood. That said, as mentioned before, it seems to me you have more fundamental issues here, e.g. contacting/talking to the web service. You should be able to paste for example the WSDL URL into your browser and get the WSDL document displayed in your browser. If you can't even do that, then it obviously won't work when you try to contact the same URL via your program. I'd suggest you go find a working web service, and experiment interfacing with that first. You can hopefully find some to work with here: http://www.webservicex.net/WS/wscatlist.aspx Once you've got some confidence working with a simple working web service using SOAPpy, you should return to this problem. You should be able to introspect the Python API provided to you from the webservice directly using the Python interpreter, and then directly call the web service methods, with zero manual construction of XML required. See these pages: http://www.diveintopython.net/soap_web_services/introspection.html http://users.skynet.be/pascalbotte/rcx-ws-doc/python.htm Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From akleider at sonic.net Tue Oct 1 11:57:03 2013 From: akleider at sonic.net (Alex Kleider) Date: Tue, 01 Oct 2013 02:57:03 -0700 Subject: [Tutor] sqlite3 COMMIT directive In-Reply-To: <673eeed8f58ad938359eba03c5697ff8@sonic.net> References: <673eeed8f58ad938359eba03c5697ff8@sonic.net> Message-ID: Thank you to respondents. That the code worked at all is something I don't understand. As Alan G pointed out, I had forgotten to include the "cur = con.cursor()" line. After this was corrected and the try/except statement deleted, it worked as I expected. Thanks to "-nick" for pointing me to the references regarding transactions. That's not easy stuff. I was aware that 'bare except' statements are to be eschewed but now, thanks to Mark Lawrence, have a better idea of why. Much appreciated. alex From alan.gauld at btinternet.com Tue Oct 1 12:28:14 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 01 Oct 2013 11:28:14 +0100 Subject: [Tutor] sqlite3 COMMIT directive In-Reply-To: <524A86EA.6000701@timgolden.me.uk> References: <673eeed8f58ad938359eba03c5697ff8@sonic.net> <524A86EA.6000701@timgolden.me.uk> Message-ID: On 01/10/13 09:25, Tim Golden wrote: > On 01/10/2013 09:03, Alan Gauld wrote: >> You don't normally need to use COMMIT when programming SQLite from >> Python, the database starts and ends transactions automatically from >> within the execute() function. > > Not so, I'm afraid. If you want autocommit, you need to send an > isolation_level of None to the .connect function. Hmm, I didn't express that as I should but I was meaning within a 'with' block (which the OP was using) based on this comment in the docs: """ Connection objects can be used as context managers that automatically commit or rollback transactions. In the event of an exception, the transaction is rolled back; otherwise, the transaction is committed: """ Now I admit I didn't test it but I read that to imply that the with would autocommit. Am I mistaken? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From i.sheeha at gmail.com Tue Oct 1 12:16:20 2013 From: i.sheeha at gmail.com (Ismar Sehic) Date: Tue, 1 Oct 2013 12:16:20 +0200 Subject: [Tutor] Tutor Digest, Vol 116, Issue 4 In-Reply-To: References: Message-ID: great, thanks for the quick reply, Walter.i will follow your advice and see what happens.:) On Tue, Oct 1, 2013 at 12:00 PM, wrote: > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > https://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Re: sqlite3 COMMIT directive (Tim Golden) > 2. Re: sqlite3 COMMIT directive (Mark Lawrence) > 3. Re: soappy, soap, xml ..fuss (Walter Prins) > 4. Re: sqlite3 COMMIT directive (Alex Kleider) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Tue, 01 Oct 2013 09:25:14 +0100 > From: Tim Golden > To: tutor at python.org > Subject: Re: [Tutor] sqlite3 COMMIT directive > Message-ID: <524A86EA.6000701 at timgolden.me.uk> > Content-Type: text/plain; charset=ISO-8859-1 > > On 01/10/2013 09:03, Alan Gauld wrote: > > You don't normally need to use COMMIT when programming SQLite from > > Python, the database starts and ends transactions automatically from > > within the execute() function. You only need to manually commit if you > > manually create the transaction using BEGIN... > > Not so, I'm afraid. If you want autocommit, you need to send an > isolation_level of None to the .connect function. If you don't, the > database will rollback any uncommitted transactions on exit. > > The code below will only output (1,) as that value was committed. The > later row is lost when the cursor/db closes. > > > import os, sys > import sqlite3 > > dbname = "no-commit.db" > if os.path.exists(dbname): > os.unlink(dbname) > > db = sqlite3.connect(dbname) > q = db.cursor() > q.execute("CREATE TABLE test(a INT)") > q.execute("INSERT INTO test(a) VALUES (1)") > db.commit() > q.execute("INSERT INTO test(a) VALUES (2)") > q.close() > db.close() > > db = sqlite3.connect(dbname) > q = db.cursor() > for row in q.execute("SELECT * FROM test").fetchall(): > print(row) > q.close() > db.close() > > > > > > > ------------------------------ > > Message: 2 > Date: Tue, 01 Oct 2013 09:40:07 +0100 > From: Mark Lawrence > To: tutor at python.org > Subject: Re: [Tutor] sqlite3 COMMIT directive > Message-ID: > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 01/10/2013 04:16, Alex Kleider wrote: > > try: > > cur.execute("COMMIT;") > > except: > > pass > > > > And the problem = \ > > """ > > If the 'cur.execute("COMMIT;")' statement is left by itself, outside of a > > "try/except" clause, I get an error with the following trace back: > > " > > Traceback (most recent call last): > > File "./uwomeds68.py", line 119, in > > go_on.insert() > > File "./uwomeds68.py", line 64, in insert > > cur.execute("COMMIT;") > > sqlite3.OperationalError: cannot commit - no transaction is active > > " > > > > As you've already had some sound advice I'd just like to point out that > a bare except is considered bad form, e.g. it would mask any attempt to > use CTRL-C to halt a rouge program that's inadvertantly gone into an > infinite loop. An obvious one to use here could be the given > sqlite3.OperationalError. Common problems that are caught include > NameError, IndexError and ScrewedUpCompletelyError :) > > -- > Cheers. > > Mark Lawrence > > > > ------------------------------ > > Message: 3 > Date: Tue, 1 Oct 2013 10:42:57 +0100 > From: Walter Prins > Cc: python mail list > Subject: Re: [Tutor] soappy, soap, xml ..fuss > Message-ID: > < > CANLXbfA948X8ov7tPBVMXi-x-kiYav9Y0JfmWCJPu233dRpPjQ at mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > Hi, > > > On 1 October 2013 09:08, Ismar Sehic wrote: > > > hello, it's me again with my stubborn soap and xml request.please take a > > look at this code and the output, just tell if i'm missing something - i > > don't get it. > > > >> File "/usr/lib/python2.6/socket.py", line 514, in create_connection > >> raise error, msg > >> socket.error: [Errno 110] Connection timed out > >> > > > > what could cause this socket error? > > > > You're getting a generic socket error. This implies the website/web > service might be down, or that the address you're using to contact it is in > fact incorrect. (Or, your computer might not be connected to the internet, > but I'm pretty sure that's not the problem here ;) ) > > > > and what is this Deprecation Warning? > > > > It's some sort of internal deprecation warning in SOAPpy, you can probably > ignore it for now. > > > > > i don't get it anymore, i tried all the possible ways - with simple http > > request i get an internal server error [500].i wrote an email to the > people > > at hotelbeds services 7 days ago, still waiting for the reply.how do i > make > > this API, i cannot get simple xml request through. > > > > You're still messing with manually constructing XML requests to feed to the > SOAP service. Don't do that. The entire point of libraries like SOAPpy > and ZSI is to mostly shield your from all the XML under the hood. That > said, as mentioned before, it seems to me you have more fundamental issues > here, e.g. contacting/talking to the web service. You should be able to > paste for example the WSDL URL into your browser and get the WSDL document > displayed in your browser. If you can't even do that, then it obviously > won't work when you try to contact the same URL via your program. > > I'd suggest you go find a working web service, and experiment interfacing > with that first. You can hopefully find some to work with here: > http://www.webservicex.net/WS/wscatlist.aspx > > Once you've got some confidence working with a simple working web service > using SOAPpy, you should return to this problem. You should be able to > introspect the Python API provided to you from the webservice directly > using the Python interpreter, and then directly call the web service > methods, with zero manual construction of XML required. See these pages: > http://www.diveintopython.net/soap_web_services/introspection.html > http://users.skynet.be/pascalbotte/rcx-ws-doc/python.htm > > Walter > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20131001/ddf69198/attachment-0001.html > > > > ------------------------------ > > Message: 4 > Date: Tue, 01 Oct 2013 02:57:03 -0700 > From: Alex Kleider > To: Python Tutor > Subject: Re: [Tutor] sqlite3 COMMIT directive > Message-ID: > Content-Type: text/plain; charset=UTF-8; format=flowed > > Thank you to respondents. > > That the code worked at all is something I don't understand. > As Alan G pointed out, I had forgotten to include the "cur = > con.cursor()" line. > After this was corrected and the try/except statement deleted, it worked > as I expected. > > Thanks to "-nick" for pointing me to the references regarding > transactions. That's not easy stuff. > I was aware that 'bare except' statements are to be eschewed but now, > thanks to Mark Lawrence, have a better idea of why. > > Much appreciated. > > alex > > > ------------------------------ > > Subject: Digest Footer > > _______________________________________________ > Tutor maillist - Tutor at python.org > https://mail.python.org/mailman/listinfo/tutor > > > ------------------------------ > > End of Tutor Digest, Vol 116, Issue 4 > ************************************* > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Tue Oct 1 12:41:03 2013 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 01 Oct 2013 11:41:03 +0100 Subject: [Tutor] sqlite3 COMMIT directive In-Reply-To: References: <673eeed8f58ad938359eba03c5697ff8@sonic.net> <524A86EA.6000701@timgolden.me.uk> Message-ID: <524AA6BF.9050806@timgolden.me.uk> On 01/10/2013 11:28, Alan Gauld wrote: > On 01/10/13 09:25, Tim Golden wrote: >> On 01/10/2013 09:03, Alan Gauld wrote: >>> You don't normally need to use COMMIT when programming SQLite from >>> Python, the database starts and ends transactions automatically from >>> within the execute() function. >> >> Not so, I'm afraid. If you want autocommit, you need to send an >> isolation_level of None to the .connect function. > > Hmm, I didn't express that as I should but I was meaning within > a 'with' block (which the OP was using) based on this comment > in the docs: > > """ > Connection objects can be used as context managers that automatically > commit or rollback transactions. In the event of an exception, the > transaction is rolled back; otherwise, the transaction is committed: > """ > > Now I admit I didn't test it but I read that to imply that the with > would autocommit. Am I mistaken? You're sort-of correct. What happens is that the database doesn't enter autocommit mode (you'll still need to specify the right isolation level on the .connect for that). Rather, the __exit__ method of the connection-as-context-manager issues the db.commit() call which will commit anything outstanding. TJG From alan.gauld at btinternet.com Tue Oct 1 13:05:20 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 01 Oct 2013 12:05:20 +0100 Subject: [Tutor] sqlite3 COMMIT directive In-Reply-To: <524AA6BF.9050806@timgolden.me.uk> References: <673eeed8f58ad938359eba03c5697ff8@sonic.net> <524A86EA.6000701@timgolden.me.uk> <524AA6BF.9050806@timgolden.me.uk> Message-ID: On 01/10/13 11:41, Tim Golden wrote: >>>> Python, the database starts and ends transactions automatically from >>>> within the execute() function. >>> >>> Not so, I'm afraid. If you want autocommit, you need to send an >>> isolation_level of None to the .connect function. >> """ >> Connection objects can be used as context managers that automatically >> commit or rollback transactions. > > You're sort-of correct. What happens is that the database doesn't enter > autocommit mode (you'll still need to specify the right isolation level > on the .connect for that). Rather, the __exit__ method of the > connection-as-context-manager issues the db.commit() call which will > commit anything outstanding. OK, That makes sense it's a bit like the file close at the end of a with block. So the docs statement that it automatically commits *transactions* is slightly misleading as it only commits the full content of the block which could hold multiple transactions. Thanks for the clarification Tim. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From mail at timgolden.me.uk Tue Oct 1 13:05:55 2013 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 01 Oct 2013 12:05:55 +0100 Subject: [Tutor] sqlite3 COMMIT directive In-Reply-To: <524AA6BF.9050806@timgolden.me.uk> References: <673eeed8f58ad938359eba03c5697ff8@sonic.net> <524A86EA.6000701@timgolden.me.uk> <524AA6BF.9050806@timgolden.me.uk> Message-ID: <524AAC93.8050707@timgolden.me.uk> On 01/10/2013 11:41, Tim Golden wrote: > You're sort-of correct. What happens is that the database doesn't enter > autocommit mode (you'll still need to specify the right isolation level > on the .connect for that). Rather, the __exit__ method of the > connection-as-context-manager issues the db.commit() call which will > commit anything outstanding. Re-reading, we may be using the term "autocommit" in two different ways. I'm using it to refer to a database-internal option where each SQL operation is committed as soon as it completes. This mode of operation is initiated (from Python) by passing an isolation_level of "None" when creating the connection. The "with sqlite3.connect..." approach could be considered a Python-level autocommit where all the operations within the block are committed by virtue of the Python context-manager mechanism which invokes the usual database "COMMIT" operation on exit. In case it helps... TJG From mahesh.d-n at hp.com Tue Oct 1 13:00:36 2013 From: mahesh.d-n at hp.com (D N, Mahesh) Date: Tue, 1 Oct 2013 11:00:36 +0000 Subject: [Tutor] PYTHON 2.5.6 64 Bit Compilation is failing on Aix Message-ID: <04DDCD62EB1CBB4EAF6BE6116D8F013F154A5BB1@G2W2445.americas.hpqcorp.net> Hi, While compiling python2.5.6 by passing 64 bit arguments on aix5.3, make is failing . Command used to build: ./configure --with-gcc="xlc_r -q64" --with-cxx="xlC_r -q64" --disable-ipv6 AR="ar -X64" --prefix=/usr/prasad/python --disable-shared --with-libs='/usr/prasad/ncurses/lib/libncurses.a' --without-threads --with-ncurses=/usr/prasad/ncurses/lib Make error. ./Modules/ld_so_aix xlc_r -q64 -bI:Modules/python.exp build/temp.aix-5.3-2.5/home/dnm/pyth/Python-2.5.6/Modules/_cursesmodule.o -L/usr/local/lib -lncursesw -o build/lib.aix-5.3-2.5/_curses.so ld: 0711-317 ERROR: Undefined symbol: _unctrl ld: 0711-317 ERROR: Undefined symbol: .setsyx ld: 0711-317 ERROR: Undefined symbol: ._setqiflush ld: 0711-317 ERROR: Undefined symbol: .initscr32 ld: 0711-317 ERROR: Undefined symbol: wacs_map ld: 0711-317 ERROR: Undefined symbol: ._getsyx ld: 0711-317 ERROR: Undefined symbol: .w32attrset ld: 0711-317 ERROR: Undefined symbol: .w32insch ld: 0711-317 ERROR: Undefined symbol: .p32echochar ld: 0711-317 ERROR: Undefined symbol: .w32echochar ld: 0711-317 ERROR: Undefined symbol: .box32 ld: 0711-317 ERROR: Undefined symbol: .w32attron ld: 0711-317 ERROR: Undefined symbol: .w32attroff ld: 0711-317 ERROR: Undefined symbol: .w32addch ld: 0711-345 Use the -bloadmap or -bnoquiet option to obtain more information. *** WARNING: renaming "_curses" since importing it failed: No such file or directory error: No such file or directory make: 1254-004 The error code from the last command is 1. Could you please help me to resolve the above mentioned error. Regards, Mahesh -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosaelise47 at gmail.com Tue Oct 1 20:21:18 2013 From: rosaelise47 at gmail.com (Elise Rosa) Date: Tue, 1 Oct 2013 14:21:18 -0400 Subject: [Tutor] Python for SPSS help Message-ID: Hello! I'm using Python in SPSS to rename and arrange some files. The setup is this: I have many .txt files in a folder, and I'd like to first remove part of their names. Next, I need to paste the second and third columns from each .txt file into another document (could be an excel sheet), and match them all by the first column in each .txt file (subject number). I also need to rename the second and third columns when they are going into the excel file with the name of the .txt file they came from. Any help would be greatly appreciated! Thank you! -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Oct 1 20:43:37 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 01 Oct 2013 19:43:37 +0100 Subject: [Tutor] PYTHON 2.5.6 64 Bit Compilation is failing on Aix In-Reply-To: <04DDCD62EB1CBB4EAF6BE6116D8F013F154A5BB1@G2W2445.americas.hpqcorp.net> References: <04DDCD62EB1CBB4EAF6BE6116D8F013F154A5BB1@G2W2445.americas.hpqcorp.net> Message-ID: On 01/10/13 12:00, D N, Mahesh wrote: > While compiling python2.5.6 by passing 64 bit arguments on aix5.3, make > is failing . The tutor list is for folks learning the Python language and standard library. You might find somebody here familiar with compiling on AIX (although maybe not v2.5 - why so old?) but you are much more likely to get success on the main Python mailing list/newsgroup.(comp.lang.python). -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Tue Oct 1 20:47:51 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 01 Oct 2013 19:47:51 +0100 Subject: [Tutor] Python for SPSS help In-Reply-To: References: Message-ID: On 01/10/13 19:21, Elise Rosa wrote: > Hello! > > I'm using Python in SPSS to rename and arrange some files. The setup is > this: I have many .txt files in a folder, and I'd like to first remove > part of their names. Next, I need to paste the second and third columns > from each .txt file into another document (could be an excel sheet), and > match them all by the first column in each .txt file (subject number). I > also need to rename the second and third columns when they are going > into the excel file with the name of the .txt file they came from. Doesn't look like SPSS is particularly significant it's just text file manipulation. Given you mention the data being in columns and you want to manipulate the column names it sounds like the CSV module should be able to help. Are you familiar or have you looked at csv yet? If not take a look at the docs then come back with any questions. For manipulating file names the standard os/path/shutil modules should provide all you need combined with some string processing. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From s.charonis at gmail.com Wed Oct 2 00:43:09 2013 From: s.charonis at gmail.com (Spyros Charonis) Date: Tue, 1 Oct 2013 23:43:09 +0100 Subject: [Tutor] Arbitrary-argument set function Message-ID: Dear Pythoners, I am trying to extract from a set of about 20 sequences, the characters which are unique to each sequence. For simplicity, imagine I have only 3 "sequences" (words in this example) such as: s1='spam'; s2='scam', s3='slam' I would like the character that is unique to each sequence, i.e. I need my function to return the list [ 'p', 'c', ',l' ]. This function I am using is as follows: def uniq(*args): """ FIND UNIQUE ELEMENTS OF AN ARBITRARY NUMBER OF SEQUENCES""" unique = [] for i in args[0]: if i not in args[1:]: unique.append(i) return unique and is returning the list [ 's', 'p', 'a', 'm' ]. Any help much appreciated, Best, Spyros -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Wed Oct 2 01:00:00 2013 From: davea at davea.name (Dave Angel) Date: Tue, 1 Oct 2013 23:00:00 +0000 (UTC) Subject: [Tutor] Arbitrary-argument set function References: Message-ID: On 1/10/2013 18:43, Spyros Charonis wrote: > Dear Pythoners, > > > I am trying to extract from a set of about 20 sequences, the characters > which are unique to each sequence. For simplicity, imagine I have only 3 > "sequences" (words in this example) such as: > > > s1='spam'; s2='scam', s3='slam' > > > I would like the character that is unique to each sequence, i.e. I need my > function to return the list [ 'p', 'c', ',l' ]. This function I am using is > as follows: > Suggest you turn each sequence into a set, and use set difference to find all the characters that aren't in any other set. So you make a list of such sets (perhaps 20 items in the list). Now just loop through the sets, subtracting from each one all the others. Simple double-nested loop. -- DaveA From alan.gauld at btinternet.com Wed Oct 2 02:17:24 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 02 Oct 2013 01:17:24 +0100 Subject: [Tutor] Arbitrary-argument set function In-Reply-To: References: Message-ID: On 01/10/13 23:43, Spyros Charonis wrote: > I am trying to extract from a set of about 20 sequences, the characters > which are unique to each sequence. For simplicity, imagine I have only 3 > "sequences" (words in this example) such as: > > > s1='spam'; s2='scam', s3='slam' > > > I would like the character that is unique to each sequence, i.e. I need > my function to return the list [ 'p', 'c', ',l' ]. Do you need them in that order or are you only looking for a list of characters that appear in a single sequence? Also what happens if a sequence has more than one unique character? If its only unique letters you want I'd do it this way (which may not be optimal!) loop over each string and from it create a dict of the individual letters with the current string as the value. At the end any dict entries with one string in the value list is unique to that string so in your example the dict would look like: { s: ['spam','scam','slam'], p: ['spam'], a: ['spam','scam','slam'], m: ['spam','scam','slam'], c: ['scam'], l: ['slam'] } If your real world solution scales to many 'words' then you could hold a counter as value instead and simply increment it instead of adding the string. But that prevents you mapping words to unique letters. Just a thought. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From steve at pearwood.info Wed Oct 2 03:29:13 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 2 Oct 2013 11:29:13 +1000 Subject: [Tutor] Arbitrary-argument set function In-Reply-To: References: Message-ID: <20131002012913.GJ7989@ando> On Tue, Oct 01, 2013 at 11:43:09PM +0100, Spyros Charonis wrote: > Dear Pythoners, > > > I am trying to extract from a set of about 20 sequences, the characters > which are unique to each sequence. For simplicity, imagine I have only 3 > "sequences" (words in this example) such as: > > > s1='spam'; s2='scam', s3='slam' > > > I would like the character that is unique to each sequence, i.e. I need my > function to return the list [ 'p', 'c', ',l' ]. This function I am using is > as follows: What happens if there is more than one unique character? s1 = 'spam'; s2 = 'eggs' Or none? s1 = 'spam'; s2 = 'pams' What happens if two sequences have the same unique character? s1 = 'spam'; s2 = 'slam'; s3 = 'slam' Do you get 'l' twice or only once? Do you need the unique characters in the order seen? All mixed in together? Your requirements are not detailed enough to solve this question. For instance, if all you want is a single collection of globally unique characters, in no particular order, this is probably the simplest and fastest way to do it: def uniq(*strings): result = set() result.update(*strings) return list(result) If you want to extract unique characters from each string, but keep them distinct, and in order, you can do this: # untested def uniq(*strings): globally_unique = set() globally_unique.update(*strings) result = [] for s in strings: tmp = [] for c in s: if c in globally_unique and not c in tmp: tmp.append(c) result.append(''.join(tmp)) return result If you want something else, you should be able to adapt the above two recipes to do whatever you like. -- Steven From oscar.j.benjamin at gmail.com Wed Oct 2 11:14:13 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Wed, 2 Oct 2013 10:14:13 +0100 Subject: [Tutor] sqlite3 COMMIT directive In-Reply-To: References: <673eeed8f58ad938359eba03c5697ff8@sonic.net> <524A86EA.6000701@timgolden.me.uk> <524AA6BF.9050806@timgolden.me.uk> Message-ID: On 1 October 2013 12:05, Alan Gauld wrote: > > OK, That makes sense it's a bit like the file close at the end of a with > block. So the docs statement that it automatically commits *transactions* is > slightly misleading as it only commits the full content of the block which > could hold multiple transactions. In the light of this confusion the docs do seem ambiguous. However I learned to use sqlite3 through those docs and always understood that the context manager was for committing or rolling back all transactions within the "with" block. It's actually very useful and a good use of a context manager (enabling auto-commit would also be useful but it doesn't really need a context manager). Oscar From bgailer at gmail.com Wed Oct 2 14:05:55 2013 From: bgailer at gmail.com (bob gailer) Date: Wed, 02 Oct 2013 08:05:55 -0400 Subject: [Tutor] Arbitrary-argument set function In-Reply-To: References: Message-ID: <524C0C23.107@gmail.com> On 10/1/2013 6:43 PM, Spyros Charonis wrote: > > Dear Pythoners, > > > I am trying to extract from a set of about 20 sequences, the > characters which are unique to each sequence. For simplicity, imagine > I have only 3 "sequences" (words in this example) such as: > > > s1='spam'; s2='scam', s3='slam' > > > I would like the character that is unique to each sequence, i.e. I > need my function to return the list [ 'p', 'c', ',l' ]. This function > I am using is as follows: > > > def uniq(*args): > > """ FIND UNIQUE ELEMENTS OF AN ARBITRARY NUMBER OF SEQUENCES""" > > unique = [] > > for i in args[0]: > > if: > > unique.append(i) > > return unique > > > and is returning the list [ 's', 'p', 'a', 'm' ]. Any help much > appreciated, > Problems with the above. 1 - where is the call to the function? (we can only guess what you fed it.) 2 - for i in args[0]: tests each character in only the first argument 3 - i not in args[1:] will always be True. Why? 4 - "characters which are unique to each sequence" is hard to translate. Did you mean "characters which appear in exactly one sequence"? BTW this sounds like homework; we are willing to give some assistance with HW but we need you to put more effort into your design and testing. I suggest you either run the program in some tool that will show you clearly what happens at each step or "desk check" it - pretend you are the computer and go step by step, making sure you know what each line does. No guessing. You always have the interactive prompt to test things, and the documentation to explain things. -- Bob Gailer 919-636-4239 Chapel Hill NC From breamoreboy at yahoo.co.uk Wed Oct 2 16:51:53 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 02 Oct 2013 15:51:53 +0100 Subject: [Tutor] sqlite3 COMMIT directive In-Reply-To: References: <673eeed8f58ad938359eba03c5697ff8@sonic.net> <524A86EA.6000701@timgolden.me.uk> <524AA6BF.9050806@timgolden.me.uk> Message-ID: On 01/10/2013 12:05, Alan Gauld wrote: > On 01/10/13 11:41, Tim Golden wrote: > >>>>> Python, the database starts and ends transactions automatically from >>>>> within the execute() function. >>>> >>>> Not so, I'm afraid. If you want autocommit, you need to send an >>>> isolation_level of None to the .connect function. > >>> """ >>> Connection objects can be used as context managers that automatically >>> commit or rollback transactions. >> >> You're sort-of correct. What happens is that the database doesn't enter >> autocommit mode (you'll still need to specify the right isolation level >> on the .connect for that). Rather, the __exit__ method of the >> connection-as-context-manager issues the db.commit() call which will >> commit anything outstanding. > > OK, That makes sense it's a bit like the file close at the end of a with > block. So the docs statement that it automatically commits > *transactions* is slightly misleading as it only commits the full > content of the block which could hold multiple transactions. > > Thanks for the clarification Tim. > I haven't followed this too closely as my SQL skills (like many others) are sadly out of date, but is it worth the hassle of raising an issue on the bug tracker to get the relevant docs changed, or is "slightly misleading" actually close enough? -- Roses are red, Violets are blue, Most poems rhyme, But this one doesn't. Mark Lawrence From fast_primes at hotmail.com Wed Oct 2 19:44:11 2013 From: fast_primes at hotmail.com (Fast Primes) Date: Wed, 2 Oct 2013 13:44:11 -0400 Subject: [Tutor] Python version prior to 02/26/2006? Message-ID: I have a python program written in 02/26/2006. Can I still get a version of python that will run it? If so, which version and from where can I get it? Thx. fp -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Wed Oct 2 19:49:05 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 2 Oct 2013 13:49:05 -0400 Subject: [Tutor] Python version prior to 02/26/2006? In-Reply-To: References: Message-ID: On Wed, Oct 2, 2013 at 1:44 PM, Fast Primes wrote: > I have a python program written in 02/26/2006. Can I still get a version of > python that will run it? > > If so, which version and from where can I get it? > > Thx. > > fp > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > you should try to run it with the latest version of the 2.x series - 2.7 If you find problems that you don't want to fix, you can always load any version of python on your system. Find the one that was current in 2006. See the python.org site for getting different versions Version 3.x series made changes that are not backward compatible with the 2.x series. -- Joel Goldstick http://joelgoldstick.com From davea at davea.name Wed Oct 2 20:04:48 2013 From: davea at davea.name (Dave Angel) Date: Wed, 2 Oct 2013 18:04:48 +0000 (UTC) Subject: [Tutor] Python version prior to 02/26/2006? References: Message-ID: On 2/10/2013 13:44, Fast Primes wrote: > I have a python program written in 02/26/2006. Can I still get a version of python that will run it? > If so, which version and from where can I get it? > Thx. > fp > > > > >
I have a python program written in 02/26/2006. Can I still get a version of python that will run it? 

If so, which version and from where can I get it?

Thx.

fp
> > (Please post using text email, as this is a text newsgroup) The first line of the script should indicate what version of Python it was written for. If not, chances are good that 2.7.5 will be fine. http://www.python.org/download/ -- DaveA From steve at pearwood.info Wed Oct 2 20:04:00 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 3 Oct 2013 04:04:00 +1000 Subject: [Tutor] Python version prior to 02/26/2006? In-Reply-To: References: Message-ID: <20131002180400.GO7989@ando> On Wed, Oct 02, 2013 at 01:44:11PM -0400, Fast Primes wrote: > I have a python program written in 02/26/2006. Can I still get a version of python that will run it? > If so, which version and from where can I get it? Yes. All versions of Python going back to version 1.1 are still available, although the oldest ones may be difficult to install on some systems. What is important though is not *when* the program was written, but what version of Python it was written for. I could write a program today, targetting Python 1.5, if I was foolish. If your program is very short, you might like to show it to us. Or read the documentation -- does it tell you what version of Python it requires? Perhaps it has a line at the top of the file like: #!/usr/bin/python2.4 But there is a very good chance that it will run perfectly using the latest Python 2.7. If not, it will probably be quite simple to fix it so that it will run. Fixing it to run under Python 3.3 will probably be a bit more work. You can download Python versions from here: http://www.python.org/download/releases/ but seriously, you should try to avoid anything older than 2.7 unless you absolutely need it. -- Steven From vitsen at gmx.com Wed Oct 2 20:50:31 2013 From: vitsen at gmx.com (vitsen at gmx.com) Date: Wed, 02 Oct 2013 20:50:31 +0200 Subject: [Tutor] Which Python should a beginner learn? Message-ID: <524C6AF7.5020001@gmx.com> Which version of Python should a beginner learn? 2.x or 3.x? From breamoreboy at yahoo.co.uk Thu Oct 3 01:59:12 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 03 Oct 2013 00:59:12 +0100 Subject: [Tutor] Which Python should a beginner learn? In-Reply-To: <524C6AF7.5020001@gmx.com> References: <524C6AF7.5020001@gmx.com> Message-ID: On 02/10/2013 19:50, vitsen at gmx.com wrote: > Which version of Python should a beginner learn? 2.x or 3.x? > Python 3 is the future so learn it unless you want to use a specific library which hasn't yet been ported. -- Roses are red, Violets are blue, Most poems rhyme, But this one doesn't. Mark Lawrence From joel.goldstick at gmail.com Thu Oct 3 03:07:33 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 2 Oct 2013 21:07:33 -0400 Subject: [Tutor] Which Python should a beginner learn? In-Reply-To: References: <524C6AF7.5020001@gmx.com> Message-ID: On Wed, Oct 2, 2013 at 7:59 PM, Mark Lawrence wrote: > On 02/10/2013 19:50, vitsen at gmx.com wrote: >> >> Which version of Python should a beginner learn? 2.x or 3.x? >> > > Python 3 is the future so learn it unless you want to use a specific library > which hasn't yet been ported. While I generally agree with Mark, you might want to consider other factors. Although 3.x has been around a few years, it took a while for it to pick up steam with third party modules. In the last year, Django has started to experiment with python 3.x. The other consideration is your learning style. You can find lots of youtube videos, and text tutorials on the web to learn python. Some will suit you, some maybe not. So that might lead you to start with the python that matches the resources you prefer. At any rate, if you are just learning programming, what they have in common exceeds their differences. In the end, though Mark is probably right -- all else being equal since some language issues were revisited and made better in 3.x and 2.x will eventually become a relic (maybe in 5 or 10 years). > > -- > Roses are red, > Violets are blue, > Most poems rhyme, > But this one doesn't. > > Mark Lawrence > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor -- Joel Goldstick http://joelgoldstick.com From carolynncsf at yahoo.com Thu Oct 3 04:01:46 2013 From: carolynncsf at yahoo.com (carolynn fryer) Date: Wed, 2 Oct 2013 19:01:46 -0700 (PDT) Subject: [Tutor] HELP I need help with Python Setup or to reach Marilyn Davis Message-ID: <1380765706.55390.YahooMailNeo@web161002.mail.bf1.yahoo.com> I am at the point where I am just spinning my wheels.? I tried to get help with logging on but so far I am just getting frustrated. ? I have a problem that I brought up the first night in class but couldn't seem to get help then.? Sorry if I am at the point where I am totally frustrated and I need HELP. PLEASE. I did not turn in homework because of the fact that I can not run anything without getting a syntax error.? I tried setting up a path for python environment variables?and a few other things but I am getting no where. ? Can you give me some suggestions why I can't run anything.? I have windows 7 on my home computer, and windows 8 on my laptop and they are both doing the same thing.? So it has to be something I am doing or not doing. I really do not like being behind/late in anything so that is making me even more frustrated. I suppose I am even more frustrated and afraid to ask because I kink of got a slap in the face last time I took a course here and the instructor would not help.? But?that was a way different situation, I simply could not understand his English and then he told me he did not have any patience.??Excuse me?but I just about died when he,?an INSTRUCTOR told me that.? I worked at Stanford for?25 years and to hear an instructor say those words was unthinkable.? Anyway you?can maybe understand my reluctance to ask for help but I need help.? Any suggestions?? When I use one of the computers at school everything works just fine.? Except I can not get my own computer to log on when I am there.? So again that is why I said it is my system and something in my set up that I don't have. ? Sorry for the long note, I was just letting out a little frustration.? LOL Thx for any suggestions, Carolynn Fryer ? ps: I know this is not the proper way to get ahold of you but I could not find nor have time to find any other way.? The UCSC?system is not very user friendly?? -------------- next part -------------- An HTML attachment was scrubbed... URL: From fp2161 at gmail.com Thu Oct 3 09:49:43 2013 From: fp2161 at gmail.com (Fabrice Pombet) Date: Thu, 3 Oct 2013 09:49:43 +0200 Subject: [Tutor] Tutor Digest, Vol 116, Issue 8 In-Reply-To: References: Message-ID: Message: 7 Date: Wed, 02 Oct 2013 20:50:31 +0200 From: vitsen at gmx.com To: tutor at python.org Subject: [Tutor] Which Python should a beginner learn? Message-ID: <524C6AF7.5020001 at gmx.com> Content-Type: text/plain; charset=UTF-8; format=flowed Which version of Python should a beginner learn? 2.x or 3.x? ------------------------------ Python 3 is the way forward, and it is not more difficult than Python 2. The frameworks/packages are becomming increasingly available for Python 3. Yet if you are aiming at using a particular package that is not yet ported on Python 3, you may have to go through Python 2... 2013/10/3 > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > https://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Re: Arbitrary-argument set function (bob gailer) > 2. Re: sqlite3 COMMIT directive (Mark Lawrence) > 3. Python version prior to 02/26/2006? (Fast Primes) > 4. Re: Python version prior to 02/26/2006? (Joel Goldstick) > 5. Re: Python version prior to 02/26/2006? (Dave Angel) > 6. Re: Python version prior to 02/26/2006? (Steven D'Aprano) > 7. Which Python should a beginner learn? (vitsen at gmx.com) > 8. Re: Which Python should a beginner learn? (Mark Lawrence) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Wed, 02 Oct 2013 08:05:55 -0400 > From: bob gailer > To: Spyros Charonis > Cc: tutor > Subject: Re: [Tutor] Arbitrary-argument set function > Message-ID: <524C0C23.107 at gmail.com> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 10/1/2013 6:43 PM, Spyros Charonis wrote: > > > > Dear Pythoners, > > > > > > I am trying to extract from a set of about 20 sequences, the > > characters which are unique to each sequence. For simplicity, imagine > > I have only 3 "sequences" (words in this example) such as: > > > > > > s1='spam'; s2='scam', s3='slam' > > > > > > I would like the character that is unique to each sequence, i.e. I > > need my function to return the list [ 'p', 'c', ',l' ]. This function > > I am using is as follows: > > > > > > def uniq(*args): > > > > """ FIND UNIQUE ELEMENTS OF AN ARBITRARY NUMBER OF SEQUENCES""" > > > > unique = [] > > > > for i in args[0]: > > > > if: > > > > unique.append(i) > > > > return unique > > > > > > and is returning the list [ 's', 'p', 'a', 'm' ]. Any help much > > appreciated, > > > Problems with the above. > 1 - where is the call to the function? (we can only guess what you fed it.) > 2 - for i in args[0]: tests each character in only the first argument > 3 - i not in args[1:] will always be True. Why? > 4 - "characters which are unique to each sequence" is hard to translate. > Did you mean > "characters which appear in exactly one sequence"? > > BTW this sounds like homework; we are willing to give some assistance > with HW but we need you to put more effort into your design and testing. > > I suggest you either run the program in some tool that will show you > clearly what happens at each step or "desk check" it - pretend you are > the computer and go step by step, making sure you know what each line > does. No guessing. You always have the interactive prompt to test > things, and the documentation to explain things. > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC > > > > ------------------------------ > > Message: 2 > Date: Wed, 02 Oct 2013 15:51:53 +0100 > From: Mark Lawrence > To: tutor at python.org > Subject: Re: [Tutor] sqlite3 COMMIT directive > Message-ID: > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 01/10/2013 12:05, Alan Gauld wrote: > > On 01/10/13 11:41, Tim Golden wrote: > > > >>>>> Python, the database starts and ends transactions automatically from > >>>>> within the execute() function. > >>>> > >>>> Not so, I'm afraid. If you want autocommit, you need to send an > >>>> isolation_level of None to the .connect function. > > > >>> """ > >>> Connection objects can be used as context managers that automatically > >>> commit or rollback transactions. > >> > >> You're sort-of correct. What happens is that the database doesn't enter > >> autocommit mode (you'll still need to specify the right isolation level > >> on the .connect for that). Rather, the __exit__ method of the > >> connection-as-context-manager issues the db.commit() call which will > >> commit anything outstanding. > > > > OK, That makes sense it's a bit like the file close at the end of a with > > block. So the docs statement that it automatically commits > > *transactions* is slightly misleading as it only commits the full > > content of the block which could hold multiple transactions. > > > > Thanks for the clarification Tim. > > > > I haven't followed this too closely as my SQL skills (like many others) > are sadly out of date, but is it worth the hassle of raising an issue on > the bug tracker to get the relevant docs changed, or is "slightly > misleading" actually close enough? > > -- > Roses are red, > Violets are blue, > Most poems rhyme, > But this one doesn't. > > Mark Lawrence > > > > ------------------------------ > > Message: 3 > Date: Wed, 2 Oct 2013 13:44:11 -0400 > From: Fast Primes > To: "tutor at python.org" > Subject: [Tutor] Python version prior to 02/26/2006? > Message-ID: > Content-Type: text/plain; charset="iso-8859-1" > > I have a python program written in 02/26/2006. Can I still get a version > of python that will run it? > If so, which version and from where can I get it? > Thx. > fp > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20131002/50f15a06/attachment-0001.html > > > > ------------------------------ > > Message: 4 > Date: Wed, 2 Oct 2013 13:49:05 -0400 > From: Joel Goldstick > To: Fast Primes > Cc: "tutor at python.org" > Subject: Re: [Tutor] Python version prior to 02/26/2006? > Message-ID: > < > CAPM-O+zyS4TkvuO+VGs_ut9Q4bkZPwAm3M+buAx0K7+Bc-G-_A at mail.gmail.com> > Content-Type: text/plain; charset=UTF-8 > > On Wed, Oct 2, 2013 at 1:44 PM, Fast Primes > wrote: > > I have a python program written in 02/26/2006. Can I still get a version > of > > python that will run it? > > > > If so, which version and from where can I get it? > > > > Thx. > > > > fp > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > https://mail.python.org/mailman/listinfo/tutor > > > you should try to run it with the latest version of the 2.x series - 2.7 > > If you find problems that you don't want to fix, you can always load > any version of python on your system. Find the one that was current > in 2006. See the python.org site for getting different versions > > Version 3.x series made changes that are not backward compatible with > the 2.x series. > > > -- > Joel Goldstick > http://joelgoldstick.com > > > ------------------------------ > > Message: 5 > Date: Wed, 2 Oct 2013 18:04:48 +0000 (UTC) > From: Dave Angel > To: tutor at python.org > Subject: Re: [Tutor] Python version prior to 02/26/2006? > Message-ID: > Content-Type: text/plain; charset=US-ASCII > > On 2/10/2013 13:44, Fast Primes wrote: > > > I have a python program written in 02/26/2006. Can I still get a version > of python that will run it? > > If so, which version and from where can I get it? > > Thx. > > fp > > > > > > > > > >
I have a python program written > in 02/26/2006. Can I still get a version of python that will run > it? 

If so, which version and from where can I get > it?

Thx.

fp
>
> > > > > > (Please post using text email, as this is a text newsgroup) > > The first line of the script should indicate what version of Python it > was written for. If not, chances are good that 2.7.5 will be fine. > > http://www.python.org/download/ > > > > -- > DaveA > > > > > ------------------------------ > > Message: 6 > Date: Thu, 3 Oct 2013 04:04:00 +1000 > From: Steven D'Aprano > To: tutor at python.org > Subject: Re: [Tutor] Python version prior to 02/26/2006? > Message-ID: <20131002180400.GO7989 at ando> > Content-Type: text/plain; charset=us-ascii > > On Wed, Oct 02, 2013 at 01:44:11PM -0400, Fast Primes wrote: > > I have a python program written in 02/26/2006. Can I still get a version > of python that will run it? > > If so, which version and from where can I get it? > > Yes. All versions of Python going back to version 1.1 are still > available, although the oldest ones may be difficult to install on some > systems. > > What is important though is not *when* the program was written, but what > version of Python it was written for. I could write a program today, > targetting Python 1.5, if I was foolish. > > If your program is very short, you might like to show it to us. Or read > the documentation -- does it tell you what version of Python it > requires? Perhaps it has a line at the top of the file like: > > #!/usr/bin/python2.4 > > But there is a very good chance that it will run perfectly using the > latest Python 2.7. If not, it will probably be quite simple to fix it so > that it will run. Fixing it to run under Python 3.3 will probably be a > bit more work. > > You can download Python versions from here: > > http://www.python.org/download/releases/ > > but seriously, you should try to avoid anything older than 2.7 unless > you absolutely need it. > > > -- > Steven > > > ------------------------------ > > Message: 7 > Date: Wed, 02 Oct 2013 20:50:31 +0200 > From: vitsen at gmx.com > To: tutor at python.org > Subject: [Tutor] Which Python should a beginner learn? > Message-ID: <524C6AF7.5020001 at gmx.com> > Content-Type: text/plain; charset=UTF-8; format=flowed > > Which version of Python should a beginner learn? 2.x or 3.x? > > > ------------------------------ > > Message: 8 > Date: Thu, 03 Oct 2013 00:59:12 +0100 > From: Mark Lawrence > To: tutor at python.org > Subject: Re: [Tutor] Which Python should a beginner learn? > Message-ID: > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 02/10/2013 19:50, vitsen at gmx.com wrote: > > Which version of Python should a beginner learn? 2.x or 3.x? > > > > Python 3 is the future so learn it unless you want to use a specific > library which hasn't yet been ported. > > -- > Roses are red, > Violets are blue, > Most poems rhyme, > But this one doesn't. > > Mark Lawrence > > > > ------------------------------ > > Subject: Digest Footer > > _______________________________________________ > Tutor maillist - Tutor at python.org > https://mail.python.org/mailman/listinfo/tutor > > > ------------------------------ > > End of Tutor Digest, Vol 116, Issue 8 > ************************************* > -------------- next part -------------- An HTML attachment was scrubbed... URL: From chris at chrisdown.name Thu Oct 3 11:44:49 2013 From: chris at chrisdown.name (Chris Down) Date: Thu, 3 Oct 2013 17:44:49 +0800 Subject: [Tutor] HELP I need help with Python Setup or to reach Marilyn Davis In-Reply-To: <1380765706.55390.YahooMailNeo@web161002.mail.bf1.yahoo.com> References: <1380765706.55390.YahooMailNeo@web161002.mail.bf1.yahoo.com> Message-ID: <20131003094448.GA15054@chrisdown.name> On 2013-10-02 19:01, carolynn fryer wrote: > I am at the point where I am just spinning my wheels.? I tried to get help > with logging on but so far I am just getting frustrated. > ? > I have a problem that I brought up the first night in class but couldn't seem > to get help then.? Sorry if I am at the point where I am totally frustrated > and I need HELP. PLEASE. I did not turn in homework because of the fact that > I can not run anything without getting a syntax error.? I tried setting up a > path for python environment variables?and a few other things but I am getting > no where. > ? > Can you give me some suggestions why I can't run anything.? I have windows 7 > on my home computer, and windows 8 on my laptop and they are both doing the > same thing.? So it has to be something I am doing or not doing. I really do > not like being behind/late in anything so that is making me even more > frustrated. I suppose I am even more frustrated and afraid to ask because I > kink of got a slap in the face last time I took a course here and the > instructor would not help.? But?that was a way different situation, I simply > could not understand his English and then he told me he did not have any > patience.??Excuse me?but I just about died when he,?an INSTRUCTOR told me > that.? I worked at Stanford for?25 years and to hear an instructor say those > words was unthinkable.? Anyway you?can maybe understand my reluctance to ask > for help but I need help.? Any suggestions?? When I use one of the computers > at school everything works just fine.? Except I can not get my own computer > to log on when I am there.? So again that is why I said it is my system and > something in my set up that I don't have. > ? > Sorry for the long note, I was just letting out a little frustration.? LOL > Thx for any suggestions, Carolynn Fryer > ? > ps: I know this is not the proper way to get ahold of you but I could not > find nor have time to find any other way.? The UCSC?system is not very user > friendly?? I genuinely have no idea what we are supposed to do with this unfocused diatribe. It would be good if you could avoid copying tutor@ to your inane UCSC-centric rants in future. You have, however, given absolutely no information that could help anyone in diagnosing your problem. I don't have the patience to wade through this contextless rant. In future: - Nobody on this list cares about what you have to say about UCSC; - Please get to the point; - Please include actual examples of error messages you face instead of just describing them. Thanks. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 490 bytes Desc: not available URL: From davea at davea.name Thu Oct 3 12:07:34 2013 From: davea at davea.name (Dave Angel) Date: Thu, 3 Oct 2013 10:07:34 +0000 (UTC) Subject: [Tutor] HELP I need help with Python Setup or to reach Marilyn Davis References: <1380765706.55390.YahooMailNeo@web161002.mail.bf1.yahoo.com> Message-ID: On 2/10/2013 22:01, carolynn fryer wrote: > the fact that I can not run anything without getting a syntax error.? I > tried setting up a path for python environment variables?and a few other things but I am getting no where. Welcome to the Python tutor mailing list. I deleted all the irrelevant parts of your post so that we could see how you described your problem. You're running Windows 7 (or 8), and you've installed Python version x.xx, which you downloaded from http://www.yyyyyyy.yyyy/zzzzzzzz After installation, which gave no errors, you tried typing in the following 5 line Python program into the file XXXXXX.PL, using the JJJJJJJ.COM text editor. #!QQQQQQQQQ/QQQQQQQQ/QQQQQQ import ZZZ for zzz in xxxxxxxxxxxxx: print ("xxx" You ran this program from the CMD box, using the Windows command: XXXXXXXXXXxx > pythonXZZ myprogEEEEE.44 and you got the following output: 932873297843294327432 n 432983274329743 2974393287432 239873249734 You guess we might want to know the folloiwing environment variables: PATH=lasjf;ljdsaf;ljfds;afjljlfdsjjfdsafds; PYTHONBADPATH=ljfdsljsfdlfdsjlfdskjfds You want to know how to correct the above explicit error. Now, that message we could probably handle, obviously depending on the details. -- DaveA From davea at davea.name Thu Oct 3 12:13:43 2013 From: davea at davea.name (Dave Angel) Date: Thu, 3 Oct 2013 10:13:43 +0000 (UTC) Subject: [Tutor] Tutor Digest, Vol 116, Issue 8 References: Message-ID: On 3/10/2013 03:49, Fabrice Pombet wrote: > Message: 7 > Date: Wed, 02 Oct 2013 20:50:31 +0200 > From: vitsen at gmx.com > Content-Type: text/plain; charset=UTF-8; format=flowed > > Which version of Python should a beginner learn? 2.x or 3.x? Please reply to an individual message, not to the digest. By replying to the digest, you lost the threading, so your message creates a brand new thread, which probably won't be noticed by the OP. Then you compound it by leaving the subject line as "Tutor Digest..." And further, by including both text and html versions of the whole digest. this is a text newsgroup, so please treat it as one. 700 extra lines of nonsense is a waste of bandwidth. -- DaveA From wprins at gmail.com Thu Oct 3 12:51:02 2013 From: wprins at gmail.com (Walter Prins) Date: Thu, 3 Oct 2013 11:51:02 +0100 Subject: [Tutor] HELP I need help with Python Setup or to reach Marilyn Davis In-Reply-To: <1380765706.55390.YahooMailNeo@web161002.mail.bf1.yahoo.com> References: <1380765706.55390.YahooMailNeo@web161002.mail.bf1.yahoo.com> Message-ID: Hi Carolynn, On 3 October 2013 03:01, carolynn fryer wrote: > I am at the point where I am just spinning my wheels. I tried to get help > with logging on but so far I am just getting frustrated. > > Please note that you've sent an email regarding what appears to be possibly be specific issues related to your PC's (?) and logging on (?) and/or your Python installation (?), to a general public mailing list concerned with learning the Python programming language. Please understand that the people on this list are volunteers, willing to help people *learn Python*, not solve arbitrary PC issues. It is not a "I'll solve all obscure PC issues posted by random strangers on the internet" list. Given the voluntary nature of this list, some of the contributors understandably don't take too kindly to people who appear vent their frustrations on them out of the blue, and seem to demand solving of their problems when they're already donating their valuable time for free. So, please don't be offended if some of the responses appear to be harsh. Usually, much more light and less heat can be generated by being less emotive and providing just the facts for people to work with, for example: - What version of Operating systems are you using (OK, Windows 7&8, but 32 bit or 64-bit?) - What version(s) of Python did you install? (2.7 or 3.3, 32 bit or 64-bit) - What exactly did you do? (How are you running your Python interpreter and what you are then doing that's not working?) - What actually happened/didn't work? - What did you expect to happen? Here's a video that was produced by one of the contributors on this list that details how to install Python on Windows 7. Maybe following this can help you resolve your (what sounds to me to be installation) issues: http://www.youtube.com/watch?v=wnAsMQbCVXA Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From bouncingcats at gmail.com Thu Oct 3 14:58:04 2013 From: bouncingcats at gmail.com (David) Date: Thu, 3 Oct 2013 22:58:04 +1000 Subject: [Tutor] HELP I need help with Python Setup or to reach Marilyn Davis In-Reply-To: References: <1380765706.55390.YahooMailNeo@web161002.mail.bf1.yahoo.com> Message-ID: On 3 October 2013 20:51, Walter Prins wrote: > Hi Carolynn, > > On 3 October 2013 03:01, carolynn fryer wrote: >> >> I am at the point where I am just spinning my wheels. I tried to get help >> with logging on but so far I am just getting frustrated. > > Please note that you've sent an email regarding what appears to be possibly > be specific issues related to your PC's (?) and logging on (?) and/or your > Python installation (?), to a general public mailing list ... ... which has 100's of readers all around the world. From alan.gauld at btinternet.com Thu Oct 3 16:39:04 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 03 Oct 2013 15:39:04 +0100 Subject: [Tutor] HELP I need help with Python Setup or to reach Marilyn Davis In-Reply-To: References: <1380765706.55390.YahooMailNeo@web161002.mail.bf1.yahoo.com> Message-ID: On 03/10/13 13:58, David wrote: >> Python installation (?), to a general public mailing list ... > > ... which has 100's of readers all around the world. Almost 4000... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From joejacques88 at aol.com Thu Oct 3 18:31:46 2013 From: joejacques88 at aol.com (Joe Jacques) Date: Thu, 3 Oct 2013 12:31:46 -0400 Subject: [Tutor] how to generate random numbers in Python Message-ID: Problems in the link http://home.manhattan.edu/~ankur.agrawal/cmpt101/assgn5.txt Sent from my iPhone From tdkrupinski at gmail.com Thu Oct 3 19:10:09 2013 From: tdkrupinski at gmail.com (Tim Krupinski) Date: Thu, 3 Oct 2013 12:10:09 -0500 Subject: [Tutor] Which Python should a beginner learn? In-Reply-To: References: <524C6AF7.5020001@gmx.com> Message-ID: I think it really depends on why you are learning python. For me, I'm using it primarily to supplement my tools as a system engineer. The standard version of Python that installs with nearly every server I manage is 2.7, so I decided to focus on learning 2.7 because I didn't want to be in a position where I had to install Python 3 onto every server. Now, it does look like 3 has a lot of additions that help OO type programming - so if you are learning it to write robust programs 3 might be the way to go. On Wed, Oct 2, 2013 at 8:07 PM, Joel Goldstick wrote: > On Wed, Oct 2, 2013 at 7:59 PM, Mark Lawrence > wrote: > > On 02/10/2013 19:50, vitsen at gmx.com wrote: > >> > >> Which version of Python should a beginner learn? 2.x or 3.x? > >> > > > > Python 3 is the future so learn it unless you want to use a specific > library > > which hasn't yet been ported. > > While I generally agree with Mark, you might want to consider other > factors. Although 3.x has been around a few years, it took a while > for it to pick up steam with third party modules. In the last year, > Django has started to experiment with python 3.x. The other > consideration is your learning style. You can find lots of youtube > videos, and text tutorials on the web to learn python. Some will suit > you, some maybe not. So that might lead you to start with the python > that matches the resources you prefer. > > At any rate, if you are just learning programming, what they have in > common exceeds their differences. > > In the end, though Mark is probably right -- all else being equal > since some language issues were revisited and made better in 3.x and > 2.x will eventually become a relic (maybe in 5 or 10 years). > > > > -- > > Roses are red, > > Violets are blue, > > Most poems rhyme, > > But this one doesn't. > > > > Mark Lawrence > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > https://mail.python.org/mailman/listinfo/tutor > > > > -- > Joel Goldstick > http://joelgoldstick.com > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Thu Oct 3 23:24:04 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 03 Oct 2013 22:24:04 +0100 Subject: [Tutor] how to generate random numbers in Python In-Reply-To: References: Message-ID: On 03/10/2013 17:31, Joe Jacques wrote: > Problems in the link > > http://home.manhattan.edu/~ankur.agrawal/cmpt101/assgn5.txt > > Sent from my iPhone > Sorry but if you want us to do your work you'll have to send a suitably sized cheque to the PSF, where the size refers to the amount written in words and numbers and not the physical dimensions. -- Roses are red, Violets are blue, Most poems rhyme, But this one doesn't. Mark Lawrence From thudfoo at gmail.com Fri Oct 4 00:24:01 2013 From: thudfoo at gmail.com (xDog Walker) Date: Thu, 3 Oct 2013 15:24:01 -0700 Subject: [Tutor] how to generate random numbers in Python In-Reply-To: References: Message-ID: <201310031524.01473.thudfoo@gmail.com> On Thursday 2013 October 03 09:31, Joe Jacques wrote: > Problems in the link > > http://home.manhattan.edu/~ankur.agrawal/cmpt101/assgn5.txt > > Sent from my iPhone Python 2.7.2 (default, Oct 10 2011, 10:47:36) [GCC 4.1.2 20061115 (prerelease) (SUSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import random >>> help(random) should get you started. -- Yonder nor sorghum stenches shut ladle gulls stopper torque wet strainers. From akleider at sonic.net Fri Oct 4 03:52:52 2013 From: akleider at sonic.net (Alex Kleider) Date: Thu, 03 Oct 2013 18:52:52 -0700 Subject: [Tutor] sqlite3 place holder problem In-Reply-To: <673eeed8f58ad938359eba03c5697ff8@sonic.net> References: <673eeed8f58ad938359eba03c5697ff8@sonic.net> Message-ID: <400729ac6fc0081533cc3a5f03bdb0fe@sonic.net> The following class method """ def insert(self, DataBase=DataBase, Table=Table): """ Insert instance of ClassMate into
. """ with sqlite3.connect(DataBase) as con: cur = con.cursor() row = \ ('NULL', self.first, self.last, self.partner, self.address, self.phone, self.email, ) directive = "INSERT INTO %s VALUES ?;" % (Table, ) cur.execute(directive, row) """ gives the following error: """ Traceback (most recent call last): File "./v_temp.py", line 155, in go_on.insert() File "./v_temp.py", line 70, in insert cur.execute(directive, row) sqlite3.OperationalError: near "?": syntax error """ (explanation: 'go_on' is an instance of my class in the __main__) It was working fine when I was using string formatting but I can't seem to get the syntax right using the qmark method which the documentation suggests is the better way to do it. Can anyone spot what should be changed? (Python 2.7 on Ubuntu ) Thanks in advance. Alex From bgailer at gmail.com Fri Oct 4 04:03:18 2013 From: bgailer at gmail.com (bob gailer) Date: Thu, 03 Oct 2013 22:03:18 -0400 Subject: [Tutor] how to generate random numbers in Python In-Reply-To: References: Message-ID: <524E21E6.8080903@gmail.com> On 10/3/2013 12:31 PM, Joe Jacques wrote: Hi and welcome to the tutor list. Be aware that we are a few volunteers who enjoy assisting when you have tried something and are stuck. As you may have gathered from Mark's response - we don't do homework for you. Were you expecting that, or if not what did you expect? We also enjoy a bit more human interaction. "Problems in the link" is a bit terse and uninviting. Also there are 3 problems on the web, but one mentioned in the subject, so I am not even sure what you want help with. Take a stab at writing the programs; show us your work; tell us where you are stuck. > Problems in the link > > http://home.manhattan.edu/~ankur.agrawal/cmpt101/assgn5.txt > > Sent from my iPhone > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Bob Gailer 919-636-4239 Chapel Hill NC From bgailer at gmail.com Fri Oct 4 04:07:24 2013 From: bgailer at gmail.com (bob gailer) Date: Thu, 03 Oct 2013 22:07:24 -0400 Subject: [Tutor] sqlite3 place holder problem In-Reply-To: <400729ac6fc0081533cc3a5f03bdb0fe@sonic.net> References: <673eeed8f58ad938359eba03c5697ff8@sonic.net> <400729ac6fc0081533cc3a5f03bdb0fe@sonic.net> Message-ID: <524E22DC.6010507@gmail.com> On 10/3/2013 9:52 PM, Alex Kleider wrote: > The following class method > """ > > def insert(self, DataBase=DataBase, Table=Table): > """ > Insert instance of ClassMate into
. > """ > with sqlite3.connect(DataBase) as con: > cur = con.cursor() > row = \ > ('NULL', self.first, self.last, self.partner, > self.address, self.phone, self.email, ) > directive = "INSERT INTO %s VALUES ?;" % (Table, ) > cur.execute(directive, row) > """ > gives the following error: > > """ > Traceback (most recent call last): > File "./v_temp.py", line 155, in > go_on.insert() > File "./v_temp.py", line 70, in insert > cur.execute(directive, row) > sqlite3.OperationalError: near "?": syntax error > """ > (explanation: 'go_on' is an instance of my class in the __main__) > > It was working fine when I was using string formatting but I can't > seem to get the syntax right using the qmark method which the > documentation suggests is the better way to do it. > > Can anyone spot what should be changed? Try: directive = "INSERT INTO %s VALUES (?,?,?,?,?,?,?);" % (Table, ) > (Python 2.7 on Ubuntu ) > > Thanks in advance. > Alex > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Bob Gailer 919-636-4239 Chapel Hill NC From akleider at sonic.net Fri Oct 4 04:14:44 2013 From: akleider at sonic.net (Alex Kleider) Date: Thu, 03 Oct 2013 19:14:44 -0700 Subject: [Tutor] sqlite3 place holder problem In-Reply-To: <524E22DC.6010507@gmail.com> References: <673eeed8f58ad938359eba03c5697ff8@sonic.net> <400729ac6fc0081533cc3a5f03bdb0fe@sonic.net> <524E22DC.6010507@gmail.com> Message-ID: <2e5ca7eba9374deddf7e54275bb7b258@sonic.net> On 2013-10-03 19:07, bob gailer wrote: > On 10/3/2013 9:52 PM, Alex Kleider wrote: >> The following class method >> """ >> >> def insert(self, DataBase=DataBase, Table=Table): >> """ >> Insert instance of ClassMate into
. >> """ >> with sqlite3.connect(DataBase) as con: >> cur = con.cursor() >> row = \ >> ('NULL', self.first, self.last, self.partner, >> self.address, self.phone, self.email, ) >> directive = "INSERT INTO %s VALUES ?;" % (Table, ) >> cur.execute(directive, row) >> """ >> gives the following error: >> >> """ >> Traceback (most recent call last): >> File "./v_temp.py", line 155, in >> go_on.insert() >> File "./v_temp.py", line 70, in insert >> cur.execute(directive, row) >> sqlite3.OperationalError: near "?": syntax error >> """ >> (explanation: 'go_on' is an instance of my class in the __main__) >> >> It was working fine when I was using string formatting but I can't >> seem to get the syntax right using the qmark method which the >> documentation suggests is the better way to do it. >> >> Can anyone spot what should be changed? > Try: directive = "INSERT INTO %s VALUES (?,?,?,?,?,?,?);" % (Table, ) >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor >> Thanks, I discovered that when I went I read further in the documentation. This is the part that lead me a stray: """ # Larger example that inserts many records at a time purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00), ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00), ('2006-04-06', 'SELL', 'IBM', 500, 53.00), ] c.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases) """ I made the incorrect assumption that individual question marks represented tuples, (as they do here with 'executemany') but I guess not so with 'execute'. From akleider at sonic.net Fri Oct 4 04:09:02 2013 From: akleider at sonic.net (Alex Kleider) Date: Thu, 03 Oct 2013 19:09:02 -0700 Subject: [Tutor] sqlite3 place holder problem In-Reply-To: <400729ac6fc0081533cc3a5f03bdb0fe@sonic.net> References: <673eeed8f58ad938359eba03c5697ff8@sonic.net> <400729ac6fc0081533cc3a5f03bdb0fe@sonic.net> Message-ID: <1b368620cae4dc4aae77c73e1f943f0c@sonic.net> On 2013-10-03 18:52, Alex Kleider wrote: > The following class method > """ > > def insert(self, DataBase=DataBase, Table=Table): > """ > Insert instance of ClassMate into
. > """ > with sqlite3.connect(DataBase) as con: > cur = con.cursor() > row = \ > ('NULL', self.first, self.last, self.partner, > self.address, self.phone, self.email, ) > directive = "INSERT INTO %s VALUES ?;" % (Table, ) > cur.execute(directive, row) > """ > gives the following error: > > """ > Traceback (most recent call last): > File "./v_temp.py", line 155, in > go_on.insert() > File "./v_temp.py", line 70, in insert > cur.execute(directive, row) > sqlite3.OperationalError: near "?": syntax error > """ > (explanation: 'go_on' is an instance of my class in the __main__) > > It was working fine when I was using string formatting but I can't > seem to get the syntax right using the qmark method which the > documentation suggests is the better way to do it. > > Can anyone spot what should be changed? > (Python 2.7 on Ubuntu ) > > Thanks in advance. > Alex Sorry to have bothered the list; I found the problems (there were two!) Here's the corrected version in case it's of interest to anyone: """ def insert(self, DataBase=DataBase, Table=Table): """ Insert instance of ClassMate into
. """ with lite.connect(DataBase) as con: cur = con.cursor() row = \ (self.first, self.last, self.partner, self.address, self.phone, self.email, ) directive = \ "INSERT INTO %s VALUES (NULL, ?, ?, ?, ?, ?, ?)" \ % (Table, ) cur.execute(directive, row) """ From alan.gauld at btinternet.com Fri Oct 4 11:48:15 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 04 Oct 2013 10:48:15 +0100 Subject: [Tutor] sqlite3 place holder problem In-Reply-To: <2e5ca7eba9374deddf7e54275bb7b258@sonic.net> References: <673eeed8f58ad938359eba03c5697ff8@sonic.net> <400729ac6fc0081533cc3a5f03bdb0fe@sonic.net> <524E22DC.6010507@gmail.com> <2e5ca7eba9374deddf7e54275bb7b258@sonic.net> Message-ID: On 04/10/13 03:14, Alex Kleider wrote: > Thanks, I discovered that when I went I read further in the documentation. > This is the part that lead me a stray: > """ > # Larger example that inserts many records at a time > purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00), > ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00), > ('2006-04-06', 'SELL', 'IBM', 500, 53.00), > ] > c.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases) > """ > I made the incorrect assumption that individual question marks > represented tuples, (as they do here with 'executemany') but I guess not > so with 'execute'. I'm not sure you got that right. There are 5 question marks there, one for each value item to be inserted. There are 5 values in each tuple in purchases. Therefore the question marks do not represent the tuples, they represent the values in the tuples. Just like in execute() executemany() performs an execute() on each item in the purchases list, passing the tuple content into the execute. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From akleider at sonic.net Fri Oct 4 20:42:44 2013 From: akleider at sonic.net (Alex Kleider) Date: Fri, 04 Oct 2013 11:42:44 -0700 Subject: [Tutor] sqlite3 place holder problem In-Reply-To: References: <673eeed8f58ad938359eba03c5697ff8@sonic.net> <400729ac6fc0081533cc3a5f03bdb0fe@sonic.net> <524E22DC.6010507@gmail.com> <2e5ca7eba9374deddf7e54275bb7b258@sonic.net> Message-ID: <5d75cc561767a99453db81bb41a1bdfb@sonic.net> On 2013-10-04 02:48, Alan Gauld wrote: > On 04/10/13 03:14, Alex Kleider wrote: > >> Thanks, I discovered that when I went I read further in the >> documentation. >> This is the part that lead me a stray: >> """ >> # Larger example that inserts many records at a time >> purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00), >> ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00), >> ('2006-04-06', 'SELL', 'IBM', 500, 53.00), >> ] >> c.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases) >> """ >> I made the incorrect assumption that individual question marks >> represented tuples, (as they do here with 'executemany') but I guess >> not >> so with 'execute'. > > I'm not sure you got that right. > > There are 5 question marks there, one for each value item to be > inserted. > There are 5 values in each tuple in purchases. > Therefore the question marks do not represent the tuples, they > represent the values in the tuples. Just like in execute() > > executemany() performs an execute() on each item in the purchases > list, passing the tuple content into the execute. > > HTH Ah, Ha! Thanks for the clarification. Now it is much more consistent (as I should have known that it would be.) From fomcl at yahoo.com Sat Oct 5 14:33:46 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sat, 5 Oct 2013 05:33:46 -0700 (PDT) Subject: [Tutor] class decorator question Message-ID: <1380976426.80681.YahooMailNeo@web163802.mail.gq1.yahoo.com> Hi, On http://lucumr.pocoo.org/2013/5/21/porting-to-python-3-redux/ I saw a very cool and useful example of a class decorator. It (re)implements __str__ and __unicode__ in case Python 2 is used. For Python 3, the decorator does nothing. I wanted to generalize this decorator so the __str__ method under Python 2 encodes the string to an arbitrary encoding. This is what I've created: http://pastebin.com/vghD1bVJ. It works, but the code is not very easy to understand, I am affraid. Or is it? And I have no idea how to call the class Klass. Maybe reimplements_Test? Is this a good approach, or can this be done in an easier way? I would *really* like keep statements "if sys.version_info[0] == 3..." separate from the "main" code. Also, learning about class decorators is cool ;-). So the code below... mehhh? no sir, I don't like it. def __str__(self): ??? if sys.version_info[0] == 3: ??? ? ? blah ? ? else: ? ? ? ? bleh ? if sys.version_info[0] == 2: ??? def __unicode__(self): ??????? blooooh ? Regards, Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~? -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sat Oct 5 15:14:42 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 5 Oct 2013 23:14:42 +1000 Subject: [Tutor] class decorator question In-Reply-To: <1380976426.80681.YahooMailNeo@web163802.mail.gq1.yahoo.com> References: <1380976426.80681.YahooMailNeo@web163802.mail.gq1.yahoo.com> Message-ID: <20131005131442.GR7989@ando> On Sat, Oct 05, 2013 at 05:33:46AM -0700, Albert-Jan Roskam wrote: > Hi, > > On http://lucumr.pocoo.org/2013/5/21/porting-to-python-3-redux/ I saw > a very cool and useful example of a class decorator. It (re)implements > __str__ and __unicode__ in case Python 2 is used. For Python 3, the > decorator does nothing. I wanted to generalize this decorator so the > __str__ method under Python 2 encodes the string to an arbitrary > encoding. This is what I've created: http://pastebin.com/vghD1bVJ. > > It works, but the code is not very easy to understand, I am affraid. It's easy to understand, it's just doing it the wrong way. It creates and subclass of your class, which it shouldn't do. Here's a better approach: inject the appropriate methods into the class directly. Here's a version for Python 3: def decorate(cls): if '__str__' not in cls.__dict__: # inject __str__ method def __str__(self): ... cls.__str__ = __str__ if '__bytes__' not in cls.__dict__: # like above return cls This avoids overwriting __str__ if it is already defined, and likewise for __bytes__. > Or is it? And I have no idea how to call the class Klass. Maybe > reimplements_Test? Is this a good approach, or can this be done in an > easier way? I would *really* like keep statements "if > sys.version_info[0] == 3..." separate from the "main" code. Also, > learning about class decorators is cool ;-). So the code below... > mehhh? no sir, I don't like it. > > > def __str__(self): > > ??? if sys.version_info[0] == 3: > ??? ? ? blah > ? ? else: > ? ? ? ? bleh > ? > if sys.version_info[0] == 2: > ??? def __unicode__(self): > ??????? blooooh That performs the version check every time the __str__ method is called. Better would be something like this: if sys.version_info[0] == 2: def __str__(self): ... def __unicode__(self): ... else: def __bytes__(self): ... def __str__(self): ... If you don't like repeating the code twice, once for version 2 and once for version 3, you may be able to define the methods once, then rename them, something like this: # Assume version 3 def __str__(self): ... def __bytes__(self): ... if sys.version_info[0] == 2: __str__.__name__ = '__unicode__' __bytes.__name__ = '__str__' # Inject into the class, as above. cls.__unicode__ = __str__ cls.__str__ = __bytes__ else: cls.__str__ = __str__ cls.__bytes__ = __bytes__ Combining this with the decorator is left for you :-) -- Steven From roberto03 at gmail.com Sat Oct 5 17:47:23 2013 From: roberto03 at gmail.com (roberto) Date: Sat, 5 Oct 2013 17:47:23 +0200 Subject: [Tutor] writing python on the web In-Reply-To: References: Message-ID: Thank you guys, I'll take a look at what you suggested! Have a nice day. On Friday, October 4, 2013, Walter Prins wrote: > Hello, > > Just thought I'd mention the following which I came across today which may > fit your purposes as well: https://koding.com > > Regards, > > Walter > > > > > On 30 September 2013 13:49, roberto > > wrote: > >> Hi, my school is considering a massive shift to Chromebooks. I've to >> carefully think about how could the students go on writing their python >> programs on the web. >> Do you know any online interpreter where programs might be written, saved >> and modified. If sharing and collaborating were allowed, that would be a >> big plus. >> >> Cheers. >> >> -- >> Roberto >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org > 'Tutor at python.org');> >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor >> >> > > > -- > Walter Prins > Trendata Solutions Limited > 26 Kirfield Drive, Hinckley, Leicestershire, LE10 1SX > Tel: 01455 635 994 (fax/landline) 077 8713 1543 (mobile) Email: > info at trendatasolutions.ltd.uk 'info at trendatasolutions.ltd.uk');> > Registered Office: 8 Emmanuel Court, 10 Mill Street, Birmingham, B72 1TJ > Company registered in England No: 07364060 VAT No: 998 3569 37 > -- Sent from Gmail Mobile -------------- next part -------------- An HTML attachment was scrubbed... URL: From fomcl at yahoo.com Sat Oct 5 21:26:14 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sat, 5 Oct 2013 12:26:14 -0700 (PDT) Subject: [Tutor] class decorator question In-Reply-To: <20131005131442.GR7989@ando> References: <1380976426.80681.YahooMailNeo@web163802.mail.gq1.yahoo.com> <20131005131442.GR7989@ando> Message-ID: <1381001174.17868.YahooMailNeo@web163806.mail.gq1.yahoo.com> _______________________________ > From: Steven D'Aprano >To: tutor at python.org >Sent: Saturday, October 5, 2013 3:14 PM >Subject: Re: [Tutor] class decorator question > >On Sat, Oct 05, 2013 at 05:33:46AM -0700, Albert-Jan Roskam wrote: >> Hi, >> >> On http://lucumr.pocoo.org/2013/5/21/porting-to-python-3-redux/ I saw >> a very cool and useful example of a class decorator. It (re)implements >> __str__ and __unicode__ in case Python 2 is used. For Python 3, the >> decorator does nothing. I wanted to generalize this decorator so the >> __str__ method under Python 2 encodes the string to an arbitrary >> encoding. This is what I've created: http://pastebin.com/vghD1bVJ. >> >> It works, but the code is not very easy to understand, I am affraid. > >It's easy to understand, it's just doing it the wrong way. It creates >and subclass of your class, which it shouldn't do. Why not? Because it's an unusual coding pattern? Or is it ineffecient? I subclassed because I needed the encoding value in the decorator. But subclassing may indeed have been overkill. Here's a better >approach: inject the appropriate methods into the class directly. Here's >a version for Python 3: > > >def decorate(cls): >? ? if '__str__' not in cls.__dict__: >? ? ? ? # inject __str__ method >? ? ? ? def __str__(self): >? ? ? ? ? ? ... >? ? ? ? cls.__str__ = __str__ > >? ? if '__bytes__' not in cls.__dict__: >? ? ? ? # like above > >? ? return cls > > >This avoids overwriting __str__ if it is already defined, and likewise >for __bytes__. Doesn't a class always have __str__ implementation? >>> class Foo(object): pass >>> f = Foo() >>> f.__str__ >>> Foo.__str__ >>> >> Or is it? And I have no idea how to call the class Klass. Maybe >> reimplements_Test? Is this a good approach, or can this be done in an >> easier way? I would *really* like keep statements "if >> sys.version_info[0] == 3..." separate from the "main" code. Also, >> learning about class decorators is cool ;-). So the code below... >> mehhh? no sir, I don't like it. Btw, that was a quote: http://www.youtube.com/watch?v=dQ3acvz5LfI ;-) >> >> >> def __str__(self): >> >> ??? if sys.version_info[0] == 3: >> ??? ? ? blah >> ? ? else: >> ? ? ? ? bleh >> ? >> if sys.version_info[0] == 2: >> ??? def __unicode__(self): >> ??????? blooooh > > >That performs the version check every time the __str__ method is called. Good point. >Better would be something like this: > >if sys.version_info[0] == 2: >? ? def __str__(self): >? ? ? ? ... > >? ? def __unicode__(self): >? ? ? ? ... > >else: >? ? def __bytes__(self): >? ? ? ? ... > >? ? def __str__(self): >? ? ? ? ... > >If you don't like repeating the code twice, once for version 2 and once >for version 3, you may be able to define the methods once, then rename >them, something like this: > ># Assume version 3 >def __str__(self): >? ? ... > >def __bytes__(self): >? ? ... > >if sys.version_info[0] == 2: >? ? __str__.__name__ = '__unicode__' >? ? __bytes.__name__ = '__str__' >? ? # Inject into the class, as above. >? ? cls.__unicode__ = __str__ >? ? cls.__str__ = __bytes__ > >else: >? ? cls.__str__ = __str__ >? ? cls.__bytes__ = __bytes__ > > >Combining this with the decorator is left for you :-) Nice, thanks Steven. I made a couple of versions after reading your advise. The main change that I still had to somehow retrieve the encoding value from the class to be decorated (decoratee?). I simply stored it in __dict__. Here is the second version that I created: http://pastebin.com/te3Ap50C. I tested it in Python 2 and 3. The Test class contains __str__ and __unicode__ which are renamed and redefined by the decorator if Python 3 (or 4, or..) is used. General question: I am using pastebin now. Is that okay, given that this is not part of the "memory" of the Python Tutor archive? It might be annoying if people search the archives and get 404s if they try to follow these links. Just in case I am also pasting the code below: from __future__ import print_function import sys ??? def decorate(cls): ??? print("decorate called") ??? if sys.version_info[0] > 2: ??????? cls.__dict__["__str__"].__name__ = '__bytes__' ??????? cls.__dict__["__unicode__"].__name__ = '__str__' ??????? cls.__bytes__ = cls.__dict__["__str__"] ??????? cls.__str__ = cls.__dict__["__unicode__"]? ??? return cls @decorate class Test(object): ??? def __init__(self): ??????? self.__dict__["encoding"] = self.encoding ??? def __str__(self): ??????? return "str called".encode(self.encoding) ??? def __unicode__(self): ??????? return "unicode called" ??? @property ??? def encoding(self): ??????? """In reality this method extracts the encoding from a file""" ??????? return "utf-8" # rot13 no longer exists in Python3 if __name__ == "__main__": ??? t = Test() ??? if sys.version_info[0] == 2: ??????? print(unicode(t)) ??? print(str(t)) From alan.gauld at btinternet.com Sun Oct 6 02:06:18 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 06 Oct 2013 01:06:18 +0100 Subject: [Tutor] class decorator question In-Reply-To: <1381001174.17868.YahooMailNeo@web163806.mail.gq1.yahoo.com> References: <1380976426.80681.YahooMailNeo@web163802.mail.gq1.yahoo.com> <20131005131442.GR7989@ando> <1381001174.17868.YahooMailNeo@web163806.mail.gq1.yahoo.com> Message-ID: On 05/10/13 20:26, Albert-Jan Roskam wrote: > General question: I am using pastebin now. Is that okay, For code as short as this it's probably best kept with the message. But once you get to 100+ lines its more debatable and if you get to 200+ lines I'd definitely say a pastebin is better. > from __future__ import print_function > import sys > > def decorate(cls): > print("decorate called") > if sys.version_info[0] > 2: > cls.__dict__["__str__"].__name__ = '__bytes__' > cls.__dict__["__unicode__"].__name__ = '__str__' > cls.__bytes__ = cls.__dict__["__str__"] > cls.__str__ = cls.__dict__["__unicode__"] > return cls > > @decorate > class Test(object): > > def __init__(self): > self.__dict__["encoding"] = self.encoding > > def __str__(self): > return "str called".encode(self.encoding) > > def __unicode__(self): > return "unicode called" > > @property > def encoding(self): > """In reality this method extracts the encoding from a file""" > return "utf-8" # rot13 no longer exists in Python3 > > if __name__ == "__main__": > t = Test() > if sys.version_info[0] == 2: > print(unicode(t)) > print(str(t)) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From bhanu.bais at gmail.com Sat Oct 5 19:17:21 2013 From: bhanu.bais at gmail.com (Bhanu Pratap Singh) Date: Sat, 5 Oct 2013 22:47:21 +0530 Subject: [Tutor] how to generate random numbers in Python In-Reply-To: References: Message-ID: <001001cec1ee$c4516950$4cf43bf0$@com> /* Generating random number -------------------------------- */ from random import randint print(randint(0,5)) >>> # anyone from 0 to 5 For generating only 0 or 1 print(randint(0,1)) >>> 0 or 1 Best, Bhanu Pratap www.bhanubais.com -----Original Message----- From: Tutor [mailto:tutor-bounces+bhanubais=gmail.com at python.org] On Behalf Of Joe Jacques Sent: 03 October 2013 10:02 PM To: tutor at python.org Subject: [Tutor] how to generate random numbers in Python Problems in the link http://home.manhattan.edu/~ankur.agrawal/cmpt101/assgn5.txt Sent from my iPhone _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor From steve at pearwood.info Sun Oct 6 04:52:04 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 6 Oct 2013 13:52:04 +1100 Subject: [Tutor] class decorator question In-Reply-To: <1381001174.17868.YahooMailNeo@web163806.mail.gq1.yahoo.com> References: <1380976426.80681.YahooMailNeo@web163802.mail.gq1.yahoo.com> <20131005131442.GR7989@ando> <1381001174.17868.YahooMailNeo@web163806.mail.gq1.yahoo.com> Message-ID: <20131006025204.GS7989@ando> On Sat, Oct 05, 2013 at 12:26:14PM -0700, Albert-Jan Roskam wrote: > >> On http://lucumr.pocoo.org/2013/5/21/porting-to-python-3-redux/ I saw > >> a very cool and useful example of a class decorator. It (re)implements > >> __str__ and __unicode__ in case Python 2 is used. For Python 3, the > >> decorator does nothing. I wanted to generalize this decorator so the > >> __str__ method under Python 2 encodes the string to an arbitrary > >> encoding. This is what I've created: http://pastebin.com/vghD1bVJ. > >> > >> It works, but the code is not very easy to understand, I am affraid. > > > >It's easy to understand, it's just doing it the wrong way. It creates > >and subclass of your class, which it shouldn't do. > > Why not? Because it's an unusual coding pattern? Or is it ineffecient? It is both of those things. (Well, the inefficiency is minor.) My main objection is that it is inelegant, like using a screwdriver as a chisel instead of using a chisel -- even when it's "good enough", it's not something you want other people to see you doing if you care about looking like a craftsman :-) Another issue is to do with naming. In your example, you decorate Test. What that means in practice is that you create a new class, Klass(Test), throw away Test, and bind Klass to the top-level name Test. So in effect you're doing this: class Test # The undecorated version. class Klass(Test) # Subclass it inside the decorator. Test = Klass # throw away the original and re-use the variable name. But classes, like functions, have *two* names. They have the name they are bound to, the variable name (*usually* one of these, but sometimes zero or two or more). And they have their own internal name: Test.__name__ => returns "Klass" This will make debugging unneccesarily confusing. If you use your decorator three times: @implements_to_string class Spam @implements_to_string class Eggs @implements_to_string class Cheese instances of all three of Spam, Eggs and Cheese will claim to be instances of "Klass". Now there is a simple work-around for this: inside the decorator, call Klass.__name__ = cls.__name__ before returning. But that leads to another issue, where instances of the parent, undecorated, class (if any!) and instances of the child, decorated, class both claim to be from the same "Test" class. This is more of theoretical concern, since you're unlikely to be instantiating the undecorated parent class. > I subclassed because I needed the encoding value in the decorator. > But subclassing may indeed have been overkill. Yes :-) The encoding value isn't actually defined until long after the decorator has finished doing its work, after the class is decorated, and an instance is defined. So there is no encoding value used in the decorator itself. The decorator can trivially refer to the encoding value, so long as that doesn't actually get executed until after an instance is created: def decorate(cls): def spam(self): print(self.encoding) cls.spam = spam return cls works fine without subclassing. > >Here's a better > >approach: inject the appropriate methods into the class directly. Here's > >a version for Python 3: [...] > >This avoids overwriting __str__ if it is already defined, and likewise > >for __bytes__. > > Doesn't a class always have __str__ implementation? No. Where is the __str__ implementation here? class X: pass This class defines no methods at all. Its *superclass*, object in Python 3, defines methods such as __str__. But you'll notice that I didn't call hasattr(cls, '__str__') since that will return True, due to object having a __str__ method. I called '__str__' in cls.__dict__ which only returns True if cls explicitly defines a __str__ method. > Nice, thanks Steven. I made a couple of versions after reading your > advise. The main change that I still had to somehow retrieve the > encoding value from the class to be decorated (decoratee?). I simply > stored it in __dict__. Here is the second version that I created: > http://pastebin.com/te3Ap50C. I tested it in Python 2 and 3. Not sufficiently :-) Your test class has problems. See below. > The Test > class contains __str__ and __unicode__ which are renamed and redefined > by the decorator if Python 3 (or 4, or..) is used. > > > General question: I am using pastebin now. Is that okay, given that > this is not part of the "memory" of the Python Tutor archive? It might > be annoying if people search the archives and get 404s if they try to > follow these links. Just in case I am also pasting the code below: In my opinion, no it's not okay, particularly if your code is short enough to be posted here. Just because a pserson has access to this mailing list doesn't necessarily mean they have access to pastebin. It might be blocked. The site might be down. They might object to websites that require Javascript (pastebin doesn't *require* it, but it's only a matter of time...). Or they may simply be too busy/lazy to follow the link. > from __future__ import print_function > import sys > ??? > def decorate(cls): > ??? print("decorate called") > ??? if sys.version_info[0] > 2: > ??????? cls.__dict__["__str__"].__name__ = '__bytes__' > ??????? cls.__dict__["__unicode__"].__name__ = '__str__' > ??????? cls.__bytes__ = cls.__dict__["__str__"] > ??????? cls.__str__ = cls.__dict__["__unicode__"]? > ??? return cls I thought your aim was to write something that was cross-version and that added default __str__ and __unicode__ methods to the class if they didn't already exist? [looks back at the original code...] Ah no, my mistake, I misunderstood. The above requires the caller to write their classes using the Python 2 style __str__ and __unicode__ methods. __unicode__ isn't even mandatory in Python 2, but your decorate won't work without it! As given, your decorator: - does nothing in Python 2, even if the caller didn't define __str__ or __unicode__ methods; - fails in Python 3 if the class doesn't define a __unicode__ method; - does the wrong thing in Python 3 if the class already has correctly working __str__ and __bytes__ methods; - doesn't help you if you have a Python 3 style class and want to use it in Python 2; - doesn't work well if the decorated class inherits its __str__ and __unicode__ methods from a parent class. Admittedly, that last one is tricky, thanks to everything inheriting from object. > @decorate > class Test(object): > > ??? def __init__(self): > ??????? self.__dict__["encoding"] = self.encoding Why are you doing that? What is the outcome you are hoping for, and why do you think it is necessary? > ??? def __str__(self): > ??????? return "str called".encode(self.encoding) > > ??? def __unicode__(self): > ??????? return "unicode called" These are wrong! Worse, you have multiple errors that cancel each other out -- sometimes, two wrongs do make a right. In Python 2: calling encode on a byte-string is permitted, but is the wrong thing to do. By accident, it (usually?) works, but you shouldn't do it. So there's your first wrong. When converted to Python 3, the __str__ method becomes __bytes__, and is supposed to return bytes. Now the "str called" literal is Unicode, and encode will work, returning bytes. But it only works because of the first wrong -- if you re-write __str__ to use b"str called", or to call "str called".decode, your Python 3 __bytes__ method will fail. In Python 2, __unicode__ ought to return a unicode string, u"unicode called". By accident, if you return a byte string, Python will decode it using ASCII, and it seems to work. But it's still wrong, and it's particularly likely to go wrong if the __unicode__ method does any, well, Unicode stuff. When converted to __str__ by the decorator, the ex-__unicode__ method will work, but only because you used a (Python2) byte-string literal "..." inside it. If you wrote a u"Unicode string", it would fail in Python 3.1 or 3.2 (but work in 3.3 and better). > ??? @property > ??? def encoding(self): > ??????? """In reality this method extracts the encoding from a file""" > ??????? return "utf-8" # rot13 no longer exists in Python3 Why would you do that? Why not just supply the encoding when you initialise the instance? def __init__(self, encoding): self.encoding = encoding > if __name__ == "__main__": > ??? t = Test() > ??? if sys.version_info[0] == 2: > ??????? print(unicode(t)) > ??? print(str(t)) This is insufficient testing. In Python 2, you need to test both unicode(t) and str(t). In Python 3, you need to test both str(t) and bytes(t). In may turn out that, by accident, all four tests work for the given Test class. But that's not going to apply to everything. -- Steven From steve at pearwood.info Sun Oct 6 04:58:28 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 6 Oct 2013 13:58:28 +1100 Subject: [Tutor] class decorator question In-Reply-To: References: <1380976426.80681.YahooMailNeo@web163802.mail.gq1.yahoo.com> <20131005131442.GR7989@ando> <1381001174.17868.YahooMailNeo@web163806.mail.gq1.yahoo.com> Message-ID: <20131006025828.GT7989@ando> On Sun, Oct 06, 2013 at 01:06:18AM +0100, Alan Gauld wrote: > On 05/10/13 20:26, Albert-Jan Roskam wrote: > > >General question: I am using pastebin now. Is that okay, > > For code as short as this it's probably best kept with the message. > But once you get to 100+ lines its more debatable and if you get > to 200+ lines I'd definitely say a pastebin is better. If somebody is tempted to post 200+ lines here, they probably shouldn't. Instead, they should read this: http://sscce.org/ -- Steven From breamoreboy at yahoo.co.uk Sun Oct 6 12:39:50 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 06 Oct 2013 11:39:50 +0100 Subject: [Tutor] class decorator question In-Reply-To: <20131006025828.GT7989@ando> References: <1380976426.80681.YahooMailNeo@web163802.mail.gq1.yahoo.com> <20131005131442.GR7989@ando> <1381001174.17868.YahooMailNeo@web163806.mail.gq1.yahoo.com> <20131006025828.GT7989@ando> Message-ID: On 06/10/2013 03:58, Steven D'Aprano wrote: > On Sun, Oct 06, 2013 at 01:06:18AM +0100, Alan Gauld wrote: >> On 05/10/13 20:26, Albert-Jan Roskam wrote: >> >>> General question: I am using pastebin now. Is that okay, >> >> For code as short as this it's probably best kept with the message. >> But once you get to 100+ lines its more debatable and if you get >> to 200+ lines I'd definitely say a pastebin is better. > > If somebody is tempted to post 200+ lines here, they probably shouldn't. > Instead, they should read this: > > http://sscce.org/ > > I totally agree. -- Roses are red, Violets are blue, Most poems rhyme, But this one doesn't. Mark Lawrence From fomcl at yahoo.com Sun Oct 6 18:28:52 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sun, 6 Oct 2013 09:28:52 -0700 (PDT) Subject: [Tutor] class decorator question In-Reply-To: <20131006025204.GS7989@ando> References: <1380976426.80681.YahooMailNeo@web163802.mail.gq1.yahoo.com> <20131005131442.GR7989@ando> <1381001174.17868.YahooMailNeo@web163806.mail.gq1.yahoo.com> <20131006025204.GS7989@ando> Message-ID: <1381076932.14735.YahooMailNeo@web163801.mail.gq1.yahoo.com> ----- Original Message ----- > From: Steven D'Aprano > To: tutor at python.org > Cc: > Sent: Sunday, October 6, 2013 4:52 AM > Subject: Re: [Tutor] class decorator question > > On Sat, Oct 05, 2013 at 12:26:14PM -0700, Albert-Jan Roskam wrote: > >> >> On http://lucumr.pocoo.org/2013/5/21/porting-to-python-3-redux/ I > saw >> >> a very cool and useful example of a class decorator. It > (re)implements >> >> __str__ and __unicode__ in case Python 2 is used. For Python 3, > the >> >> decorator does nothing. I wanted to generalize this decorator so > the >> >> __str__ method under Python 2 encodes the string to an arbitrary >> >> encoding. This is what I've created: > http://pastebin.com/vghD1bVJ. >> >> >> >> It works, but the code is not very easy to understand, I am > affraid. >> > >> >It's easy to understand, it's just doing it the wrong way. It > creates >> >and subclass of your class, which it shouldn't do. >> >> Why not? Because it's an unusual coding pattern? Or is it ineffecient? > > It is both of those things. (Well, the inefficiency is minor.) My > main objection is that it is inelegant, like using a screwdriver as > a chisel instead of using a chisel -- even when it's "good > enough", > it's not something you want other people to see you doing if you > care about looking like a craftsman :-) or use a shoe to hammer a nail in the wall... ;-) > Another issue is to do with naming. In your example, you decorate Test. > What that means in practice is that you create a new class, Klass(Test), > throw away Test, and bind Klass to the top-level name Test. So in effect > you're doing this: > > class Test # The undecorated version. > > class Klass(Test)? # Subclass it inside the decorator. > > Test = Klass? # throw away the original and re-use the variable name. > > But classes, like functions, have *two* names. They have the name they > are bound to, the variable name (*usually* one of these, but sometimes > zero or two or more). And they have their own internal name: > > Test.__name__ > => returns "Klass" > > > This will make debugging unneccesarily confusing. If you use your > decorator three times: > > @implements_to_string > class Spam > > @implements_to_string > class Eggs > > @implements_to_string > class Cheese > > > instances of all three of Spam, Eggs and Cheese will claim to be > instances of "Klass". That would indeed be *very* confusing. > Now there is a simple work-around for this: inside the decorator, call > > Klass.__name__ = cls.__name__ > > before returning. But that leads to another issue, where instances of > the parent, undecorated, class (if any!) and instances of the child, > decorated, class both claim to be from the same "Test" class. This is > more of theoretical concern, since you're unlikely to be instantiating > the undecorated parent class. > > >> I subclassed because I needed the encoding value in the decorator. >> But subclassing may indeed have been overkill. > > Yes :-) > > The encoding value isn't actually defined until long after the decorator > has finished doing its work, after the class is decorated, and an > instance is defined. So there is no encoding value used in the decorator > itself. The decorator can trivially refer to the encoding value, so long > as that doesn't actually get executed until after an instance is > created: > > def decorate(cls): > ? ? def spam(self): > ? ? ? ? print(self.encoding) > ? ? cls.spam = spam > ? ? return cls > > works fine without subclassing. waah, why didn't I think of this? I've been making this way more complicated than needed. self.__dict__["encoding"] = self.encoding (see also below) was another way I considered to pass the encoding value from the class to its decorator. I even considered making a class decorator with arguments. All unnecesary. ? > >> >Here's a better >> >approach: inject the appropriate methods into the class directly. > Here's >> >a version for Python 3: > [...] >> >This avoids overwriting __str__ if it is already defined, and likewise >> >for __bytes__. >> >> Doesn't a class always have __str__ implementation? > > No. Where is the __str__ implementation here? > > class X: > ? ? pass > > This class defines no methods at all. Its *superclass*, object in Python > 3, defines methods such as __str__. But you'll notice that I didn't call > > > ? ? hasattr(cls, '__str__') > > since that will return True, due to object having a __str__ method. I > called > > ? ? '__str__' in cls.__dict__ > > which only returns True if cls explicitly defines a __str__ method. aaaaaahh, yes, of course these are not the same so 'method_name' in cls.__dict__ tests whether method_name is *implemented* in that class. In many/most cases hasattr is all you need because you want to know whether method_name can be *called* in that class. ? >> Nice, thanks Steven. I made a couple of versions after reading your >> advise. The main change that I still had to somehow retrieve the >> encoding value from the class to be decorated (decoratee?). I simply >> stored it in __dict__. Here is the second version that I created: >> http://pastebin.com/te3Ap50C. I tested it in Python 2 and 3. > > Not sufficiently :-) Your test class has problems. See below. > > > >> The Test >> class contains __str__ and __unicode__ which are renamed and redefined >> by the decorator if Python 3 (or 4, or..) is used. >> >> >> General question: I am using pastebin now. Is that okay, given that >> this is not part of the "memory" of the Python Tutor archive? It > might >> be annoying if people search the archives and get 404s if they try to >> follow these links. Just in case I am also pasting the code below: > > In my opinion, no it's not okay, particularly if your code is short > enough to be posted here. > > Just because a pserson has access to this mailing list doesn't > necessarily mean they have access to pastebin. It might be blocked. The > site might be down. They might object to websites that require > Javascript (pastebin doesn't *require* it, but it's only a matter of > time...). Or they may simply be too busy/lazy to follow the link. It's also easy to do both. I always hope code in mails does not get mangled (even if it's plain text). The colour coding of pastebin and similar sites helps other readers understand code more easily. And I agree posting long code is a no-no. ? >> from __future__ import print_function >> import sys >> ??? >> def decorate(cls): >> ??? print("decorate called") >> ??? if sys.version_info[0] > 2: >> ??????? cls.__dict__["__str__"].__name__ = '__bytes__' >> ??????? cls.__dict__["__unicode__"].__name__ = '__str__' >> ??????? cls.__bytes__ = cls.__dict__["__str__"] >> ??????? cls.__str__ = cls.__dict__["__unicode__"]? >> ??? return cls > > I thought your aim was to write something that was cross-version and > that added default __str__ and __unicode__ methods to the class if they > didn't already exist? [looks back at the original code...] Ah no, my > mistake, I misunderstood. > > The above requires the caller to write their classes using the Python 2 > style __str__ and __unicode__ methods. __unicode__ isn't even mandatory > in Python 2, but your decorate won't work without it! > > As given, your decorator: > - does nothing in Python 2, even if the caller didn't define __str__ > ? or __unicode__ methods;. I *know* that I defined three classes that each contain __str__ and __unicode__, so is it still a good idea to test for their existence? So a meta question: How generally applicable should code, in this case a decorator, be? Should one always strive for code that could readily be re-used in other places? It is cool (and efficient, and intellectually gratifying) if code can be re-used, but isn't a downside that the code is more sophisticated/longer than required for a given context? At what point does refined code turn into "bloated software"? http://c2.com/cgi/wiki?PrematureGeneralization . > - fails in Python 3 if the class doesn't define a? __unicode__ method; > > - does the wrong thing in Python 3 if the class already has correctly > ? working __str__ and __bytes__ methods; > > - doesn't help you if you have a Python 3 style class and want to use > ? it in Python 2; Python 3 style class is a class that inherits from object, right (class Foo(object):...)? I indeed had not considered the possibility that the decorator might fail when used for old-style classes. ? > - doesn't work well if the decorated class inherits its __str__ and > ? __unicode__ methods from a parent class. > > > Admittedly, that last one is tricky, thanks to everything inheriting > from object. > > >> @decorate >> class Test(object): >> >> ??? def __init__(self): >> ??????? self.__dict__["encoding"] = self.encoding > > Why are you doing that? What is the outcome you are hoping for, and why > do you think it is necessary? See also above. I should have deleted that. ? >> ??? def __str__(self): >> ??????? return "str called".encode(self.encoding) >> >> ??? def __unicode__(self): >> ??????? return "unicode called" > > These are wrong! Worse, you have multiple errors that cancel each > other out -- sometimes, two wrongs do make a right. aargh, of course. I should have done (me thinks): ??? def __str__(self): ??????? return self.__unicode__().encode(self.encoding) ??? def __unicode__(self): ??????? return u"unicode called" > In Python 2: calling encode on a byte-string is permitted, but is the > wrong thing to do. By accident, it (usually?) works, but you shouldn't > do it. So there's your first wrong. > > When converted to Python 3, the __str__ method becomes __bytes__, and is > supposed to return bytes. Now the "str called" literal is Unicode, and > > encode will work, returning bytes. But it only works because of the > first wrong -- if you re-write __str__ to use b"str called", or to > call > "str called".decode, your Python 3 __bytes__ method will fail. > > In Python 2, __unicode__ ought to return a unicode string, u"unicode > called". By accident, if you return a byte string, Python will decode it > using ASCII, and it seems to work. But it's still wrong, and it's > particularly likely to go wrong if the __unicode__ method does any, > well, Unicode stuff. > > When converted to __str__ by the decorator, the ex-__unicode__ method > will work, but only because you used a (Python2) byte-string literal > "..." inside it. If you wrote a u"Unicode string", it would > fail in > Python 3.1 or 3.2 (but work in 3.3 and better). > > >> ??? @property >> ??? def encoding(self): >> ??????? """In reality this method extracts the encoding from > a file""" >> ??????? return "utf-8" # rot13 no longer exists in Python3 > > Why would you do that? > > Why not just supply the encoding when you initialise the instance? Counter question: why would I ask the caller for information if that information can automatically be retrieved? ? > ? ? def __init__(self, encoding): > ? ? ? ? self.encoding = encoding > > >> if __name__ == "__main__": >> ??? t = Test() >> ??? if sys.version_info[0] == 2: >> ??????? print(unicode(t)) >> ??? print(str(t)) > > This is insufficient testing. In Python 2, you need to test both > unicode(t) and str(t). In Python 3, you need to test both str(t) and > bytes(t). > > In may turn out that, by accident, all four tests work for the given > Test class. But that's not going to apply to everything. > > > > > -- > Steven > _______________________________________________ > Tutor maillist? -? Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From bgailer at gmail.com Sun Oct 6 18:52:17 2013 From: bgailer at gmail.com (bob gailer) Date: Sun, 06 Oct 2013 12:52:17 -0400 Subject: [Tutor] Parsing Rhino Sightings - Python In-Reply-To: References: Message-ID: <52519541.5040506@gmail.com> On 10/6/2013 12:11 PM, Mason Majors wrote: > Dear Bob, > > I just came across your email address on the following website: > > https://mail.python.org/pipermail//tutor/2011-November/087044.html > > I was wondering, if you were able to provide any help and slove this > Pythn coding problem, as I am working on a similar coing script > without much success. > > Just wondering if yo umight be able to help please? I am copying this to the tutor list, as that gives you access to more helpers. In the above link I said: "Welcome to the Tutor List. We are a few volunteers who enjoy tutoring folk on specific Python learning issues. We like posts that are in plain text rather than HTML. Please post plain text in future. Also your code has a blank line between every LOC, Please remove these in future posts I failed to see any specific request in your post so all I can say is welcome and how can we help you. Did you run the code? Did you get errors or unexpected results? Please report these. Errors usually appear as a traceback. Include the entire traceback (after putting in some effort to figure out the error on your own). unexpected results? Tell us what you expected and how the results differ. Good luck!" -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From michael.weylandt at gmail.com Sun Oct 6 23:27:02 2013 From: michael.weylandt at gmail.com (R. Michael Weylandt ) Date: Sun, 6 Oct 2013 17:27:02 -0400 Subject: [Tutor] writing python on the web In-Reply-To: References: Message-ID: <87CA4033-C6C0-4EA6-B052-E6985F71B250@gmail.com> On Oct 5, 2013, at 11:47, roberto wrote: > > Thank you guys, I'll take a look at what you suggested! Also take note of some of the cloud based solutions developed in the scientific community. Wakari (from Continuum Analytics) has a free plan that would likely suffice for students in their first programming course. I think they also have educational arrangements, but I've never used them. That said, there's little more exciting as a beginner than writing code which does something on your own machine that you'd normally do by hand. Cloud based prevents that a priori. MW From gupta.leena at gmail.com Tue Oct 8 22:46:12 2013 From: gupta.leena at gmail.com (Leena Gupta) Date: Tue, 8 Oct 2013 13:46:12 -0700 Subject: [Tutor] Processing CSV files Message-ID: Hello, Looking for some inputs on Python's csv processing feature. I need to process a large csv file every 5-10 minutes. The file could contain 3mill to 10 mill rows and size could be 6MB to 10MB(+). As part of the processing, I need to sum up a number value by grouping on certain attributes and store the output in a datastore. I wanted to know if Python is recommended and can it be used for processing data in csv files of this size? Any issues that we need to be aware of? I believe Python has a csv library as well. Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Oct 8 23:28:04 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 08 Oct 2013 22:28:04 +0100 Subject: [Tutor] Processing CSV files In-Reply-To: References: Message-ID: On 08/10/13 21:46, Leena Gupta wrote: > I need to process a large csv file every 5-10 minutes. The file could > contain 3mill to 10 mill rows and size could be 6MB to 10MB(+). Assuming you have a modern multi-core PC with >2G RAM then those sizes should not be a problem. If you have an older PC then you may need to be a bit more clever about how you load the files. > ... I need to sum up a number value by grouping on > certain attributes and store the output in a datastore. Again that sounds fairly normal. There are modules that can help with that too. > I wanted to know if Python is recommended and can it be used > for processing data in csv files of this size? Yes, for sure. > Python has a csv library as well. Yes and it is quite well documented but if you have specific questions we can try to help. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From davea at davea.name Tue Oct 8 23:28:17 2013 From: davea at davea.name (Dave Angel) Date: Tue, 8 Oct 2013 21:28:17 +0000 (UTC) Subject: [Tutor] Processing CSV files References: Message-ID: On 8/10/2013 16:46, Leena Gupta wrote: > Hello, > > Looking for some inputs on Python's csv processing feature. > > I need to process a large csv file every 5-10 minutes. The file could > contain 3mill to 10 mill rows and size could be 6MB to 10MB(+). As part of > the processing, I need to sum up a number value by grouping on certain > attributes and store the output in a datastore. I wanted to know if Python > is recommended and can it be used for processing data in csv files of this > size? Any issues that we need to be aware of? I believe Python has a csv > library as well. > > Thanks! > > >
Hello,

Looking for some inputs on Python's csv processing feature.

I need to process a large csv file every 5-10 minutes. The file could contain 3mill to 10 mill rows and size could be 6MB to 10MB(+). As part of the processing, I need to sum up a number value by grouping on certain attributes and store the output in a datastore. I wanted to know if Python is recommended and can it be used for processing data in csv files of this size? Any issues that we need to be aware of? I believe Python has a csv library as well.
>
Thanks!
> Please use text messages here, not html. It not only wastes space, but frequently messes up formatting. Python's csv logic should have no problem dealing with a file of 10 million rows. As long as you're not trying to keep all 10 million of them in some internal data structure, the csv logic will deal you a row at a time, in a most incremental fashion. Just make sure the particular datastore you require is supported in Python. -- DaveA From abdallah.rabah91 at googlemail.com Tue Oct 8 20:33:16 2013 From: abdallah.rabah91 at googlemail.com (Rabah Abdallah) Date: Tue, 8 Oct 2013 20:33:16 +0200 Subject: [Tutor] No module named odbchelper Message-ID: <5B16195A-7B39-41B9-AE47-9DDC6891DF66@googlemail.com> Hi I am using dive in python book to to learn python programing languege on mac in one of the examples is odbchelper imported but when i start debugging I recieved ImportError: No module named odbchelper here is my code on text wrangler import sys sys.path.append('/Users/rabahabdallah/Desktop') from apihelper import info li = [] print info(li) print ' ' print ' ' """Advanced Usage of apihelper.py""" import odbchelper a = info(odbcherper) print a b = info(odbchelper, 30) print b c = info(odbchelper, 30, 0) print c thanks From connormdy at gmail.com Tue Oct 8 18:41:54 2013 From: connormdy at gmail.com (Connor Moody) Date: Tue, 8 Oct 2013 11:41:54 -0500 Subject: [Tutor] Help Beginning Message-ID: Hello, I'm starting off programing with python and i like it (so far). Im having trouble finding a website that simply teaches it. I have never programmed before and i thought this would be a great place to start. What websites should I use to start off? Sent from my iPad From kjakupak at gmail.com Tue Oct 8 19:42:49 2013 From: kjakupak at gmail.com (Kristen Jakupak) Date: Tue, 8 Oct 2013 13:42:49 -0400 Subject: [Tutor] Converting letters to numbers? Message-ID: I have to define a function add(c1, c2), where c1 and c2 are capital letters; the return value should be the sum (obtained by converting the letters to numbers, adding mod 26, then converting back to a capital letter). What I have so far is def add(c1, c2): ans = '' for i in c1 + c2: ans += chr((((ord(i)-65))%26) + 65) return ans Any guidance would be great, thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From thabilerampa at gmail.com Tue Oct 8 22:38:02 2013 From: thabilerampa at gmail.com (Thabile Rampa) Date: Tue, 8 Oct 2013 22:38:02 +0200 Subject: [Tutor] Tax Brand Message-ID: Hello, So my task is to get information from a user about their salary and then find their net salary and tax deductions. I have seemingly worked everything fine until the part where I am supposed to tell them what tax Band they are in (i.e 1,2,3 or 4). My code is like this: taxBAND = None GrossSalary = None costs = None taxdeducted =None netSalary = None line ="-"*80 name ="" while not name: name =raw_input("ENTER NAME HERE: ") while not costs: costs =float(raw_input("enter costs here: ")) while not GrossSalary: GrossSalary= int(raw_input("enter your gross salary: ")) if (GrossSalary < 50000): taxdeducted= 0.05*(GrossSalary -costs) netSalary = GrossSalary - taxdeducted while GrossSalary < 50000: print taxBAND == 1 elif (GrossSalary >= 50000 and GrossSalary < 150000): taxdeducted = 0.1*(GrossSalary - costs) netSalary = GrossSalary - taxdeducted print line print "\t\t BURS STATEMENT: ",name print line print "Gross", "\t Costs", "\t Tax BAND", "\tTax Deducted", "\t Net Salary" print GrossSalary,"\t",costs,"\t\b",taxBAND,"\t",taxdeducted,"\t\t",netSalary print line I haven't put in the whole code because it's too long. I instead want to focus on the problem which can be found in the if section: print taxBAND == 1 I have tried all the different operators, from augmentation to logical to comparison, but I still get errrors. The errors I have acquired so far are: 1. Traceback (most recent call last): File "X:/xxx/Xxxx.py", line 30, in taxBAND += 1 TypeError: unsupported operand type (s) for +=: 'NoneType' and 'int' 2. Traceback (most recent call last): File "X:/xxx/Xxxx.py", line 30, in taxBAND = I NameError: Name 'I' is not defined (the first two errors were before i added the line "while GrossSalary < 50000:") 3. Traceback (most recent call last): File "X:/xxx/Xxxx.py", line 31, in taxBAND += 1 TypeError: unsupported operand type (s) for +=: 'NoneType' and 'int' 4. Traceback (most recent call last): File "X:/xxx/Xxxx.py", line 31, in taxBAND = I NameError: Name 'I' is not defined Regards, Tab -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Oct 9 00:35:59 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 08 Oct 2013 23:35:59 +0100 Subject: [Tutor] Help Beginning In-Reply-To: References: Message-ID: On 08/10/13 17:41, Connor Moody wrote: >Im having trouble finding a website that simply teaches it. There is a page at python.org for complete beginners. One thing to watch is which version of Python you use. Some tutorials are written for Python v2 others for v3, and although similar they are not directly compatible. OTOH you could try mine(see below) which covers the basics for both v2 and v3 :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Wed Oct 9 00:37:59 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 08 Oct 2013 23:37:59 +0100 Subject: [Tutor] No module named odbchelper In-Reply-To: <5B16195A-7B39-41B9-AE47-9DDC6891DF66@googlemail.com> References: <5B16195A-7B39-41B9-AE47-9DDC6891DF66@googlemail.com> Message-ID: On 08/10/13 19:33, Rabah Abdallah wrote: > Hi > > I am using dive in python book to to learn python programing languege on mac > in one of the examples is odbchelper imported but when i start debugging I recieved > ImportError: No module named odbchelper ODBC is a Microsoft database access protocol. It may not exist on non Windows systems. From the path you give below that might be the problem here. > import sys > sys.path.append('/Users/rabahabdallah/Desktop') Looks like Linux to me? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Wed Oct 9 00:45:46 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 08 Oct 2013 23:45:46 +0100 Subject: [Tutor] Converting letters to numbers? In-Reply-To: References: Message-ID: On 08/10/13 18:42, Kristen Jakupak wrote: > I have to define a function add(c1, c2), where c1 and c2 are capital > letters; the return value should be the sum (obtained by converting the > letters to numbers, adding mod 26, then converting back to a capital > letter). That makes no sense to me. Can you explain what you mean in more detail. I read it as: def add(c1, c2): i1 = ord(c1) # convert to numbers i2 = ord(c2) i1 += i1 % 26 # add mod 26 - why? i2 += i2 % 26 return str(i1+i2).upper() #add together and convert to upper case That doesn't seem sensible to me. > What I have so far is > def add(c1, c2): > ans = '' > for i in c1 + c2: > ans += chr((((ord(i)-65))%26) + 65) > return ans That seems different to what you described, and equally non sensible? Can you describe what the output should look like: c1 c2 result ------------------------ a b ??? c d ??? A a ??? Can you create a sample table showing input and desired output? That might help. And if you can't, how do you intend to test it? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Wed Oct 9 01:19:12 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 09 Oct 2013 00:19:12 +0100 Subject: [Tutor] Tax Brand In-Reply-To: References: Message-ID: On 08/10/13 21:38, Thabile Rampa wrote: > deductions. I have seemingly worked everything fine until the part where > I am supposed to tell them what tax Band they are in (i.e 1,2,3 or 4). > My code is like this: > > taxBAND = None > GrossSalary = None > costs = None > taxdeducted =None > netSalary = None You don't really need these since you initialise everything below... But thats not your problem. > line ="-"*80 > name ="" > while not name: > name =raw_input("ENTER NAME HERE: ") > while not costs: > costs =float(raw_input("enter costs here: ")) > while not GrossSalary: > GrossSalary= int(raw_input("enter your gross salary: ")) OK so far > if (GrossSalary < 50000): > taxdeducted= 0.05*(GrossSalary -costs) > netSalary = GrossSalary - taxdeducted > while GrossSalary < 50000: Here is a problem. You already know the salary is less than 50000 since you tested it in the if statement. So now you create a loop that will always be true so it will loop forever. > print taxBAND == 1 And you compound that by trying to print the result of a Boolean expression which will be either True or False. I suspect you actually want to print(or store?) the taxBAND (unusual capitalization BTW) > elif (GrossSalary >= 50000 and GrossSalary < 150000): > taxdeducted = 0.1*(GrossSalary - costs) > netSalary = GrossSalary - taxdeducted And here you make no attempt to set the taxBAND? > print line > print "\t\t BURS STATEMENT: ",name > print line > print "Gross", "\t Costs", "\t Tax BAND", "\tTax Deducted", "\t Net Salary" > print > GrossSalary,"\t",costs,"\t\b",taxBAND,"\t",taxdeducted,"\t\t",netSalary Nice try but you'll find it easier to use the string format operation to create fixed length fields. And that will still depend on your user having fixed space fonts. > 1. > Traceback (most recent call last): > File "X:/xxx/Xxxx.py", line 30, in > taxBAND += 1 > TypeError: unsupported operand type (s) for +=: 'NoneType' and 'int' Because you set taxBAND to None initially. You probably just wanted to set taxBAND to 1 not add it. > 2. > Traceback (most recent call last): > File "X:/xxx/Xxxx.py", line 30, in > taxBAND = I > NameError: Name 'I' is not defined And that's true too. You either wanted to set it to 1 or to 'I' (with quotes) > (the first two errors were before i added the line "while GrossSalary < > 50000:") Probablty thats correct, but you want assdignment not equality test ie taxBAND = 1 > 3. > Traceback (most recent call last): > File "X:/xxx/Xxxx.py", line 31, in > taxBAND += 1 > TypeError: unsupported operand type (s) for +=: 'NoneType' and 'int' See above > 4. > Traceback (most recent call last): > File "X:/xxx/Xxxx.py", line 31, in > taxBAND = I > NameError: Name 'I' is not defined And again. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From gupta.leena at gmail.com Wed Oct 9 01:26:34 2013 From: gupta.leena at gmail.com (Leena Gupta) Date: Tue, 8 Oct 2013 16:26:34 -0700 Subject: [Tutor] Processing CSV files In-Reply-To: References: Message-ID: Dave, Alan - thanks for replying. We have a box with 16GB RAM so RAM should not be an issue hopefully. The datastore is Cassandra and I'm hoping to use the pycassa library for interaction. I do have an additional question related to Cassandra & Python. As part of data processing, I need to fetch slices of data from Cassandra and run computations like sum and percentile calculation on it. The sum along with other attributes needs to be stored back in another Cassandra table that will be queried by end users of a reporting system. This is because Cassandra does not provide any aggregation functions, so we will precompute the aggregations and store in cassandra. So for calculating the sum & percentile in Python, some of the data slices on Cassandra could fetch a lot of rows (e.g.750,000 to 1mill rows) ? And since I need to compute a sum and percentile, I need to consider all the rows. I am planning to do this in Python. Do you foresee any issues with this approach? Any advise on this will be greatly appreciated. Thanks a ton! On Tue, Oct 8, 2013 at 2:28 PM, Dave Angel wrote: > On 8/10/2013 16:46, Leena Gupta wrote: > > > Hello, > > > > Looking for some inputs on Python's csv processing feature. > > > > I need to process a large csv file every 5-10 minutes. The file could > > contain 3mill to 10 mill rows and size could be 6MB to 10MB(+). As part > of > > the processing, I need to sum up a number value by grouping on certain > > attributes and store the output in a datastore. I wanted to know if > Python > > is recommended and can it be used for processing data in csv files of > this > > size? Any issues that we need to be aware of? I believe Python has a csv > > library as well. > > > > Thanks! > > > > > >
Hello,

Looking for some inputs on Python's csv > processing feature.

I need to process a large csv file every 5-10 > minutes. The file could contain 3mill to 10 mill rows and size could be 6MB > to 10MB(+). As part of the processing, I need to sum up a number value by > grouping on certain attributes and store the output in a datastore. I > wanted to know if Python is recommended and can it be used for processing > data in csv files of this size? Any issues that we need to be aware of? I > believe Python has a csv library as well.
> >
Thanks!
> > > > Please use text messages here, not html. It not only wastes space, but > frequently messes up formatting. > > Python's csv logic should have no problem dealing with a file of 10 > million rows. As long as you're not trying to keep all 10 million of > them in some internal data structure, the csv logic will deal you a row > at a time, in a most incremental fashion. > > Just make sure the particular datastore you require is supported in > Python. > > > -- > DaveA > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Wed Oct 9 01:39:36 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 9 Oct 2013 10:39:36 +1100 Subject: [Tutor] Tax Brand In-Reply-To: References: Message-ID: <20131008233936.GZ7989@ando> On Tue, Oct 08, 2013 at 10:38:02PM +0200, Thabile Rampa wrote: > taxBAND = None You set taxBAND to None here. This is the only time you assign a value to taxBAND. > if (GrossSalary < 50000): > taxdeducted= 0.05*(GrossSalary -costs) > netSalary = GrossSalary - taxdeducted > while GrossSalary < 50000: > print taxBAND == 1 This will be an infinite loop. You test whether GrossSalary is less than 50000, and if it is, you print True or False (it will always be False, because taxBAND at this point is still None). Then you test whether GrossSalary is less than 50000, which of course it will be, since you haven't changed it, then print False again. Then you test whether GrossSalary is still less than 50000, which is will be, then print False again. And again. And again. And again. Until the sun burns out and the planet is destroyed. (Or you type Ctrl-C to halt the program.) What was your intention in this bit of code? Can you explain in English what you hoped to do? The first step in programming is to understand in your own head what you hope to do, then you do it. If you're unclear what needs to be done, how can you do it? > elif (GrossSalary >= 50000 and GrossSalary < 150000): > taxdeducted = 0.1*(GrossSalary - costs) > netSalary = GrossSalary - taxdeducted You can write that test more simply as: elif 50000 <= GrossSalary < 150000: > print line > print "\t\t BURS STATEMENT: ",name > print line > print "Gross", "\t Costs", "\t Tax BAND", "\tTax Deducted", "\t Net Salary" You can simplify this by making it a single string: print "Gross\tCosts\tTax BAND\tTax Deducted\tNet Salary" > print > GrossSalary,"\t",costs,"\t\b",taxBAND,"\t",taxdeducted,"\t\t",netSalary > print line What is the purpose of the \b above? Is that a typo? Why do you sometimes have one tab \t and sometimes two \t\t? In this case, since you have never changed the value of TaxBAND, it is still set to the same value you gave it all the way back at the beginning of the program. Remember this line? taxBAND = None taxBAND will still be None, since you have never set it to something else. In English, you might say: If the gross salary is less than 50000, then set taxBAND to 1; otherwise, if the gross salary is less than 150000, then set taxBAND to 2; otherwise ... In your code, you already have tests for the gross salary: if GrossSalary < 50000: # things to do when gross salary is less than 50000 One of those "things to do", which you don't do, is to set taxBAND to 1, or another way to say the same thing, assign 1 to taxBAND. Do you remember how to assign values to a variable? taxBAND = None # assign None to the variable taxBAND > I haven't put in the whole code because it's too long. I instead want to > focus on the problem which can be found in the if section: print taxBAND == > 1 > > I have tried all the different operators, from augmentation to logical to > comparison, but I still get errrors. The errors I have acquired so far are: Ah, the good ol' "Make Random Changes In The Hope That The Error Will Go Away" strategy! :-) Making random changes to the code will just give you random errors. You must understand what you are writing. The first step is to understand the errors: > taxBAND += 1 > TypeError: unsupported operand type (s) for +=: 'NoneType' and 'int' Remember, taxBAND is still set to None. Here you are trying to add 1 (an int, or integer) to None. Python does not allow that. Why are you trying to *add* 1? Why not subtract 1, or add 15? Ask yourself, what am I actually trying to accomplish? > Traceback (most recent call last): > File "X:/xxx/Xxxx.py", line 30, in > taxBAND = I > NameError: Name 'I' is not defined In this case, you are telling Python "assign the value of the variable I to the variable taxBAND", and Python says "I? What the hell is variable I? Never heard of it." Which is absolutely correct, since nowhere do you assign a value to I: # you don't do anything like this I = 1972 > Traceback (most recent call last): > File "X:/xxx/Xxxx.py", line 31, in > taxBAND += 1 > TypeError: unsupported operand type (s) for +=: 'NoneType' and 'int' This is exactly the same error as above. > Traceback (most recent call last): > File "X:/xxx/Xxxx.py", line 31, in > taxBAND = I > NameError: Name 'I' is not defined And so is this. -- Steven From alan.gauld at btinternet.com Wed Oct 9 01:44:38 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 09 Oct 2013 00:44:38 +0100 Subject: [Tutor] Processing CSV files In-Reply-To: References: Message-ID: On 09/10/13 00:26, Leena Gupta wrote: > I do have an additional question related to Cassandra & Python. As part > of data processing, I need to fetch slices of data from Cassandra and > run computations like sum and percentile calculation on it. Sorry, I've never even heard of Cassandra before > So for calculating the sum & percentile in Python, some of the data > slices on Cassandra could fetch a lot of rows (e.g.750,000 to 1mill > rows) ? And since I need to compute a sum and percentile, I need to > consider all the rows. But not all at the same time. You can create a running total and keep track of the count. Assuming the API supports an iterative read - but I've no experience there. But if the rows are short even a million rows shouldn't be a big problem given your RAM. And assuming you are using 64bit of course... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From martin at linux-ip.net Wed Oct 9 01:45:32 2013 From: martin at linux-ip.net (Martin A. Brown) Date: Tue, 8 Oct 2013 19:45:32 -0400 Subject: [Tutor] Processing CSV files In-Reply-To: References: Message-ID: Hello there, : We have a box with 16GB RAM so RAM should not be an issue : hopefully. : : The datastore is Cassandra and I'm hoping to use the pycassa : library for interaction. : : I do have an additional question related to Cassandra & Python. : As part of data processing, I need to fetch slices of data from : Cassandra and run computations like sum and percentile : calculation on it. The sum along with other attributes needs to : be stored back in another Cassandra table that will be queried by : end users of a reporting system. This is because Cassandra does : not provide any aggregation functions, so we will precompute the : aggregations and store in cassandra. : : So for calculating the sum & percentile in Python, some of the : data slices on Cassandra could fetch a lot of rows (e.g.750,000 : to 1mill rows) ? And since I need to compute a sum and : percentile, I need to consider all the rows. I am planning to do : this in Python. Do you foresee any issues with this approach? Any : advise on this will be greatly appreciated. Even if you simply use sum(), it'll be just fine to compute sum(). Computing won't be the bottleneck--retrieval is more likely to be your problem. For 1 million rows simulation, which occurs pretty darned quickly, try this out: >>> sum(random.sample(xrange(10000000),1000000)) 5002880911167 >>> len(random.sample(xrange(10000000),1000000)) 1000000 If you want to do percentiles, then .... do you know about numpy and pandas? You may want to look into these good, mature, third-party Python libraries. numpy: http://www.numpy.org/ pandas: http://pandas.pydata.org/ They are both nice tools for working with data in Python. Pandas bears a clear resemblance to R. I think numpy is one of the oldest scientific computational libraries available for Python. Good luck, -Martin -- Martin A. Brown http://linux-ip.net/ From davea at davea.name Wed Oct 9 02:02:50 2013 From: davea at davea.name (Dave Angel) Date: Wed, 9 Oct 2013 00:02:50 +0000 (UTC) Subject: [Tutor] Converting letters to numbers? References: Message-ID: On 8/10/2013 13:42, Kristen Jakupak wrote: > I have to define a function add(c1, c2), where c1 and c2 are capital > letters; the return value should be the sum (obtained by converting the > letters to numbers, adding mod 26, then converting back to a capital > letter). > > What I have so far is > def add(c1, c2): > ans = '' > for i in c1 + c2: > ans += chr((((ord(i)-65))%26) + 65) > return ans > > Any guidance would be great, thanks. > > >
I have to define a function add(c1, c2), where c1 and c2 are capital letters; the return value should be the sum (obtained by converting the letters to numbers, adding mod 26, then converting back to a capital letter).?
> >
What I have so far is
def add(c1, c2):?
> > ? ? ans = ''?
? ? for i in c1 + c2:?
> > ? ? ? ? ans += chr((((ord(i)-65))%26) + 65)?
? ? return ans?
> >

Any guidance would be great, thanks.
> > I suggest you read the other thread you started. And getting more specific, don't try to do everything on one line. Factor out the logic so you can test each part independently. And add comments describing what each line is trying to do. That way, you'll have a chance of figuring out why things aren't working. After it all works, if you're trying to impress someone, you can squeeze it down to one cryptic line again. -- DaveA From akleider at sonic.net Wed Oct 9 02:50:15 2013 From: akleider at sonic.net (Alex Kleider) Date: Tue, 08 Oct 2013 17:50:15 -0700 Subject: [Tutor] docopt module: defaults appear to be ignored Message-ID: <699eef205224370c65e709fc62e9692b@sonic.net> A recent post recommended the docopt module so I've incorporated it into the code I'm using to learn SQLite. It's not behaving as I expected. Here's a snippet of code: #!/usr/bin/env python # -*- coding : utf -8 -*- # file: 'test' """Usage: test [new_data | text_entry FILE | show_data ] [-hdv] [--db=DATABASE] [--tb=TABLE] -h --help show this -d --debug show debugging statements -v --verbose shows table when not absolutely necessary. --db DATABASE specify database file to use [default: ./uwomeds68.db] --tb TABLE specify table to use [default: matesTb] """ from docopt import docopt cl_args = docopt(__doc__, version='testing v0.1') print "Arguments in effect (from ):" print(cl_args) print "-------------------------------" print I would have expected the defaults (./uwomeds68.db and matesTb) to be populated but as it turns out, values are populated only of --db or --tb are specified on the command line; otherwise, None is assigned to the values keyed by "--db" and "--tb". Here are two example runs: alex at x301:~/Python/SQL/SQLite$ ./test show_data Arguments in effect (from ): {'--db': None, '--tb': None, '-d': False, '-h': False, '-v': False, 'FILE': None, 'new_data': False, 'show_data': True, 'text_entry': False} ------------------------------- alex at x301:~/Python/SQL/SQLite$ ./test show_data --db=new.db Arguments in effect (from ): {'--db': 'new.db', '--tb': None, '-d': False, '-h': False, '-v': False, 'FILE': None, 'new_data': False, 'show_data': True, 'text_entry': False} ------------------------------- My interpretation of the documentation is that the defaults are meant to be picked up. Is that not correct? From steve at pearwood.info Wed Oct 9 03:02:59 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 9 Oct 2013 12:02:59 +1100 Subject: [Tutor] docopt module: defaults appear to be ignored In-Reply-To: <699eef205224370c65e709fc62e9692b@sonic.net> References: <699eef205224370c65e709fc62e9692b@sonic.net> Message-ID: <20131009010259.GC7989@ando> On Tue, Oct 08, 2013 at 05:50:15PM -0700, Alex Kleider wrote: > > A recent post recommended the docopt module so I've incorporated it into > the code I'm using to learn SQLite. It's not behaving as I expected. Since docopt is not a standard part of Python, nor part of the language itself, you may not find anyone here who knows it well enough to solve the problem. Also keep in mind that docopt is still a fairly young package and may still contain bugs. If we can't help, you should try a dedicated docopt mailing list, if any, or try contacting the developer. I haven't actually used docopt, but I'm willing to try to help... > """Usage: test [new_data | text_entry FILE | show_data ] [-hdv] > [--db=DATABASE] [--tb=TABLE] > > -h --help show this > -d --debug show debugging statements > -v --verbose shows table when not absolutely necessary. > --db DATABASE specify database file to use [default: ./uwomeds68.db] > --tb TABLE specify table to use [default: matesTb] The defaults for --db and --tb aren't valid Python objects. Perhaps you need to specify them as strings? --db DATABASE specify database file to use [default: './uwomeds68.db'] --tb TABLE specify table to use [default: 'matesTb'] -- Steven From alan.gauld at btinternet.com Wed Oct 9 03:17:30 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 09 Oct 2013 02:17:30 +0100 Subject: [Tutor] Tax Brand In-Reply-To: <20131008233936.GZ7989@ando> References: <20131008233936.GZ7989@ando> Message-ID: On 09/10/13 00:39, Steven D'Aprano wrote: > Ah, the good ol' "Make Random Changes In The Hope That The Error Will Go > Away" strategy! :-) When I was a young and naive apprentice we had a gnarled old training instructor who called this the "poke n' hope" strategy for fixing faults... (Actually, he probably only seemed gnarled to us, callow, 16 year old, youths, he was probably younger than I am now! :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From akleider at sonic.net Wed Oct 9 05:35:13 2013 From: akleider at sonic.net (Alex Kleider) Date: Tue, 08 Oct 2013 20:35:13 -0700 Subject: [Tutor] docopt module: defaults appear to be ignored In-Reply-To: <20131009010259.GC7989@ando> References: <699eef205224370c65e709fc62e9692b@sonic.net> <20131009010259.GC7989@ando> Message-ID: <02da72dcf330fec7aa954ff008e903f1@sonic.net> On 2013-10-08 18:02, Steven D'Aprano wrote: > Since docopt is not a standard part of Python, nor part of the language > itself, you may not find anyone here who knows it well enough to solve > the problem. Also keep in mind that docopt is still a fairly young > package and may still contain bugs. If we can't help, you should try a > dedicated docopt mailing list, if any, or try contacting the developer. Fair enough. I would submit however that it does seem to be an ideal solution to the challenge of command line parsing. > > I haven't actually used docopt, but I'm willing to try to help... Much appreciated. > >> """Usage: test [new_data | text_entry FILE | show_data ] [-hdv] >> [--db=DATABASE] [--tb=TABLE] >> >> -h --help show this >> -d --debug show debugging statements >> -v --verbose shows table when not absolutely necessary. >> --db DATABASE specify database file to use [default: ./uwomeds68.db] >> --tb TABLE specify table to use [default: matesTb] > > The defaults for --db and --tb aren't valid Python objects. Perhaps you > need to specify them as strings? The docopt module converts these into strings if/when they appear in the command line arguments. According to the documentation these items are not quoted (which is what I assume you are suggesting.) I did try to quote them but it made no difference. Thanks for taking an interest. You are correct that only someone who has used it would likely be in a position to offer advice. I would never have heard about it if it wasn't for this list. ak From breamoreboy at yahoo.co.uk Wed Oct 9 07:13:48 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 09 Oct 2013 06:13:48 +0100 Subject: [Tutor] Processing CSV files In-Reply-To: References: Message-ID: On 08/10/2013 21:46, Leena Gupta wrote: > Hello, > > Looking for some inputs on Python's csv processing feature. > > I need to process a large csv file every 5-10 minutes. The file could > contain 3mill to 10 mill rows and size could be 6MB to 10MB(+). As part > of the processing, I need to sum up a number value by grouping on > certain attributes and store the output in a datastore. I wanted to know > if Python is recommended and can it be used for processing data in csv > files of this size? Any issues that we need to be aware of? I believe > Python has a csv library as well. > > Thanks! > 1) As others have already stated Python can easily handle this. 2) I'd recommend using a csv.DictReader as it makes your code easier to read, please see http://docs.python.org/3/library/csv.html#csv.DictReader. Note the fieldnames parameter is very useful if your files don't have header rows. -- Roses are red, Violets are blue, Most poems rhyme, But this one doesn't. Mark Lawrence From breamoreboy at yahoo.co.uk Wed Oct 9 07:35:08 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 09 Oct 2013 06:35:08 +0100 Subject: [Tutor] docopt module: defaults appear to be ignored In-Reply-To: <699eef205224370c65e709fc62e9692b@sonic.net> References: <699eef205224370c65e709fc62e9692b@sonic.net> Message-ID: On 09/10/2013 01:50, Alex Kleider wrote: > > A recent post recommended the docopt module so I've incorporated it into > the code I'm using to learn SQLite. It's not behaving as I expected. > Here's a snippet of code: > > #!/usr/bin/env python > # -*- coding : utf -8 -*- > # file: 'test' > """Usage: test [new_data | text_entry FILE | show_data ] [-hdv] > [--db=DATABASE] [--tb=TABLE] > > -h --help show this > -d --debug show debugging statements > -v --verbose shows table when not absolutely necessary. > --db DATABASE specify database file to use [default: ./uwomeds68.db] > --tb TABLE specify table to use [default: matesTb] > """ > You have no definitions for new_data, text_entry, FILE and show_data, and the use of the square brackets around them looks wrong. Here's a real life example from my code. """Usage: cashflow.py [-t] ACCOUNTS TRANSFERS ENDDATE (report|plot) Arguments: ACCOUNTS mandatory file containing accounts data TRANSFERS mandatory file containing transfer data ENDDATE mandatory end date for the report or plot Options: -h --help -t show total of accounts """ If you haven't already looked at them there are lots of extremely useful examples here https://github.com/docopt/docopt/tree/master/examples. -- Roses are red, Violets are blue, Most poems rhyme, But this one doesn't. Mark Lawrence From andipersti at gmail.com Wed Oct 9 09:17:52 2013 From: andipersti at gmail.com (Andreas Perstinger) Date: Wed, 09 Oct 2013 09:17:52 +0200 Subject: [Tutor] No module named odbchelper In-Reply-To: References: <5B16195A-7B39-41B9-AE47-9DDC6891DF66@googlemail.com> Message-ID: <52550320.9090504@gmail.com> On 09.10.2013 00:37, Alan Gauld wrote: > On 08/10/13 19:33, Rabah Abdallah wrote: >> Hi >> >> I am using dive in python book to to learn python programing languege on mac >> in one of the examples is odbchelper imported but when i start debugging I recieved >> ImportError: No module named odbchelper > > ODBC is a Microsoft database access protocol. > It may not exist on non Windows systems. From > the path you give below that might be the > problem here. Actually, Mark Pilgrim, the author of "Dive into Python" introduces a module called "odbchelper" in chapter 2: http://www.diveintopython.net/getting_to_know_python/index.html#odbchelper.divein Abdallah, you need to make sure that the file "odbchelper.py" is in the same directory as the script from which you want to import it. Bye, Andreas From __peter__ at web.de Wed Oct 9 09:29:33 2013 From: __peter__ at web.de (Peter Otten) Date: Wed, 09 Oct 2013 09:29:33 +0200 Subject: [Tutor] docopt module: defaults appear to be ignored References: <699eef205224370c65e709fc62e9692b@sonic.net> Message-ID: Alex Kleider wrote: > > A recent post recommended the docopt module so I've incorporated it into > the code I'm using to learn SQLite. It's not behaving as I expected. > Here's a snippet of code: > > > #!/usr/bin/env python > # -*- coding : utf -8 -*- > # file: 'test' > """Usage: test [new_data | text_entry FILE | show_data ] [-hdv] > [--db=DATABASE] [--tb=TABLE] > > -h --help show this > -d --debug show debugging statements > -v --verbose shows table when not absolutely necessary. > --db DATABASE specify database file to use [default: ./uwomeds68.db] > --tb TABLE specify table to use [default: matesTb] > """ > > from docopt import docopt > > cl_args = docopt(__doc__, version='testing v0.1') > print "Arguments in effect (from ):" > print(cl_args) > print "-------------------------------" > print > > I would have expected the defaults (./uwomeds68.db and matesTb) to be > populated but as it turns out, values are populated only of --db or --tb > are specified on the command line; otherwise, None is assigned to the > values keyed by "--db" and "--tb". > > Here are two example runs: > > alex at x301:~/Python/SQL/SQLite$ ./test show_data > Arguments in effect (from ): > {'--db': None, > '--tb': None, > '-d': False, > '-h': False, > '-v': False, > 'FILE': None, > 'new_data': False, > 'show_data': True, > 'text_entry': False} > ------------------------------- > > alex at x301:~/Python/SQL/SQLite$ ./test show_data --db=new.db > Arguments in effect (from ): > {'--db': 'new.db', > '--tb': None, > '-d': False, > '-h': False, > '-v': False, > 'FILE': None, > 'new_data': False, > 'show_data': True, > 'text_entry': False} > ------------------------------- > > My interpretation of the documentation is that the defaults are meant to > be picked up. Is that not correct? While I did not read the documentation I did try your code: (docopt)$ cat test #!/usr/bin/env python # -*- coding : utf -8 -*- # file: 'test' """Usage: test [new_data | text_entry FILE | show_data ] [-hdv] [--db=DATABASE] [--tb=TABLE] -h --help show this -d --debug show debugging statements -v --verbose shows table when not absolutely necessary. --db DATABASE specify database file to use [default: ./uwomeds68.db] --tb TABLE specify table to use [default: matesTb] """ from docopt import docopt cl_args = docopt(__doc__, version='testing v0.1') print "Arguments in effect (from ):" print(cl_args) print "-------------------------------" print (docopt)$ ./test show_data Arguments in effect (from ): {'--db': './uwomeds68.db', '--debug': False, '--help': False, '--tb': 'matesTb', '--verbose': False, 'FILE': None, 'new_data': False, 'show_data': True, 'text_entry': False} ------------------------------- So over here it works as you expected -- perhaps you need a newer version of docopt? I have (docopt)$ python -c 'import docopt; print docopt.__version__' 0.6.1 From chood1994 at hotmail.com Wed Oct 9 00:50:53 2013 From: chood1994 at hotmail.com (Connor Hood) Date: Tue, 8 Oct 2013 17:50:53 -0500 Subject: [Tutor] Writing Function Definitions Message-ID: Hi, I am taking a class in order to learn Python. One of the exercises I need to do is write function definitions. I cannot figure out how to do one of them. To show you an example here is a similar problem: If m is an integer, then isPrime(m) i? m is prime.The code: # Prompts the user for an integer m and then computes and prints whether# m is prime or not. # isPrime(m): I -> Bool# If m is an integer, then isPrime(m) if and only if m is prime.def isPrime(m): return False if m <= 1 else isPrimeItr(1,0,m) # isPrimeItr(i,a,m): I x I x I -> Booldef isPrimeItr(i,a,m): return False if a> 2 else True if a == 2 and i == m +1 else isPrimeItr(i+1,a+1,m) if m % i == 0 else isPrimeItr(i+1,a,m) # print a brief description of the program followed by an empty lineprint("Computing Prime Numbers")print("Prompts the user an integer value for m and then computes and")print("prints if m is prime or not.")print() # prompt the user for a value for mm = eval(input("Enter an integer value for m: ")) # print if m is primeprint("The value that", m, "is a prime integer is", isPrime(m)) ------------------------------------------------------------------------------------------------------------------------ These are the problems I am having problem with: If m and n are integers, then anyPrimes(m,n) i? there are any prime numbers in the interval [m,n). If m and n are integers, then countPrimes(m,n) is the number of prime numbers in the interval [m,n). If anyone could help that would be great. Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From chris at chrisdown.name Wed Oct 9 10:58:42 2013 From: chris at chrisdown.name (Chris Down) Date: Wed, 9 Oct 2013 16:58:42 +0800 Subject: [Tutor] Writing Function Definitions In-Reply-To: References: Message-ID: <20131009085841.GA1913@chrisdown.name> Hi Connor, On 2013-10-08 17:50, Connor Hood wrote: > Hi, I am taking a class in order to learn Python. One of the exercises I need to do is write function definitions. I cannot figure out how to do one of them. To show you an example here is a similar problem: > If m is an integer, then isPrime(m) i? m is prime.The code: > # Prompts the user for an integer m and then computes and prints whether# m is prime or not. > # isPrime(m): I -> Bool# If m is an integer, then isPrime(m) if and only if m is prime.def isPrime(m): return False if m <= 1 else isPrimeItr(1,0,m) > # isPrimeItr(i,a,m): I x I x I -> Booldef isPrimeItr(i,a,m): return False if a> 2 else True if a == 2 and i == m +1 else isPrimeItr(i+1,a+1,m) if m % i == 0 else isPrimeItr(i+1,a,m) > # print a brief description of the program followed by an empty lineprint("Computing Prime Numbers")print("Prompts the user an integer value for m and then computes and")print("prints if m is prime or not.")print() > # prompt the user for a value for mm = eval(input("Enter an integer value for m: ")) > # print if m is primeprint("The value that", m, "is a prime integer is", isPrime(m)) > ------------------------------------------------------------------------------------------------------------------------ > These are the problems I am having problem with: > If m and n are integers, then anyPrimes(m,n) i? there are any prime numbers in the interval [m,n). > If m and n are integers, then countPrimes(m,n) is the number of prime numbers in the interval [m,n). > If anyone could help that would be great. Thank you. Your code seems totally unreadable to me (all squashed on one line). Perhaps you should consider attaching it, instead. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 490 bytes Desc: not available URL: From alan.gauld at btinternet.com Wed Oct 9 11:06:22 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 09 Oct 2013 10:06:22 +0100 Subject: [Tutor] Writing Function Definitions In-Reply-To: References: Message-ID: On 08/10/13 23:50, Connor Hood wrote: > # isPrime(m): I -> Bool > # If m is an integer, then isPrime(m) if and only if m is prime. > def isPrime(m): > return False if m <= 1 else isPrimeItr(1,0,m) > > # isPrimeItr(i,a,m): I x I x I -> Bool > def isPrimeItr(i,a,m): > return False if a> 2 else True if a == 2 and i == m +1 else > isPrimeItr(i+1,a+1,m) if m % i == 0 else isPrimeItr(i+1,a,m) While the above looks like it is valid Python it is not very readable. I'd suggest splitting your functions into multiple lines rather than trying to cram everything into a single line. Also, because recursion runs into memory limits this solution will not always work for large numbers. I've tried to disentangle your single line above to show what I mean def isPrimeItr(i,a,m): if a > 2: return False elif a == 2 and i == m+1: return True elif m % i == 0: return isPrimeItr(i+1,a+1,m) else return isPrimeItr(i+1,a,m) It's subjective of course but I think that makes it easier to see the algorithm. I don't know if it works for testing primes but at least I could think about it if I had the time. For now I'll assume you've tested it and it works. > # prompt the user for a value for m > m = eval(input("Enter an integer value for m: ")) This is bad practice, it makes the program vulnerable to security exploits. Avoid the use of eval() for this type of task and instead use float()) or int() to convert the input from input(). ie. m = int(input(....)) Its always best to get into good habits early. > ------------------------------------------------------------------------------------------------------------------------ > > These are the problems I am having problem with: > > If m and n are integers, then anyPrimes(m,n) i? there are any prime > numbers in the interval [m,n). Do you understand loops? If so then you can test each number in the range using your isPrime() function above and stop if you find any primes. > If m and n are integers, then countPrimes(m,n) is the number of prime > numbers in the interval [m,n). Same here except you need to test all numbers and keep a running count. Try those suggestions and come back if you get stuck. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From davea at davea.name Wed Oct 9 13:28:16 2013 From: davea at davea.name (Dave Angel) Date: Wed, 9 Oct 2013 11:28:16 +0000 (UTC) Subject: [Tutor] Writing Function Definitions References: Message-ID: On 8/10/2013 18:50, Connor Hood wrote: > Hi, I am taking a class in order to learn Python. Welcome to Python, and to Python-tutor. > One of the exercises I need to do is write function definitions. I > cannot figure out how to do one of them. To show you an example here is a similar problem: > If m is an integer, then isPrime(m) i? m is prime.The code: > # Prompts the user for an integer m and then computes and prints whether# m is prime or not. > # isPrime(m): I -> Bool# If m is an integer, then isPrime(m) if and only if m is prime.def isPrime(m): return False if m <= 1 else isPrimeItr(1,0,m) > # isPrimeItr(i,a,m): I x I x I -> Booldef isPrimeItr(i,a,m): return False if a> 2 else True if a == 2 and i == m +1 else isPrimeItr(i+1,a+1,m) if m % i == 0 else isPrimeItr(i+1,a,m) > # print a brief description of the program followed by an empty lineprint("Computing Prime Numbers")print("Prompts the user an integer value for m and then computes and")print("prints if m is prime or not.")print() > # prompt the user for a value for mm = eval(input("Enter an integer value for m: ")) > # print if m is primeprint("The value that", m, "is a prime integer is", isPrime(m)) > ------------------------------------------------------------------------------------------------------------------------ > These are the problems I am having problem with: > If m and n are integers, then anyPrimes(m,n) i? there are any prime numbers in the interval [m,n). > If m and n are integers, then countPrimes(m,n) is the number of prime numbers in the interval [m,n). > If anyone could help that would be great. Thank you. > You've posted using html email, and the lines are squished together. it makes it quite hard to make sense out of your Python code. Please use text email in the future for posting here. Alan's suggestions pretty much cover mine. Make your code readable, rather than clever while you're learning. The two new functions you need can be written without recursion. And if you write countPrimes() first, it should be very easy to write anyPrimes(). Have you written any top-level code to test the existing functions? Or to test the ones you're about to write? Frequently wrting the test code makes it clearer how to write the actual code. Suggest you test first with literal numbers, so you can rerun those tests quickily, rather than always having to type in values to input statements. I'm curious, what is the intent of i, a, and m in the existing function isPrimeItr() ? BTW, Alan omitted a colon in his rewriting of the function. The last line needed a colon after the 'else'. -- DaveA From chris at chrisdown.name Wed Oct 9 13:35:09 2013 From: chris at chrisdown.name (Chris Down) Date: Wed, 9 Oct 2013 19:35:09 +0800 Subject: [Tutor] Writing Function Definitions In-Reply-To: References: Message-ID: <20131009113507.GB4383@chrisdown.name> On 2013-10-09 11:28, Dave Angel wrote: > Alan's suggestions pretty much cover mine. Make your code readable, > rather than clever while you're learning. s/while you're learning// -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 490 bytes Desc: not available URL: From davea at davea.name Wed Oct 9 14:14:16 2013 From: davea at davea.name (Dave Angel) Date: Wed, 9 Oct 2013 12:14:16 +0000 (UTC) Subject: [Tutor] Writing Function Definitions References: <20131009113507.GB4383@chrisdown.name> Message-ID: On 9/10/2013 07:35, Chris Down wrote: > On 2013-10-09 11:28, Dave Angel wrote: >> Alan's suggestions pretty much cover mine. Make your code readable, >> rather than clever while you're learning. > > s/while you're learning// > But by the time you learn enough, you realize that when you stop learning you stop breathing. Point taken. Readable trumps clever, at all stages of programming. -- DaveA From nsivaram.net at gmail.com Wed Oct 9 19:34:08 2013 From: nsivaram.net at gmail.com (Sivaram Neelakantan) Date: Wed, 09 Oct 2013 23:04:08 +0530 Subject: [Tutor] Processing CSV files References: Message-ID: <87y562z6un.fsf@gmail.com> On Wed, Oct 09 2013,Leena Gupta wrote: > Hello, > > Looking for some inputs on Python's csv processing feature. > > I need to process a large csv file every 5-10 minutes. The file could > contain 3mill to 10 mill rows and size could be 6MB to 10MB(+). As part of > the processing, I need to sum up a number value by grouping on certain > attributes and store the output in a datastore. I wanted to know if Python > is recommended and can it be used for processing data in csv files of this > size? Any issues that we need to be aware of? I believe Python has a csv > library as well. [snipped 6 lines] I've found pandas to be very useful for this. It provides good functions to read CSVs and higher order functions to sum the generated dataframes in pandas. sivaram -- From akleider at sonic.net Wed Oct 9 19:36:35 2013 From: akleider at sonic.net (Alex Kleider) Date: Wed, 09 Oct 2013 10:36:35 -0700 Subject: [Tutor] docopt module: defaults appear to be ignored In-Reply-To: References: <699eef205224370c65e709fc62e9692b@sonic.net> Message-ID: On 2013-10-08 22:35, Mark Lawrence wrote: > On 09/10/2013 01:50, Alex Kleider wrote: >> >> A recent post recommended the docopt module so I've incorporated it >> into >> the code I'm using to learn SQLite. It's not behaving as I expected. >> Here's a snippet of code: >> >> #!/usr/bin/env python >> # -*- coding : utf -8 -*- >> # file: 'test' >> """Usage: test [new_data | text_entry FILE | show_data ] [-hdv] >> [--db=DATABASE] [--tb=TABLE] >> >> -h --help show this >> -d --debug show debugging statements >> -v --verbose shows table when not absolutely necessary. >> --db DATABASE specify database file to use [default: ./uwomeds68.db] >> --tb TABLE specify table to use [default: matesTb] >> """ >> > > You have no definitions for new_data, text_entry, FILE and show_data, > and the use of the square brackets around them looks wrong. What I believe I'm specifying here is that these are mutually exclusive commands, one of which must be entered. This part is behaving properly. > If you haven't already looked at them there are lots of extremely > useful examples here > https://github.com/docopt/docopt/tree/master/examples. Thanks, yes, I've been looking there. What I haven't been able to create is an example of my own where a default value is specified in the Usage pattern and gets propogated into the dictionary created by docopt. I haven't yet given up. From paulrsmith7777 at gmail.com Thu Oct 10 23:28:26 2013 From: paulrsmith7777 at gmail.com (Paul Smith) Date: Thu, 10 Oct 2013 17:28:26 -0400 Subject: [Tutor] Protecting username - password items in python3.3 Message-ID: Ok experts I need to protect username and password items in some Python3.3 code I am writing. Let me clarify, I don't care here about protecting the program itself i.e. using else: main() to work around my username password input, I simply don't want to reveal username and password info. I see md5, hashlib etc. but my program will be up against some BIG CORPS and I need to make it as painful a process possible for someone to get username(typically email) and password information from my program. I am considering using subprocess to achieve this if necessary. Thanks in advance! Paul Smith -------------- next part -------------- An HTML attachment was scrubbed... URL: From oscar.j.benjamin at gmail.com Thu Oct 10 23:49:37 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Thu, 10 Oct 2013 22:49:37 +0100 Subject: [Tutor] Protecting username - password items in python3.3 In-Reply-To: References: Message-ID: On 10 October 2013 22:28, Paul Smith wrote: > Ok experts I need to protect username and password items in some Python3.3 > code I am writing. I'm not an expert on this subject but... > Let me clarify, I don't care here about protecting the program itself i.e. > using > > else: > main() > > to work around my username password input, I simply don't want to reveal > username and password info. I have no idea what the above means. > I see md5, hashlib etc. but my program will be up against some BIG CORPS and > I need to make it as painful a process possible for someone to get > username(typically email) and password information from my program. What do you mean by "BIG CORPS"? Is someone out to get you? > I am considering using subprocess to achieve this if necessary. I still don't really understand what you mean. The easiest way to protect your program from leaking passwords is just to not store any passwords. Presumably you also want to store them in some form in order to do something useful though? Do you want to store the passwords so that they can be recovered? Or just so they can be checked against to see if a password entered later matches? Are you also trying to hide some other data from the "BIG CORPS". Perhaps if you could show a small demo script that does approximately what you're thinking but indicating the parts currently missing I might understand what you mean. Oscar From paulrsmith7777 at gmail.com Fri Oct 11 01:30:30 2013 From: paulrsmith7777 at gmail.com (Paul Smith) Date: Thu, 10 Oct 2013 19:30:30 -0400 Subject: [Tutor] Protecting username - password items in python3.3 In-Reply-To: References: Message-ID: I am automating my email login to yahoo... I run my python script injecting username and password into the login fields... I run my own filters grab only the information I want... Not a new concept just a new twist I am working on... I need to keep the username and password info in my python code hashed or encrypted somehow without referencing an outside source or file. I don't care about the program being locked down, we intend on githubbing it eventually, I just need the ability to protect any username or password items written in the code. Is this possible? No one is out to get us or else they would already have us, lol. Ideas have consequences and though not nefarious it could be easily uglified um just think automated function married to a password cracker. I just know that I want to protect any and all information like real email addresses or passwords folks may use with our script. -Paul On Thu, Oct 10, 2013 at 5:49 PM, Oscar Benjamin wrote: > On 10 October 2013 22:28, Paul Smith wrote: > > Ok experts I need to protect username and password items in some > Python3.3 > > code I am writing. > > I'm not an expert on this subject but... > > > Let me clarify, I don't care here about protecting the program itself > i.e. > > using > > > > else: > > main() > > > > to work around my username password input, I simply don't want to reveal > > username and password info. > > I have no idea what the above means. > > > I see md5, hashlib etc. but my program will be up against some BIG CORPS > and > > I need to make it as painful a process possible for someone to get > > username(typically email) and password information from my program. > > What do you mean by "BIG CORPS"? Is someone out to get you? > > > I am considering using subprocess to achieve this if necessary. > > I still don't really understand what you mean. The easiest way to > protect your program from leaking passwords is just to not store any > passwords. Presumably you also want to store them in some form in > order to do something useful though? > > Do you want to store the passwords so that they can be recovered? Or > just so they can be checked against to see if a password entered later > matches? Are you also trying to hide some other data from the "BIG > CORPS". Perhaps if you could show a small demo script that does > approximately what you're thinking but indicating the parts currently > missing I might understand what you mean. > > > Oscar > -------------- next part -------------- An HTML attachment was scrubbed... URL: From akleider at sonic.net Fri Oct 11 03:24:59 2013 From: akleider at sonic.net (Alex Kleider) Date: Thu, 10 Oct 2013 18:24:59 -0700 Subject: [Tutor] docopt module: defaults appear to be ignored In-Reply-To: References: <699eef205224370c65e709fc62e9692b@sonic.net> Message-ID: <053c6e2c93bdf181700d28f1bf14ab24@sonic.net> On 2013-10-09 00:29, Peter Otten wrote: > While I did not read the documentation I did try your code: > > (docopt)$ cat test > #!/usr/bin/env python > # -*- coding : utf -8 -*- > # file: 'test' > """Usage: test [new_data | text_entry FILE | show_data ] [-hdv] > [--db=DATABASE] [--tb=TABLE] > > -h --help show this > -d --debug show debugging statements > -v --verbose shows table when not absolutely necessary. > --db DATABASE specify database file to use [default: ./uwomeds68.db] > --tb TABLE specify table to use [default: matesTb] > """ > > from docopt import docopt > > cl_args = docopt(__doc__, version='testing v0.1') > print "Arguments in effect (from ):" > print(cl_args) > print "-------------------------------" > print > (docopt)$ ./test show_data > Arguments in effect (from ): > {'--db': './uwomeds68.db', > '--debug': False, > '--help': False, > '--tb': 'matesTb', > '--verbose': False, > 'FILE': None, > 'new_data': False, > 'show_data': True, > 'text_entry': False} > ------------------------------- > > So over here it works as you expected -- perhaps you need a newer > version of > docopt? I have > > (docopt)$ python -c 'import docopt; print docopt.__version__' > 0.6.1 > Can you tell me please on which system you ran this? I am running Linux (Ubuntu12.04) and a friend who also runs Linux (I've yet to find out which flavour) got the same result as did I, so I am beginning to think it might be OS dependent. thks. alex From davea at davea.name Fri Oct 11 04:22:19 2013 From: davea at davea.name (Dave Angel) Date: Fri, 11 Oct 2013 02:22:19 +0000 (UTC) Subject: [Tutor] Protecting username - password items in python3.3 References: Message-ID: On 10/10/2013 19:30, Paul Smith wrote: > > >
I am automating my email login to yahoo... I run my python script injecting username and password into the login fields... I run my own filters grab only the information I want... Not a new concept just a new twist I am working on... I need to keep the username and password info in my python code hashed or encrypted somehow without referencing an outside source or file. I don't care about the program being locked down, we intend on githubbing it eventually, I just need the ability to protect any username or password items written in the code. Is this possible??
>
No one is out to get us or else they would already have us, lol. Ideas have consequences and though not nefarious it could be easily uglified um just think automated function married to a password cracker. I just know that I want to protect any and all information like real email addresses or passwords folks may use with our script.?
>

-Paul


On Thu, Oct 10, 2013 at 5:49 PM, Oscar Benjamin <oscar.j.benjamin at gmail.com> wrote:
>
On 10 October 2013 22:28, Paul Smith <paulrsmith7777 at gmail.com> wrote:
> Lots of words, not much clarity. You're writing a script, and you'll allow anybody to read the script. But you don't want them to be able to analyze the script to see what name and password are being used. How about you encode it as the first letter of each token, and hope they don't notice? Or maybe pig latin. If the data is in the text file, and "they" can examine, modify and run the text file, the data is totally insecure. So just don't show them the script, and don't let them run it, and don't run it yourself unless you're in a dark closet with no wires leaving the room. What you seem to want could be cracked in half an hour if you do it in Python. And in a day if you do it in C. -- DaveA From aurelien at xload.io Fri Oct 11 08:02:53 2013 From: aurelien at xload.io (=?utf-8?Q?Aur=C3=A9lien_DESBRI=C3=88RES?=) Date: Fri, 11 Oct 2013 08:02:53 +0200 Subject: [Tutor] Protecting username - password items in python3.3 In-Reply-To: (Paul Smith's message of "Thu, 10 Oct 2013 19:30:30 -0400") References: Message-ID: <87zjqgtkdu.fsf@unicorn.home> Paul Smith writes: > On Thu, Oct 10, 2013 at 5:49 PM, Oscar Benjamin > wrote: > > On 10 October 2013 22:28, Paul Smith > wrote: > > Ok experts I need to protect username and password items in some > Python3.3 > > code I am writing. > > > I'm not an expert on this subject but... > > > > Let me clarify, I don't care here about protecting the program > itself i.e. > > using > > > > else: > > main() > > > > to work around my username password input, I simply don't want > to reveal > > username and password info. > > > I have no idea what the above means. > > > > I see md5, hashlib etc. but my program will be up against some > BIG CORPS and > > I need to make it as painful a process possible for someone to > get > > username(typically email) and password information from my > program. > > > What do you mean by "BIG CORPS"? Is someone out to get you? > > > > I am considering using subprocess to achieve this if necessary. > > > I still don't really understand what you mean. The easiest way to > protect your program from leaking passwords is just to not store > any > passwords. Presumably you also want to store them in some form in > order to do something useful though? > > Do you want to store the passwords so that they can be recovered? > Or > just so they can be checked against to see if a password entered > later > matches? Are you also trying to hide some other data from the "BIG > CORPS". Perhaps if you could show a small demo script that does > approximately what you're thinking but indicating the parts > currently > missing I might understand what you mean. > > > Oscar > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > I am automating my email login to yahoo... I run my python script > injecting username and password into the login fields... I run my own > filters grab only the information I want... Not a new concept just a > new twist I am working on... I need to keep the username and password > info in my python code hashed or encrypted somehow without referencing > an outside source or file. I don't care about the program being locked > down, we intend on githubbing it eventually, I just need the ability > to protect any username or password items written in the code. Is this > possible? > > No one is out to get us or else they would already have us, lol. Ideas > have consequences and though not nefarious it could be easily uglified > um just think automated function married to a password cracker. I just > know that I want to protect any and all information like real email > addresses or passwords folks may use with our script. > > -Paul > Hi, Since this place is [Tutor] I think it's fine to explain that on mail list you write your answer below. Thanks Paul. -- Aur?lien DESBRI?RES Run Free - Run GNU.org From __peter__ at web.de Fri Oct 11 09:55:55 2013 From: __peter__ at web.de (Peter Otten) Date: Fri, 11 Oct 2013 09:55:55 +0200 Subject: [Tutor] docopt module: defaults appear to be ignored References: <699eef205224370c65e709fc62e9692b@sonic.net> <053c6e2c93bdf181700d28f1bf14ab24@sonic.net> Message-ID: Alex Kleider wrote: > On 2013-10-09 00:29, Peter Otten wrote: >> While I did not read the documentation I did try your code: >> >> (docopt)$ cat test >> #!/usr/bin/env python >> # -*- coding : utf -8 -*- >> # file: 'test' >> """Usage: test [new_data | text_entry FILE | show_data ] [-hdv] >> [--db=DATABASE] [--tb=TABLE] >> >> -h --help show this >> -d --debug show debugging statements >> -v --verbose shows table when not absolutely necessary. >> --db DATABASE specify database file to use [default: ./uwomeds68.db] >> --tb TABLE specify table to use [default: matesTb] >> """ >> >> from docopt import docopt >> >> cl_args = docopt(__doc__, version='testing v0.1') >> print "Arguments in effect (from ):" >> print(cl_args) >> print "-------------------------------" >> print >> (docopt)$ ./test show_data >> Arguments in effect (from ): >> {'--db': './uwomeds68.db', >> '--debug': False, >> '--help': False, >> '--tb': 'matesTb', >> '--verbose': False, >> 'FILE': None, >> 'new_data': False, >> 'show_data': True, >> 'text_entry': False} >> ------------------------------- >> >> So over here it works as you expected -- perhaps you need a newer >> version of >> docopt? I have >> >> (docopt)$ python -c 'import docopt; print docopt.__version__' >> 0.6.1 >> > > > Can you tell me please on which system you ran this? > I am running Linux (Ubuntu12.04) and a friend who also runs Linux (I've > yet to find out which flavour) got the same result as did I, so I am > beginning to think it might be OS dependent. > thks. Uh, still struggling with that ;) I'm using Linux Mint, but I think I've found a more promising cause: $ python -c 'import docopt; print docopt.docopt("Usage: foo [-- bar=BAR]\n\n--bar BAR\twhatever [default: 42]")' {'--bar': None} $ python -c 'import docopt; print docopt.docopt("Usage: foo [-- bar=BAR]\n\n--bar BAR whatever [default: 42]")' {'--bar': '42'} Did you spot the difference? When "--bar BAR" is separated from "whatever" by a TAB the default is not honoured, you need two or more spaces. You probably have TABs in your source which were replaced by spaces in the email... From jackiexxduh at yahoo.com Fri Oct 11 07:18:27 2013 From: jackiexxduh at yahoo.com (Jackie Canales) Date: Thu, 10 Oct 2013 22:18:27 -0700 (PDT) Subject: [Tutor] Looking for Words - Help Message-ID: <1381468707.8479.YahooMailNeo@web121702.mail.ne1.yahoo.com> Need assistance with a questions in regards to python: 1.?function occurs(name, word) which looks for a word in the file with name name. 2.?for each occurrence of the word we want to display its context by showing the 5 words (or so) preceding and following the occurrence, e.g. '... a man to set the river on fire. He had ...' for the first occurrence of 'river' in 'innocents.txt'. 3. since the results may be long, we want to collect them all, and write them to a file whose name should be 'occurs'+name. Hint: at first ignore writing the results to a file. Simply collect all material in a string which you print to the screen. Then writing it to a file will be simple. To get both the word and its context you need an indexed loop through the words. Use the stripw() function we saw on individual words to make finding hits more accurate (e.g. the program found 'river.' above). Finally, the join() method will come in handy to reconstruct the context as a string. Link to final product:?http://imgur.com/q1aAAhp For my program this is what i have so far, I am kinda lost at this point if you can please guide me to help resolve this program. def lines(name, word): ? ? 'print all lines of name in which word occurs' ? ? infile = open(name, 'r') ? ? lst = infile.readlines() ? ? infile.close() ? ? for i in range(len(lst)): ? ? ? ? line = lst[i] ? ? ? ? if wordin(word, line): ? ? ? ? ? ? w = ('Word found in line {}:'.format(i)) ? ? ? ? ? ? #x = (lst[i+1]) ? ? ? ? ? ? y = lst[i]? ? ? ?? ? ? ? ? ? ? ? ? ? ? ? ? ? print (''.join(y)) -------------- next part -------------- An HTML attachment was scrubbed... URL: From vaddesreenivasulu at gmail.com Thu Oct 10 12:34:58 2013 From: vaddesreenivasulu at gmail.com (Sreenivasulu) Date: Thu, 10 Oct 2013 16:04:58 +0530 Subject: [Tutor] ImportError: 'DLL load failed: %1 is not a valid Win32 application.' Message-ID: Hi, I have windows 8 64 bit machine and installed python 2.7.3 64 bit version . i have 32 bit package 4Suite-XML-1.0.24Suite-XML-1.0.2.win32.exe package but am getting below error : Python 2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from Ft.Xml.Lib.XmlString import SplitQName ImportError: 'DLL load failed: %1 is not a valid Win32 application.' Please help me how to run win32 modules in 64 bit . Thanks & Regards, SReeni. -------------- next part -------------- An HTML attachment was scrubbed... URL: From chris at chrisdown.name Fri Oct 11 12:06:56 2013 From: chris at chrisdown.name (Chris Down) Date: Fri, 11 Oct 2013 18:06:56 +0800 Subject: [Tutor] ImportError: 'DLL load failed: %1 is not a valid Win32 application.' In-Reply-To: References: Message-ID: <20131011100655.GA17178@chrisdown.name> On 2013-10-10 16:04, Sreenivasulu wrote: > ImportError: 'DLL load failed: %1 is not a valid Win32 application.' > > Please help me how to run win32 modules in 64 bit . If I'm reading that correctly, that's not an error about running a 32-bit application in a 64-bit environment, but an error about it not being a valid 32-bit application in the first place... I have no idea what I'm talking about when it comes to Windows though, so who knows. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 490 bytes Desc: not available URL: From davea at davea.name Fri Oct 11 12:23:00 2013 From: davea at davea.name (Dave Angel) Date: Fri, 11 Oct 2013 10:23:00 +0000 (UTC) Subject: [Tutor] Looking for Words - Help References: <1381468707.8479.YahooMailNeo@web121702.mail.ne1.yahoo.com> Message-ID: On 11/10/2013 01:18, Jackie Canales wrote: > Need assistance with a questions in regards to python: > 1.?function occurs(name, word) which looks for a word in the file with name name. > 2.?for each occurrence of the word we want to display its context by showing the 5 words (or so) preceding and following the occurrence, e.g. '... a man to set the river on fire. He had ...' for the first occurrence of 'river' in 'innocents.txt'. > 3. since the results may be long, we want to collect them all, and write them to a file whose name should be 'occurs'+name. > > Hint: at first ignore writing the results to a file. Simply collect all material in a string which you print to the screen. Then writing it to a file will be simple. To get both the word and its context you need an indexed loop through the words. Use the stripw() function we saw on individual words to make finding hits more accurate (e.g. the program found 'river.' above). Finally, the join() method will come in handy to reconstruct the context as a string. > > > Link to final product:?http://imgur.com/q1aAAhp > > For my program this is what i have so far, I am kinda lost at this point if you can please guide me to help resolve this program. > > def lines(name, word): > ? ? 'print all lines of name in which word occurs' > > ? ? infile = open(name, 'r') > ? ? lst = infile.readlines() > ? ? infile.close() > > ? ? for i in range(len(lst)): > ? ? ? ? line = lst[i] > ? ? ? ? if wordin(word, line): > ? ? ? ? ? ? w = ('Word found in line {}:'.format(i)) > ? ? ? ? ? ? #x = (lst[i+1]) > ? ? ? ? ? ? y = lst[i]? ? ? ?? > ? ? ? ? ? ? ? > ? ? ? ? ? ? print (''.join(y)) > >
Need assistance with a questions in regards to python:
1. function occurs(name, word) which looks for a word in the file with name name.
2. for each occurrence of the word we want to display its context by showing the 5 words (or so) preceding and following the occurrence, e.g. '... a man to set the river > on fire. He had ...' for the first occurrence of 'river' in 'innocents.txt'.
3. since the results may be long, we want to collect them all, and write them to a file whose name should be 'occurs'+name.

Hint: at first ignore writing the results to a file. Simply collect all material in a string which you print to the screen. Then writing it to a file will be simple. To get both the word and its context you need an > indexed loop through the words. Use the stripw() function we saw on individual words to make finding hits more accurate (e.g. the program found 'river.' above). Finally, the join() method will come in handy to reconstruct the context as a string.

Link to final product: http://imgur.com/q1aAAhp

For my program this is what i have so far, I am kinda lost at this point if you can please guide me to help resolve this program.

def lines(name, word):
    'print all lines of name in which word occurs'

style="background-color: transparent;">    infile = open(name, 'r')
    lst = infile.readlines()
    infile.close()

    for i in range(len(lst)):
        line = lst[i]
        if wordin(word, line):
style="background-color: transparent;">            w = ('Word found in line {}:'.format(i))
            #x = (lst[i+1])
            y = lst[i]        
             
            print (''.join(y))
> This is a text mailing list. Please post as text message, not html. (That's an option in your email program.) That's a lot of mess to wade through. And in many email programs, the text portion of an html message will not quite match the html portion, so we see something somewhat different than what you typed. Your phrase "kinda lost" doesn't narrow it down much. When you run this code, what happens? By inspection, the first problem I see is that you don't actually call the function. You need a call to lines() at your top-level, supplying some filename and word name. Second problem I spot is the call to wordin(), which isn't included. Third problem is that you're calling join() method and passing it a string rather than a list. That's legal, but it doesn't do what you think. And once you find a list to pass it, I think you'll find that the "" string for its object wants to be " " instead. Fourth is that the function isn't called occurs(), and doesn't do what the assignment says. Which part are you stumped at, or are you getting a syntax error or something else that I'm not guessing. -- DaveA From wprins at gmail.com Fri Oct 11 12:25:36 2013 From: wprins at gmail.com (Walter Prins) Date: Fri, 11 Oct 2013 11:25:36 +0100 Subject: [Tutor] ImportError: 'DLL load failed: %1 is not a valid Win32 application.' In-Reply-To: References: Message-ID: Hi, On 10 October 2013 11:34, Sreenivasulu wrote: > Hi, > > I have windows 8 64 bit machine and installed python 2.7.3 64 bit > version . > > i have 32 bit package 4Suite-XML-1.0.24Suite-XML-1.0.2.win32.exe package > but am getting below error : > > Python 2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)] > on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> from Ft.Xml.Lib.XmlString import SplitQName > > ImportError: 'DLL load failed: %1 is not a valid Win32 application.' > > Please help me how to run win32 modules in 64 bit . > You can't use 32 bit Python modules with 64-bit Python. Either install 32-bit python and use the 32-bit Python module with 32-bit Python (probably the simplest solution for you for now), or alternatively find (or compile/build yourself -- very non-trivial) a 64-bit build of the module you're wanting to use and install that instead of the 32-bit version. Often http://www.lfd.uci.edu/~gohlke/pythonlibs/ will have unofficial 64-bit versions of many common 32-bit Python modules, but unfortunately this particular package is not listed there. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Fri Oct 11 12:25:48 2013 From: __peter__ at web.de (Peter Otten) Date: Fri, 11 Oct 2013 12:25:48 +0200 Subject: [Tutor] Looking for Words - Help References: <1381468707.8479.YahooMailNeo@web121702.mail.ne1.yahoo.com> Message-ID: Jackie Canales wrote: > Need assistance with a questions in regards to python: > 1. function occurs(name, word) which looks for a word in the file with > name name. 2. for each occurrence of the word we want to display its > context by showing the 5 words (or so) preceding and following the > occurrence, e.g. '... a man to set the river on fire. He had ...' for the > first occurrence of 'river' in 'innocents.txt'. 3. since the results may > be long, we want to collect them all, and write them to a file whose name > should be 'occurs'+name. > > Hint: at first ignore writing the results to a file. Simply collect all > material in a string which you print to the screen. Then writing it to a > file will be simple. To get both the word and its context you need an > indexed loop through the words. Use the stripw() function we saw on > individual words to make finding hits more accurate (e.g. the program > found 'river.' above). Finally, the join() method will come in handy to > reconstruct the context as a string. > > > Link to final product: http://imgur.com/q1aAAhp > > For my program this is what i have so far, I am kinda lost at this point > if you can please guide me to help resolve this program. > def lines(name, word): > 'print all lines of name in which word occurs' > > infile = open(name, 'r') > lst = infile.readlines() You need the words, not the lines, so it is simpler if you read the complete file as a string. Next, look for a method to split the string into words and apply that. Once you have the list of words you can iterate over that and the index using for index, word_from_text in enumerate(words): ... Check if word_from_text matches word, and if it does use slicing to get a list of words that surround it: context = words[index-5:index+5] Come back if you run into problems you can't solve yourself. > infile.close() > > for i in range(len(lst)): > line = lst[i] > if wordin(word, line): > w = ('Word found in line {}:'.format(i)) > #x = (lst[i+1]) > y = lst[i] > > print (''.join(y)) > From breamoreboy at yahoo.co.uk Fri Oct 11 15:02:46 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 11 Oct 2013 14:02:46 +0100 Subject: [Tutor] Looking for Words - Help In-Reply-To: <1381468707.8479.YahooMailNeo@web121702.mail.ne1.yahoo.com> References: <1381468707.8479.YahooMailNeo@web121702.mail.ne1.yahoo.com> Message-ID: On 11/10/2013 06:18, Jackie Canales wrote: > > for i in range(len(lst)): > line = lst[i] Sound advice already from Dave and Peter so I'll just point out for the benefit of newbies that you don't write Python for loops like this, it's. for line in lst: etc Please see http://docs.python.org/3/tutorial/controlflow.html#index-0 -- Roses are red, Violets are blue, Most poems rhyme, But this one doesn't. Mark Lawrence From alan.gauld at btinternet.com Fri Oct 11 15:23:11 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 11 Oct 2013 14:23:11 +0100 Subject: [Tutor] Looking for Words - Help In-Reply-To: <1381468707.8479.YahooMailNeo@web121702.mail.ne1.yahoo.com> References: <1381468707.8479.YahooMailNeo@web121702.mail.ne1.yahoo.com> Message-ID: On 11/10/13 06:18, Jackie Canales wrote: > Need assistance with a questions in regards to python: > 1.function occurs(name, word) which looks for a word in the file with > name name. That means you need to define a function called occurs() not lines(). > 2. for each occurrence of the word we want to display its context by > showing the 5 words (or so) preceding and following the occurrence, e.g. > '... a man to set the river on fire. He had ...' for the first > occurrence of 'river' in 'innocents.txt'. OK, so far > 3. since the results may be long, we want to collect them all, and write > them to a file whose name should be 'occurs'+name. > > /Hint/: at first ignore writing the results to a file. That's a good hint so lets just do that. In fact writing to a file in the occurs function is probably a bad idea anyway! But that's another debate altogether. > to a file will be simple. To get both the word and its context you need > an indexed loop through the words. That's only partly true. although you need both index and word you don;t need to loop on the index. You can use the enumerate() function to get both in a single hit. > Use the stripw() function we saw on individual words to make > finding hits more accurate No idea what that means but since the assignment suggests it we should assume its correct. > For my program this is what i have so far, I am kinda lost at this point > if you can please guide me to help resolve this program. You have several bad habits in here... > def lines(name, word): > 'print all lines of name in which word occurs' > > infile = open(name, 'r') > lst = infile.readlines() > infile.close() You could do that in one line: lst = open(name).readlines() Although if you want context to stretch over line breaks you would be better using read() to get the whole file as a single string. > for i in range(len(lst)): > line = lst[i] This is where enumerate gives you a better solution: for index, line in enumerate(lst): > if wordin(word, line): I assume round about now is where you were supposed to use the stripw() function mentioned in the hint? You haven't got the location of the word to work out the context. So really you need to split the line into words and then see if your word is in there. You can then get the location either by using enumerate() and a loop or using the index() list operation. > w = ('Word found in line {}:'.format(i)) You don't need the parens here and I don't think the colon on the end makes much sense either > y = lst[i] > print (''.join(y)) y is just the original input line so is not needed you can just passs lst[i]) to join().. But joining it with an empty string doesn't do much. >>> ''.join('abcde') 'abcde' In summary I'd go for reading the whole file as a string then use your splitw() function to extract the words (assuming that's what it does?) Then use enumerate() to loop over the list of words to find the words and its index. Then use list slicing to get the 5 words before and after the found word. Finally join them together to form a string and append that string to a result list that you can return. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From __peter__ at web.de Fri Oct 11 16:23:37 2013 From: __peter__ at web.de (Peter Otten) Date: Fri, 11 Oct 2013 16:23:37 +0200 Subject: [Tutor] Looking for Words - Help References: <1381468707.8479.YahooMailNeo@web121702.mail.ne1.yahoo.com> Message-ID: Alan Gauld wrote: >> Use the stripw() function we saw on individual words to make >> finding hits more accurate > > No idea what that means but since the assignment suggests > it we should assume its correct. My crystal ball says def stripw(word): return word.strip('",.') or somesuch. > You have several bad habits in here... > > > def lines(name, word): > > 'print all lines of name in which word occurs' > > > > infile = open(name, 'r') > > lst = infile.readlines() > > infile.close() > > You could do that in one line: > > lst = open(name).readlines() Talking about bad habits -- what you are suggesting here is a step in the wrong direction. If at this point in the OP's Python career you bother about how to open and close a file at all you should recommend the safe variant with open(name) as infile: lines = infile.readlines() rather than the version for, err, us lazy old bastards ;) From breamoreboy at yahoo.co.uk Fri Oct 11 16:40:33 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 11 Oct 2013 15:40:33 +0100 Subject: [Tutor] Looking for Words - Help In-Reply-To: References: <1381468707.8479.YahooMailNeo@web121702.mail.ne1.yahoo.com> Message-ID: On 11/10/2013 15:23, Peter Otten wrote: > Alan Gauld wrote: > >>> Use the stripw() function we saw on individual words to make >>> finding hits more accurate >> >> No idea what that means but since the assignment suggests >> it we should assume its correct. > > My crystal ball says > > def stripw(word): > return word.strip('",.') > > or somesuch. > >> You have several bad habits in here... >> >>> def lines(name, word): >>> 'print all lines of name in which word occurs' >>> >>> infile = open(name, 'r') >>> lst = infile.readlines() >>> infile.close() >> >> You could do that in one line: >> >> lst = open(name).readlines() > > Talking about bad habits -- what you are suggesting here is a step in the > wrong direction. > > If at this point in the OP's Python career you bother about how to open and > close a file at all you should recommend the safe variant > > with open(name) as infile: > lines = infile.readlines() > > rather than the version for, err, us lazy old bastards ;) > Why bother building a list when the modern idiom is simply for line in infile: ? -- Roses are red, Violets are blue, Most poems rhyme, But this one doesn't. Mark Lawrence From __peter__ at web.de Fri Oct 11 17:23:22 2013 From: __peter__ at web.de (Peter Otten) Date: Fri, 11 Oct 2013 17:23:22 +0200 Subject: [Tutor] Looking for Words - Help References: <1381468707.8479.YahooMailNeo@web121702.mail.ne1.yahoo.com> Message-ID: Mark Lawrence wrote: > On 11/10/2013 15:23, Peter Otten wrote: >> Alan Gauld wrote: >> >>>> Use the stripw() function we saw on individual words to make >>>> finding hits more accurate >>> >>> No idea what that means but since the assignment suggests >>> it we should assume its correct. >> >> My crystal ball says >> >> def stripw(word): >> return word.strip('",.') >> >> or somesuch. >> >>> You have several bad habits in here... >>> >>>> def lines(name, word): >>>> 'print all lines of name in which word occurs' >>>> >>>> infile = open(name, 'r') >>>> lst = infile.readlines() >>>> infile.close() >>> >>> You could do that in one line: >>> >>> lst = open(name).readlines() >> >> Talking about bad habits -- what you are suggesting here is a step in the >> wrong direction. >> >> If at this point in the OP's Python career you bother about how to open >> and close a file at all you should recommend the safe variant >> >> with open(name) as infile: >> lines = infile.readlines() >> >> rather than the version for, err, us lazy old bastards ;) >> > > Why bother building a list when the modern idiom is simply > > for line in infile: ? Without context the question would rather be "When should you build a list of lines from a file?" and the right answer is "Hardly ever" while the pragmatic answer is "It doesn't matter unless your file is 'big'". As to the with open(name) as infile: for line in infile.readlines(): # wrong! use 'for line in infile: ... ... idiom the only way to get rid of that is to remove the readlines() method. See also http://bugs.python.org/issue13510 To bring this back on topic, I recommended a list of words because that is easier to handle for a newbie than a generator, but if you (reader, not Mark) are an intermediate Python user and know about generators you can try to implement a generator like def context(items, is_match, nbefore=1, nafter=1): """ >>> list(context([-1, 2, 3, -1, 4, -1], lambda item: item < 0)) [[-1, 2], [3, -1, 4], [4, -1]] """ that stores only nbefore + nafter + 1 items. From alan.gauld at btinternet.com Fri Oct 11 22:40:18 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 11 Oct 2013 21:40:18 +0100 Subject: [Tutor] Looking for Words - Help In-Reply-To: References: <1381468707.8479.YahooMailNeo@web121702.mail.ne1.yahoo.com> Message-ID: On 11/10/13 16:23, Peter Otten wrote: >>>>> infile = open(name, 'r') >>>>> lst = infile.readlines() >>>>> infile.close() >>>> >>>> You could do that in one line: >>>> >>>> lst = open(name).readlines() >>> >>> Talking about bad habits -- what you are suggesting here is a step in the >>> wrong direction. >>> >>> with open(name) as infile: >>> lines = infile.readlines() Good point, I should have used with. (Slaps self on face with wet fish!) >> for line in infile: ? I actually considered this but decided it was one step too far for the OP. > an intermediate Python user and know about generators you can try > to implement a generator like I also considered a generator but decided that was way too much for the OP! :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From juanscopp at gmail.com Fri Oct 11 17:09:29 2013 From: juanscopp at gmail.com (Juan I. Scopp) Date: Fri, 11 Oct 2013 12:09:29 -0300 Subject: [Tutor] Consolidate several lines of a CSV file with firewall rules Message-ID: Hi guys. I have a CSV file, which I created using an HTML export from a Check Point firewall policy. Each rule is represented as several lines, in some cases. That occurs when a rule has several address sources, destinations or services. I need the output to have each rule described in only one line. It's easy to distinguish when each rule begins. In the first column, there's the rule ID, which is a number. Let me show you an example: NO.;NAME;SOURCE;DESTINATION;VPN  ;SERVICE;ACTION;TRACK;INSTALL ON;TIME;COMMENT 1;;fwxcluster;mcast_vrrp;;vrrp;accept;Log;fwxcluster;Any;"VRRP;;*Comment suppressed* ;;;;;igmp**;;;;; 2;;fwxcluster;fwxcluster;;FireWall;accept;Log;fwxcluster;Any;"Management FWg;*Comment suppressed* ;;fwmgmpe**;fwmgmpe**;;ssh**;;;;; ;;fwmgm**;fwmgm**;;;;;;; 3;NTP;G_NTP_Clients;cmm_ntpserver_pe01;;ntp;accept;None;fwxcluster;Any;*Comment suppressed* ;;;cmm_ntpserver_pe02**;;;;;;; What I need ,explained in pseudo code, is this: Read the first column of the next line. If there's a number: Evaluate the first column of the next line. If there's no number there, concatenate (separating with a comma) \ the strings in the columns of this line with the last one and eliminate the text in the current one The output should be something like this: NO.;NAME;SOURCE;DESTINATION;VPN  ;SERVICE;ACTION;TRACK;INSTALL ON;TIME;COMMENT 1;;fwxcluster,fwmgmpe**,fwmgm**;mcast_vrrp,fwmgmpe**,fwmgm**;;vrrp,ssh**;accept;Log;fwxcluster;Any;*Comment suppressed* ;;;;;;;;;; ;;;;;;;;;; 3;NTP;G_NTP_Clients;cmm_ntpserver_pe01,cmm_ntpserver_pe02**;;ntp;accept;None;fwxcluster;Any;*Comment suppressed* ;;;;;;;;;; The empty lines are there only to be more clear, I don't actually need them. Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Sat Oct 12 01:14:15 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 12 Oct 2013 00:14:15 +0100 Subject: [Tutor] Consolidate several lines of a CSV file with firewall rules In-Reply-To: References: Message-ID: On 11/10/2013 16:09, Juan I. Scopp wrote: > Hi guys. > I have a CSV file, which I created using an HTML export from a Check > Point firewall policy. > Each rule is represented as several lines, in some cases. That occurs > when a rule has several address sources, destinations or services. > I need the output to have each rule described in only one line. > It's easy to distinguish when each rule begins. In the first column, > there's the rule ID, which is a number. > > Let me show you an example: > > NO.;NAME;SOURCE;DESTINATION;VPN  ;SERVICE;ACTION;TRACK;INSTALL > ON;TIME;COMMENT > 1;;fwxcluster;mcast_vrrp;;vrrp;accept;Log;fwxcluster;Any;"VRRP;;*Comment > suppressed* > ;;;;;igmp**;;;;; > 2;;fwxcluster;fwxcluster;;FireWall;accept;Log;fwxcluster;Any;"Management > FWg;*Comment suppressed* > ;;fwmgmpe**;fwmgmpe**;;ssh**;;;;; > ;;fwmgm**;fwmgm**;;;;;;; > 3;NTP;G_NTP_Clients;cmm_ntpserver_pe01;;ntp;accept;None;fwxcluster;Any;*Comment > suppressed* > ;;;cmm_ntpserver_pe02**;;;;;;; > What I need ,explained in pseudo code, is this: > > Read the first column of the next line. If there's a number: > Evaluate the first column of the next line. If there's no number there, > concatenate (separating with a comma) \ > the strings in the columns of this line with the last one and eliminate > the text in the current one > > The output should be something like this: > > NO.;NAME;SOURCE;DESTINATION;VPN  ;SERVICE;ACTION;TRACK;INSTALL > ON;TIME;COMMENT > 1;;fwxcluster,fwmgmpe**,fwmgm**;mcast_vrrp,fwmgmpe**,fwmgm**;;vrrp,ssh**;accept;Log;fwxcluster;Any;*Comment > suppressed* > ;;;;;;;;;; > ;;;;;;;;;; > 3;NTP;G_NTP_Clients;cmm_ntpserver_pe01,cmm_ntpserver_pe02**;;ntp;accept;None;fwxcluster;Any;*Comment > suppressed* > ;;;;;;;;;; > > The empty lines are there only to be more clear, I don't actually need them. > > Thanks! > Save your time folks, this was answered hours ago on the main Python mailing list. -- Roses are red, Violets are blue, Most poems rhyme, But this one doesn't. Mark Lawrence From glez_b at comunidad.unam.mx Sat Oct 12 03:18:52 2013 From: glez_b at comunidad.unam.mx (Boris Vladimir Comi) Date: Sat, 12 Oct 2013 01:18:52 +0000 Subject: [Tutor] Getting daily averages with pandas In-Reply-To: <7a0c6960a735485f8f4919ead104b934@CO1PR07MB316.namprd07.prod.outlook.com> References: <7a0c6960a735485f8f4919ead104b934@CO1PR07MB316.namprd07.prod.outlook.com> Message-ID: Boris Vladimir Comi escrito: I found a way to create daily averages of many variables, for example of a database that has the following structure: Fecha,Time, DirViento, MagViento, Temperatura, Humedad, PreciAcu. Each column is daily data every 15 minutes. I share the code, which, with the help of your comments I have adapted to my project. The code calculates the average of the columns Temperatura and Humedad as well as the sum of column PreciAcu. The code is as follows: import numpy as np import pandas as pd data = pd.read_csv('tancoyol.csv') index5=data.set_index(['Fecha','Hora'],inplace=True) grouped = index5.groupby(level=0) stat_cea = grouped.agg({'Temperatura':np.mean,'Humedad':np.mean,'PreciAcu':np.sum}) print 'Done............' Now I have one more question, I need to convert to radians the DirViento column, how I can do this and how can add this new column to my data file? In summary,i need to obtain 3 columns from the DirViento column agregate to datafile. DirViento 1/07/2011 00:00:00 1/07/2011 00:15:00 1/07/2011 00:30:00 1/07/2011 00:45:00 2/07/2011 00:00:00 2/07/2011 00:15:00 2/07/2011 00:30:00 2/07/2011 00:45:00 . . . Specifically: First I need to convert the values of DirViento column to Radians (This should be a new column called Rad) Second I need to get the sine of Rad column (This should be a new column called Sin) Third I need to get the cosine of Rad column (This should be a new column called Cos). How I can achieve this? -------------- next part -------------- An HTML attachment was scrubbed... URL: From jackiexxduh at yahoo.com Sat Oct 12 07:18:56 2013 From: jackiexxduh at yahoo.com (Jackie Canales) Date: Fri, 11 Oct 2013 22:18:56 -0700 (PDT) Subject: [Tutor] Looking for Words - Help In-Reply-To: <1381468707.8479.YahooMailNeo@web121702.mail.ne1.yahoo.com> References: <1381468707.8479.YahooMailNeo@web121702.mail.ne1.yahoo.com> Message-ID: <1381555136.33670.YahooMailNeo@web121705.mail.ne1.yahoo.com> from string import punctuation #helper function def strip(text): ? ? 'returns text with all punctuation removed' ? ? for symb in punctuation: #import from string ? ? ? ? text = text.replace(symb, ' ') ? ? ? ?? ? ? return text #helper function def wordin(s,t): ? ? 'does word s occur in text t' ? ? #s in t ? ? t = strip(t) ? ? return s in t.split() def lines(name, word): ? ? 'print all lines of name in which word occurs' ? ? infile = open(name, 'r') ? ? lst = infile.read() ? ? infile.close() ? ? for line in lst.splitlines(): ? ? ? ? if word in line: ? ? ? ? ? ?words = line ? ? for index, word in enumerate(words): ? ? ? ? print(words) LINK TO CODE:http://codetidy.com/6926/ Thank you for the help so far! I figured out how to split the file in order to only out all the lines that have the word river in it. I tried reading up on enumerate but I am still having trouble understanding it. The code above just repeats this line in the middle of the page about 20 times. ? ? probably essentially dam the widest river in the world. LINK:?http://imgur.com/7pZvfzA I tried understanding the feedback given to me the above is what i got so far if you could please help me with the enumerate. Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Sat Oct 12 10:15:37 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 12 Oct 2013 09:15:37 +0100 Subject: [Tutor] Looking for Words - Help In-Reply-To: <1381555136.33670.YahooMailNeo@web121705.mail.ne1.yahoo.com> References: <1381468707.8479.YahooMailNeo@web121702.mail.ne1.yahoo.com> <1381555136.33670.YahooMailNeo@web121705.mail.ne1.yahoo.com> Message-ID: On 12/10/2013 06:18, Jackie Canales wrote: > from string import punctuation > #helper function I'd be inclined to call this strippunc as strip is use so often. > def strip(text): > 'returns text with all punctuation removed' > > for symb in punctuation: #import from string > text = text.replace(symb, ' ') > return text Just for reference instead of replace you might like to consider the string translate method and its associated maketrans see http://docs.python.org/3/library/stdtypes.html#str.translate and http://docs.python.org/3/library/stdtypes.html#str.maketrans. They're in the string module in Python 2. > > #helper function > def wordin(s,t): > 'does word s occur in text t' > #s in t > t = strip(t) > return s in t.split() > > def lines(name, word): > 'print all lines of name in which word occurs' > > infile = open(name, 'r') > lst = infile.read() > infile.close() > > for line in lst.splitlines(): > if word in line: > words = line > for index, word in enumerate(words): > print(words) I suspect you want print(word) above :) Better yet print(index, word) will show you exactly what you're getting. Also see further below. > > LINK TO CODE:http://codetidy.com/6926/ > > Thank you for the help so far! I figured out how to split the file in > order to only out all the lines that have the word river in it. I tried > reading up on enumerate but I am still having trouble understanding it. > The code above just repeats this line in the middle of the page about 20 > times. > > probably essentially dam the widest river in the world. > LINK: http://imgur.com/7pZvfzA > > I tried understanding the feedback given to me the above is what i got > so far if you could please help me with the enumerate. > Enumerate simply pulls an item from some iterable such as a list with an associated index which has a default start number of zero. The example from http://docs.python.org/3/library/functions.html#enumerate >>> seasons = ['Spring', 'Summer', 'Fall', 'Winter'] >>> list(enumerate(seasons)) [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')] >>> list(enumerate(seasons, start=1)) [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')] Note that the above is taken from an interactive session. If you haven't used this extremely powerful tool please start doing so immediately, it's one of Python's most powerful features. It may well help you to try this by actually typing in some of the code from Peter Otten's original reply to your post. HTH. -- Roses are red, Violets are blue, Most poems rhyme, But this one doesn't. Mark Lawrence From davea at davea.name Sat Oct 12 13:50:44 2013 From: davea at davea.name (Dave Angel) Date: Sat, 12 Oct 2013 11:50:44 +0000 (UTC) Subject: [Tutor] Looking for Words - Help References: <1381468707.8479.YahooMailNeo@web121702.mail.ne1.yahoo.com> <1381555136.33670.YahooMailNeo@web121705.mail.ne1.yahoo.com> Message-ID: On 12/10/2013 01:18, Jackie Canales wrote: You're still posting in html, not text. I stripped out the markup portion of your message, but you're still left with lots of invisible characters in the following. Your email program is stuffing "\xa0" characters in place of every other space, which cuts the indentation in half. Here's the html in your message for just one of the lines below:
    infile.close()
In the text version, it looks approximately like this: _ _ infile.close() some readers will just show it as infile.close() When you compose your message in your email program, please mark it as a text message in your email program. Otherwise you can never be sure what each of us will see. > from string import punctuation > #helper function > def strip(text): > ? ? 'returns text with all punctuation removed' > > ? ? for symb in punctuation: #import from string > ? ? ? ? text = text.replace(symb, ' ') > ? ? ? ?? > ? ? return text > > #helper function > def wordin(s,t): > ? ? 'does word s occur in text t' > ? ? #s in t > ? ? t = strip(t) > ? ? return s in t.split() I have no idea how that function will be useful. It makes much more sense to me to strip the entire file, then split it into a list of words. Then you loop through that list of words, seeing which of those words match your sample word. > > def lines(name, word): > ? ? 'print all lines of name in which word occurs' > > ? ? infile = open(name, 'r') > ? ? lst = infile.read() > ? ? infile.close() > > ? ? for line in lst.splitlines(): > ? ? ? ? if word in line: > ? ? ? ? ? ?words = line > ? ? for index, word in enumerate(words): > ? ? ? ? print(words) > > LINK TO CODE:http://codetidy.com/6926/ > > Thank you for the help so far! I figured out how to split the file in order to only out all the lines that have the word river in it. But that's not what the assignment called for. You shouldn't be splitting on lines, but on words. Otherwise, how are you going to handle a line that starts with the word river? Make a single list containing all the words in the file. > I tried reading > up on enumerate but I am still having trouble understanding it. The > code above just repeats this line in the middle of the page about 20 > times. > > ? ? probably essentially dam the widest river in the world. Well, it prints the same thing because you're printing "words", rather than "word." And of course if you wanted to actually see the index working, you'd have to print that as well. for index, word in enumerate(words): print(index, word) > > LINK:?http://imgur.com/7pZvfzA > > I tried understanding the feedback given to me the above is what i got so far if you could please help me with the enumerate. > > Thanks > -- DaveA From kushgoyal.89 at gmail.com Sat Oct 12 17:01:04 2013 From: kushgoyal.89 at gmail.com (Kush Goyal) Date: Sat, 12 Oct 2013 20:31:04 +0530 Subject: [Tutor] Cannot understand object initiation Message-ID: Hi, I am learning web development by using flask framework. The below code is used to create a class LoginForm which inherits from the class Form. In the method 'validate' of class 'LoginForm' the variable 'user' is initialized by using: "user = User.query.filter_by ( username = self.username.data ).first() " now this I do not understand. Can a object be create by using a method of a class instead of the class consturctor? I mean shouldn't it be: user = User() Later in the code "user.check_password(self.password.data)" is used. So here also how can check_password be used when the object 'user' has not been initiated using a constructor? Also, 'User' is a class which inherits from 'db.Model'. And db is initialized as: db = SQLAlchemy(app) So, here is db is an object and Model is a variable of class SQLAlchemy. Can someone please explain what is db.Model and can SQLAlchemy.Model be used in place of db.Model? I hope my questions are clear. Thanks in advance. Below is the code. Kush from flask.wtf import Form, TextField, PasswordField, validators from myapplication.models import User class LoginForm(Form): username = TextField('Username', [validators.Required()]) password = PasswordField('Password', [validators.Required()]) def __init__(self, *args, **kwargs): Form.__init__(self, *args, **kwargs) self.user = None def validate(self): rv = Form.validate(self) if not rv: return False user = User.query.filter_by( username=self.username.data).first() if user is None: self.username.errors.append('Unknown username') return False if not user.check_password(self.password.data): self.password.errors.append('Invalid password') return False self.user = user return True From alan.gauld at btinternet.com Sat Oct 12 18:42:54 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 12 Oct 2013 17:42:54 +0100 Subject: [Tutor] Cannot understand object initiation In-Reply-To: References: Message-ID: On 12/10/13 16:01, Kush Goyal wrote: > Hi, > > I am learning web development by using flask framework. The below code > is used to create a class LoginForm which inherits from the class > Form. > > In the method 'validate' of class 'LoginForm' the variable 'user' is > initialized by using: > > "user = User.query.filter_by ( username = self.username.data ).first()" > > now this I do not understand. > > Can a object be create by using a method of a class instead of the > class consturctor? I mean shouldn't it be: > > user = User() > An object can be returned by any function or method. Consider: >>> class C: ... pass ... >>> def f(): ... return C() ... >>> c1 = C() >>> c2 = f() >>> isinstance(c1,C) True >>> isinstance(c2,C) True >>> > Later in the code "user.check_password(self.password.data)" is used. > So here also how can check_password be used when the object 'user' has > not been initiated using a constructor? It has, but it was done inside the User.query.filter_by() method. I don't know Flask but I assume this method initializes a new empty User instance then populates it with data retrieved from a database before returning the instance to its caller. > Also, 'User' is a class which inherits from 'db.Model'. And db is > initialized as: db = SQLAlchemy(app) > > So, here is db is an object and Model is a variable of class > SQLAlchemy. Can someone please explain what is db.Model and can > SQLAlchemy.Model be used in place of db.Model? That requires a wee bit more detailed knowledge of SQLAlchemy. My guess is that db.Model is a class. Classes are objects too and can be stored as variables. Again, continuing the session above: >>> myclass = C >>> c3 = myclass() >>> isinstance(c3,C) True HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From bgailer at gmail.com Sat Oct 12 18:47:51 2013 From: bgailer at gmail.com (bob gailer) Date: Sat, 12 Oct 2013 12:47:51 -0400 Subject: [Tutor] Cannot understand object initiation In-Reply-To: References: Message-ID: <52597D37.8000905@gmail.com> On 10/12/2013 11:01 AM, Kush Goyal wrote: > [[snip] > "user = User.query.filter_by ( username = self.username.data ).first()" > > now this I do not understand. > > Can a object be create by using a method of a class instead of the > class consturctor? I Without seeing the code you reference (User module) I can hazard a guess: This code is not creating an object - it is returning a reference to an existing object. The key to the object is username, and first() returns the first instance should there be more than one, User is some objectimported from myapplication.models. query is a callable object that is an attribute of User. filter_by is a callable object that is an attribute of query. first is a callable object that is an attribute of filter_by. Nothing in the above suggests object creation. HTH -- Bob Gailer 919-636-4239 Chapel Hill NC From alan.gauld at btinternet.com Sat Oct 12 18:55:34 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 12 Oct 2013 17:55:34 +0100 Subject: [Tutor] Looking for Words - Help In-Reply-To: <1381555136.33670.YahooMailNeo@web121705.mail.ne1.yahoo.com> References: <1381468707.8479.YahooMailNeo@web121702.mail.ne1.yahoo.com> <1381555136.33670.YahooMailNeo@web121705.mail.ne1.yahoo.com> Message-ID: On 12/10/13 06:18, Jackie Canales wrote: > for line in lst.splitlines(): > if word in line: > words = line Notice that you are overwriting words each time you get a match. So the final value of words at the end of the for loop will just be the last line found. All earlier lines will have been lost. However, as Dave points out, this is the wrong approach to the assignment. You should be getting all the words not just lines that contain the word because the context(=/- 5 words) might span lines into lines that do not of themselves contain your word. So this approach throws away words which you may need. > for index, word in enumerate(words): > print(words) The obvious error of using words instead of word has already been pointed out. But since we've seen a few errors in your use of for loops can I just check you are clear on how Python for loops work? If you have used other languages they are like a foreach loop. They do not use indexing they return each item in a sequence until the sequence ends. This is much easier than the for loops in languages like C, Pascal, Java, Basic etc. enumerate() gives you access to indexes on the relatively few occasions you need that extra information. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From emile at fenx.com Sun Oct 13 18:08:08 2013 From: emile at fenx.com (Emile van Sebille) Date: Sun, 13 Oct 2013 09:08:08 -0700 Subject: [Tutor] Getting daily averages with pandas In-Reply-To: References: <7a0c6960a735485f8f4919ead104b934@CO1PR07MB316.namprd07.prod.outlook.com> Message-ID: Hi Boris, Read up on the trig functions in the math module. http://docs.python.org/2/library/math.html#trigonometric-functions Emile On 10/11/2013 6:18 PM, Boris Vladimir Comi wrote: > > Boris Vladimir Comi escrito: > > I found a way to create daily averages of many variables, for example of > a database that has the following structure: > > Fecha,Time, DirViento, MagViento, Temperatura, Humedad, PreciAcu. > > Each column is daily data every 15 minutes. I share the code, which, > with the help of your comments I have adapted to my project. The code > calculates the average of the columns Temperatura and Humedad as well as > the sum of column PreciAcu. The code is as follows: > > |import numpyas np > import pandasas pd > > > data= pd.read_csv('tancoyol.csv') > index5=data.set_index(['Fecha','Hora'],inplace=True) > > grouped= index5.groupby(level=0) > stat_cea= grouped.agg({'Temperatura':np.mean,'Humedad':np.mean,'PreciAcu':np.sum}) > print 'Done............'| > > Now I have one more question, I need to convert to radians the DirViento > column, how I can do this and how can add this new column to my data file? > > In summary,i need to obtain 3 columns from the DirViento column agregate > to datafile. > > DirViento > 1/07/2011 00:00:00 > 1/07/2011 00:15:00 > 1/07/2011 00:30:00 > 1/07/2011 00:45:00 > 2/07/2011 00:00:00 > 2/07/2011 00:15:00 > 2/07/2011 00:30:00 > 2/07/2011 00:45:00 > . > . > . > > Specifically: > > First I need to convert the values of DirViento column to Radians (This > should be a new column called Rad) Second I need to get the sine of Rad > column (This should be a new column called Sin) Third I need to get the > cosine of Rad column (This should be a new column called Cos). > > How I can achieve this? > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From kushgoyal.89 at gmail.com Mon Oct 14 15:27:44 2013 From: kushgoyal.89 at gmail.com (Kush Goyal) Date: Mon, 14 Oct 2013 18:57:44 +0530 Subject: [Tutor] Cannot understand object initiation In-Reply-To: <52597D37.8000905@gmail.com> References: <52597D37.8000905@gmail.com> Message-ID: Hi, Thanks a lot Bob and Allan for the help. I tried experimenting with classes and objects on python interpretor and learned that in python functions, classes, method, objects and modules all can be passed around and returned. >From what I understood from your answers: user = User.query.filter_by ( username = self.username.data ).first() returns a reference to an instance of class User. So user is an object of type User class. Also, db is an sqlalchemy engine and db.Model is a class. db.Model is I think a sqlalchemy declarative base class which has all the needed methods and classes for database handling. So, did I get the above things right? Thanks! Kush On Sat, Oct 12, 2013 at 10:17 PM, bob gailer wrote: > On 10/12/2013 11:01 AM, Kush Goyal wrote: >> >> [[snip] >> >> "user = User.query.filter_by ( username = self.username.data ).first()" >> >> now this I do not understand. >> >> Can a object be create by using a method of a class instead of the >> class consturctor? I > > Without seeing the code you reference (User module) I can hazard a guess: > > This code is not creating an object - it is returning a reference to an > existing object. > > The key to the object is username, and first() returns the first instance > should there be more than one, > > User is some objectimported from myapplication.models. > query is a callable object that is an attribute of User. > filter_by is a callable object that is an attribute of query. > first is a callable object that is an attribute of filter_by. > Nothing in the above suggests object creation. > > HTH > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC > From okeronye at gmail.com Mon Oct 14 12:54:01 2013 From: okeronye at gmail.com (Okechukwu Nkaronye) Date: Mon, 14 Oct 2013 10:54:01 +0000 Subject: [Tutor] Fwd: we need assistance in my school In-Reply-To: References: Message-ID: ---------- Forwarded message ---------- From: Okechukwu Nkaronye Date: Fri, 11 Oct 2013 13:04:10 +0000 Subject: we need assistance in my school To: sanomat.tai at formin.fi, office at ise.edu.ee, support at edline.com, contact at thebaudieves.org, contact at thebaudieres.org Hi my name is okechukwu . I teaches computer at a low grade of 8, 9, 10, 12 years ages . Please I would be pleased if you could assist us in helping our children to get to know programming skills I am not very vast in programming and know little in programming. We dim it fit the create a forum for our younger ones to start early to learn computer programming . Much Anticipations Mr. Okechukwu Nkaronye From alan.gauld at btinternet.com Mon Oct 14 15:39:07 2013 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Mon, 14 Oct 2013 14:39:07 +0100 (BST) Subject: [Tutor] Cannot understand object initiation In-Reply-To: References: <52597D37.8000905@gmail.com> Message-ID: <1381757947.37180.YahooMailNeo@web186006.mail.ir2.yahoo.com> I tried experimenting with classes and objects on python interpretor >and learned that in python functions, classes, method, objects and >modules all can be passed around and returned.That's correct, they are all objects in Python From what I understood from your answers: > >user = User.query.filter_by ( username = self.username.data ).first() > >returns a reference to an instance of class User. So user is an object >of type User class.Not necessarily. first() can return any kind of object. It just seems likely? that in this case it will be a User. But it depends entirely on how the? first() method of whatever object User.query.filter_by() is implemented. Also, db is an sqlalchemy engine and db.Model is a class. > >db.Model is I think a sqlalchemy declarative base class which has all >the needed methods and classes for database handling. > >Possibly but you'll need someone who knows SQLAlchemy better than? me to answer definitively Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Oct 14 15:48:48 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 14 Oct 2013 14:48:48 +0100 Subject: [Tutor] Fwd: we need assistance in my school In-Reply-To: References: Message-ID: On 14/10/13 11:54, Okechukwu Nkaronye wrote: > Hi my name is okechukwu . I teaches computer at a low grade of 8, 9, 10, 12 > years ages . > > Please I would be pleased if you could assist us in helping our children to > get to know programming skills > > I am not very vast in programming and know little in programming. There is a Python education Special Interest Group(SIG) that you could join. It has a mailing list and focuses on issues around teaching Python. http://www.python.org/community/sigs/current/edu-sig/ This list is more about providing hands on advice and help to those learning Python rather than those teaching it. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From kwpolska at gmail.com Mon Oct 14 16:26:22 2013 From: kwpolska at gmail.com (=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?=) Date: Mon, 14 Oct 2013 16:26:22 +0200 Subject: [Tutor] Cannot understand object initiation In-Reply-To: References: <52597D37.8000905@gmail.com> Message-ID: On Mon, Oct 14, 2013 at 3:27 PM, Kush Goyal wrote: > Also, db is an sqlalchemy engine and db.Model is a class. > > db.Model is I think a sqlalchemy declarative base class which has all > the needed methods and classes for database handling. > > So, did I get the above things right? Not quite. db.Model is basically a representation of a database record. Read this: http://docs.sqlalchemy.org/en/rel_0_8/orm/tutorial.html Note that the above document uses the name `Base` (declarative base) to describe what Flask-SQLAlchemy calls `db.Model`. -- Chris ?Kwpolska? Warrick PGP: 5EAAEA16 stop html mail | always bottom-post | only UTF-8 makes sense From bharathks123 at yahoo.com Mon Oct 14 16:16:20 2013 From: bharathks123 at yahoo.com (bharath ks) Date: Mon, 14 Oct 2013 22:16:20 +0800 (SGT) Subject: [Tutor] Fw: Fwd: we need assistance in my school In-Reply-To: References: Message-ID: <1381760180.73682.YahooMailNeo@web192501.mail.sg3.yahoo.com> this is interesting .. i would like to contribute and i am living in germany ? Thanks & BR, Bharath Shetty On Monday, 14 October 2013 3:49 PM, Alan Gauld wrote: On 14/10/13 11:54, Okechukwu Nkaronye wrote: > Hi my name is okechukwu . I teaches computer at a low grade of 8, 9, 10, 12 > years ages . > > Please I would be pleased if you could assist us in helping our children to > get to know programming skills > > I am not very vast in programming and know little in programming. There is a Python education Special Interest Group(SIG) that you could join. It has a mailing list and focuses on issues around teaching Python. http://www.python.org/community/sigs/current/edu-sig/ This list is more about providing hands on advice and help to those learning Python rather than those teaching it. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From corsam28 at hotmail.com Mon Oct 14 16:41:43 2013 From: corsam28 at hotmail.com (Sammy Cornet) Date: Mon, 14 Oct 2013 09:41:43 -0500 Subject: [Tutor] Compare function! Message-ID: Hello!I?m using Idle (Python 2.7,5 version). I?m trying to write a program of compare function that returns 1 if a > b , 0 if a == b , and -1 if a < b . In which I?m want to get the user to prompt for the values of a and b. For some reason I can?t run it. The follwing is what I have written on my script: def comparefunc (a, b): a = 3 b = 4 if a < b: return 1 elif a == b: return 0 elif a < b: return -1 print "return" And, this is what I get for my output: Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32Type "copyright", "credits" or "license()" for more information.>>> ================================ RESTART ================================>>> >>> -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Oct 14 22:47:45 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 14 Oct 2013 21:47:45 +0100 Subject: [Tutor] Fw: Fwd: we need assistance in my school In-Reply-To: <1381760180.73682.YahooMailNeo@web192501.mail.sg3.yahoo.com> References: <1381760180.73682.YahooMailNeo@web192501.mail.sg3.yahoo.com> Message-ID: On 14/10/13 15:16, bharath ks wrote: > this is interesting .. i would like to contribute and i am living in germany Where you live shouldn't be an issue. Join the SIG by getting involved. The links are all on the SIG web pages. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From brianjamesarb at gmail.com Mon Oct 14 22:53:44 2013 From: brianjamesarb at gmail.com (brian arb) Date: Mon, 14 Oct 2013 16:53:44 -0400 Subject: [Tutor] Fwd: we need assistance in my school In-Reply-To: References: Message-ID: This looks like a very fun way to teach programming at an early age http://scratch.mit.edu/ On Mon, Oct 14, 2013 at 6:54 AM, Okechukwu Nkaronye wrote: > ---------- Forwarded message ---------- > From: Okechukwu Nkaronye > Date: Fri, 11 Oct 2013 13:04:10 +0000 > Subject: we need assistance in my school > To: sanomat.tai at formin.fi, office at ise.edu.ee, support at edline.com, > contact at thebaudieves.org, contact at thebaudieres.org > > Hi my name is okechukwu . I teaches computer at a low grade of 8, 9, 10, 12 > years ages . > > Please I would be pleased if you could assist us in helping our children to > get to know programming skills > > I am not very vast in programming and know little in programming. > > > > We dim it fit the create a forum for our younger ones to start early to > learn computer programming . > > > > Much Anticipations > > Mr. Okechukwu Nkaronye > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Oct 14 23:07:27 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 14 Oct 2013 22:07:27 +0100 Subject: [Tutor] Compare function! In-Reply-To: References: Message-ID: On 14/10/13 15:41, Sammy Cornet wrote: > . In which I?m want to get the user to prompt for the values of a and b. So where is the code where you prompt the user and read input. All we can see is a single function? > For some reason I can?t run it. The follwing is what I have written on > my script: > > def comparefunc (a, b): > a = 3 > b = 4 The above assignments make your parameters useless since you have overwritten them This function effectively compares 3 and 4 only. As such the result will always return -1. Having func as part of the name is usually considered a bad idea. We can see its a function by the way we use it. The only time having func in the name is useful is when you are passing it as a parameter to another function or storing it in another variable. But I suspect that's several learning steps away from you just now. > if a < b: > return 1 > elif a == b: > return 0 > elif a < b: > return -1 > print "return" This all looks OK except putting prints inside a function like this is usually only good as a debugging aid. You probably want to lose that once you have it working correctly. > And, this is what I get for my output: > >>> ================================ RESTART > ================================ That may be because you define the function but don't seem to call it at any point. You need to remove the two assignments for a and b Then implement the get input calls to get the values from the user then call the function and finally print the result. Something like this: a = int(raw_input('gimme an a ')) b = int(raw_input('gimme a b ')) result = camparefunc(a,b) print result HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From askar.kengesbayev at etrade.com Tue Oct 15 15:56:31 2013 From: askar.kengesbayev at etrade.com (Kengesbayev, Askar) Date: Tue, 15 Oct 2013 13:56:31 +0000 Subject: [Tutor] Fwd: we need assistance in my school In-Reply-To: References: Message-ID: <6FAD14604B087B438F6FF64D9875A40C68F57846@atl1ex10mbx4.corp.etradegrp.com> Hi Okechukwu, I would recommend to use Khan Academy. It is free resource of use. He covers python basic plus they built sophisticated system that track performance of each student. That would help you a lot and see weak sides of your students. https://www.khanacademy.org/cs For more advance students I would go with coursera. I like that course a lot. https://www.coursera.org/course/interactivepython Thanks, Askar -----Original Message----- From: Okechukwu Nkaronye [mailto:okeronye at gmail.com] Sent: Monday, October 14, 2013 6:54 AM To: tutor at python.org; okeronye at gmail.com Subject: [Tutor] Fwd: we need assistance in my school ---------- Forwarded message ---------- From: Okechukwu Nkaronye Date: Fri, 11 Oct 2013 13:04:10 +0000 Subject: we need assistance in my school To: sanomat.tai at formin.fi, office at ise.edu.ee, support at edline.com, contact at thebaudieves.org, contact at thebaudieres.org Hi my name is okechukwu . I teaches computer at a low grade of 8, 9, 10, 12 years ages . Please I would be pleased if you could assist us in helping our children to get to know programming skills I am not very vast in programming and know little in programming. We dim it fit the create a forum for our younger ones to start early to learn computer programming . Much Anticipations Mr. Okechukwu Nkaronye From davea at davea.name Wed Oct 16 03:00:40 2013 From: davea at davea.name (Dave Angel) Date: Wed, 16 Oct 2013 01:00:40 +0000 (UTC) Subject: [Tutor] ImportError: 'DLL load failed: %1 is not a valid Win32 application.' References: Message-ID: On 10/10/2013 06:34, Sreenivasulu wrote: > Hi, > > I have windows 8 64 bit machine and installed python 2.7.3 64 bit version > . > > i have 32 bit package 4Suite-XML-1.0.24Suite-XML-1.0.2.win32.exe package > but am getting below error : Can't do it. 32 bit dll's cannot be loaded by 64 bit exes. If you need to use that particular DLL, get a 32bit version of Python. Or if you can find or build a 64bit version of the DLL, it could work with the 64bit Python. -- DaveA From rapinedo at miners.utep.edu Wed Oct 16 20:49:01 2013 From: rapinedo at miners.utep.edu (Pinedo, Ruben A) Date: Wed, 16 Oct 2013 18:49:01 +0000 Subject: [Tutor] Help please Message-ID: I was given this code and I need to modify it so that it will: #1. Error handling for the files to ensure reading only .txt file #2. Print a range of top words... ex: print top 10-20 words #3. Print only the words with > 3 characters #4. Modify the printing function to print top 1 or 2 or 3 .... #5. How many unique words are there in the book of length 1, 2, 3 etc I am fairly new to python and am completely lost, i looked in my book as to how to do number one but i cannot figure out what to modify and/or delete to add the print selection. This is the code: import string def process_file(filename): hist = dict() fp = open(filename) for line in fp: process_line(line, hist) return hist def process_line(line, hist): line = line.replace('-', ' ') for word in line.split(): word = word.strip(string.punctuation + string.whitespace) word = word.lower() hist[word] = hist.get(word, 0) + 1 def common_words(hist): t = [] for key, value in hist.items(): t.append((value, key)) t.sort(reverse=True) return t def most_common_words(hist, num=100): t = common_words(hist) print 'The most common words are:' for freq, word in t[:num]: print freq, '\t', word hist = process_file('emma.txt') print 'Total num of Words:', sum(hist.values()) print 'Total num of Unique Words:', len(hist) most_common_words(hist, 50) Any help would be greatly appreciated because i am struggling in this class. Thank you in advance Respectfully, Ruben Pinedo Computer Information Systems College of Business Administration University of Texas at El Paso -------------- next part -------------- An HTML attachment was scrubbed... URL: From c.t.matsumoto at gmail.com Thu Oct 17 10:05:18 2013 From: c.t.matsumoto at gmail.com (Todd Matsumoto) Date: Thu, 17 Oct 2013 10:05:18 +0200 Subject: [Tutor] Help please In-Reply-To: References: Message-ID: <525F9A3E.4030807@gmail.com> Hello Ruben, You might already know this, but the Python documentation will get you pretty far: http://www.python.org/doc/ Here are some things to lookup that may help you solve the problems. On 10/16/2013 08:49 PM, Pinedo, Ruben A wrote: > I was given this code and I need to modify it so that it will: > > #1. Error handling for the files to ensure reading only .txt file Look up exceptions. Find out what the string method endswith() does. > #2. Print a range of top words... ex: print top 10-20 words > #3. Print only the words with > 3 characters Look up how the built-in len() works. > #4. Modify the printing function to print top 1 or 2 or 3 .... > #5. How many unique words are there in the book of length 1, 2, 3 etc Read up on different datatypes and choose the one, or combination types that would solve this for you. T P.S. Tutors I hope this is posted to the list and the top. I always get that wrong! From alan.gauld at btinternet.com Thu Oct 17 15:13:07 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 17 Oct 2013 14:13:07 +0100 Subject: [Tutor] Help please In-Reply-To: References: Message-ID: On 16/10/13 19:49, Pinedo, Ruben A wrote: > I was given this code and I need to modify it so that it will: > > #1. Error handling for the files to ensure reading only .txt file I'm not sure what is meant here since your code only ever opens 'emma.txt', so it is presumably a text file... Or are you supposed to make the filename a user provided value maybe (using raw_input maybe?) > #2. Print a range of top words... ex: print top 10-20 words I assume 'top' here means the most common? Whoever is writing the specification for this problem needs to be a bit more specific in their definitions. If so you need to fix the bugs in process_line() and process_file(). I don;t know if these are deliberate bugs or somebody is just sloppy. But neither work as expected right now. (Hint: Consider the return values of each) Once you've done that you can figure out how to extract the required number of words from your (unsorted) dictionary. and put that in a reporting function and print the output. You might be able to use the two common words functions, although watch out because they don't do exactly what you want and one of them is basically broken... > #3. Print only the words with > 3 characters Modify the above to discard words of 3 letters or less. > #4. Modify the printing function to print top 1 or 2 or 3 .... I assume this means take a parameter that speciffies the number of words to print. Or it could be the length of word to ignore. Again the specification is woolly In either case its a small modification to your reporting function. > #5. How many unique words are there in the book of length 1, 2, 3 etc This is slicing the data slightly differently but again not that different to the earlier requirement. > I am fairly new to python and am completely lost, i looked in my book as > to how to do number one but i cannot figure out what to modify and/or > delete to add the print selection. This is the code: You need to modify the two brokemn functions and add a new reporting function. (Despite the reference to a printing function I'd suggest keeping the data extraction and printing seperate. > import string > > def process_file(filename): > hist = dict() > fp = open(filename) > for line in fp: > process_line(line, hist) > return hist > > def process_line(line, hist): > line = line.replace('-', ' ') > for word in line.split(): > word = word.strip(string.punctuation + string.whitespace) > word = word.lower() > hist[word] = hist.get(word, 0) + 1 > > def common_words(hist): > t = [] > for key, value in hist.items(): > t.append((value, key)) > t.sort(reverse=True) > return t > > def most_common_words(hist, num=100): > t = common_words(hist) > print 'The most common words are:' > for freq, word in t[:num]: > print freq, '\t', word > hist = process_file('emma.txt') > print 'Total num of Words:', sum(hist.values()) > print 'Total num of Unique Words:', len(hist) > most_common_words(hist, 50) > > Any help would be greatly appreciated because i am struggling in this > class. Thank you in advance hth -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From __peter__ at web.de Thu Oct 17 15:37:49 2013 From: __peter__ at web.de (Peter Otten) Date: Thu, 17 Oct 2013 15:37:49 +0200 Subject: [Tutor] Help please References: Message-ID: Alan Gauld wrote: [Ruben Pinedo] > def process_file(filename): > hist = dict() > fp = open(filename) > for line in fp: > process_line(line, hist) > return hist > > def process_line(line, hist): > line = line.replace('-', ' ') > > for word in line.split(): > word = word.strip(string.punctuation + string.whitespace) > word = word.lower() > > hist[word] = hist.get(word, 0) + 1 [Alan Gauld] > If so you need to fix the bugs in process_line() and > process_file(). I don;t know if these are deliberate bugs > or somebody is just sloppy. But neither work as expected > right now. (Hint: Consider the return values of each) I fail to see the bug. process_line() mutates its `hist` argument, so there's no need to return something. Or did you mean something else that escapes me? From nik at naturalnet.de Thu Oct 17 16:17:27 2013 From: nik at naturalnet.de (Dominik George) Date: Thu, 17 Oct 2013 16:17:27 +0200 Subject: [Tutor] Help please In-Reply-To: <525F9A3E.4030807@gmail.com> References: <525F9A3E.4030807@gmail.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA512 Todd Matsumoto schrieb: >> #1. Error handling for the files to ensure reading only .txt file >Look up exceptions. >Find out what the string method endswith() does. One should note that the OP probably meant files of the type text/plain rather than .txt files. File name extensions are a convenience to identify a file on first glance, but they tell absolutely nothing about the contents. So, look up MIME types as well ;)! - -nik -----BEGIN PGP SIGNATURE----- Version: APG v1.0.8-fdroid iQFNBAEBCgA3BQJSX/F3MBxEb21pbmlrIEdlb3JnZSAobW9iaWxlIGtleSkgPG5p a0BuYXR1cmFsbmV0LmRlPgAKCRAvLbGk0zMOJZxHB/9TGh6F1vRzgZmSMHt48arc jruTRfvOK9TZ5MWm6L2ZpxqKr3zBP7KSf1ZWSeXIovat9LetETkEwZ9bzHBuN8Ve m8YsOVX3zR6VWqGkRYYer3MbWo9DCONlJUKGMs/qjB180yxxhQ12Iw9WAHqam1Ti n0CCWsf4l5B3WBe+t2aTOlQNmo//6RuBK1LfCrnYX0XV2Catv1075am0KaTvbxfB rfHHnR4tdIYmZ8P/SkO3t+9JzJU9e+H2W90++K9EkMTBJxUhsa4AuZIEr8WqEfSe EheQMUp23tlMgKRp6UHiRJBljEsQJ0XFuYa+zj6hXCXoru/9ReHTRWcvJEpfXxEC =hJ0m -----END PGP SIGNATURE----- From askar.kengesbayev at etrade.com Thu Oct 17 16:21:17 2013 From: askar.kengesbayev at etrade.com (Kengesbayev, Askar) Date: Thu, 17 Oct 2013 14:21:17 +0000 Subject: [Tutor] Help please In-Reply-To: References: Message-ID: <6FAD14604B087B438F6FF64D9875A40C68F5ADCA@atl1ex10mbx4.corp.etradegrp.com> Ruben, #1 you can try something like this try: with open('my_file.txt') as file: pass except IOError as e: print "Unable to open file" #Does not exist or you do not have read permission #2. I would try to use regular expression push words to array and then you can manipulate array. Not sure if it is efficient way but it should work. #3 . easy way would be to use regular expression. Re module. #4. Once you will have array in #2 you can sort it and print whatever top words you need. #5. I am not sure the best way on this but you can play with array from #2. Thanks, Askar From: Pinedo, Ruben A [mailto:rapinedo at miners.utep.edu] Sent: Wednesday, October 16, 2013 2:49 PM To: tutor at python.org Subject: [Tutor] Help please I was given this code and I need to modify it so that it will: #1. Error handling for the files to ensure reading only .txt file #2. Print a range of top words... ex: print top 10-20 words #3. Print only the words with > 3 characters #4. Modify the printing function to print top 1 or 2 or 3 .... #5. How many unique words are there in the book of length 1, 2, 3 etc I am fairly new to python and am completely lost, i looked in my book as to how to do number one but i cannot figure out what to modify and/or delete to add the print selection. This is the code: import string def process_file(filename): hist = dict() fp = open(filename) for line in fp: process_line(line, hist) return hist def process_line(line, hist): line = line.replace('-', ' ') for word in line.split(): word = word.strip(string.punctuation + string.whitespace) word = word.lower() hist[word] = hist.get(word, 0) + 1 def common_words(hist): t = [] for key, value in hist.items(): t.append((value, key)) t.sort(reverse=True) return t def most_common_words(hist, num=100): t = common_words(hist) print 'The most common words are:' for freq, word in t[:num]: print freq, '\t', word hist = process_file('emma.txt') print 'Total num of Words:', sum(hist.values()) print 'Total num of Unique Words:', len(hist) most_common_words(hist, 50) Any help would be greatly appreciated because i am struggling in this class. Thank you in advance Respectfully, Ruben Pinedo Computer Information Systems College of Business Administration University of Texas at El Paso -------------- next part -------------- An HTML attachment was scrubbed... URL: From bill_77 at hotmail.com Thu Oct 17 17:36:06 2013 From: bill_77 at hotmail.com (Bill) Date: Thu, 17 Oct 2013 15:36:06 +0000 (UTC) Subject: [Tutor] keyboard interrupt References: <519D7025.8030108@davea.name> <519D77BE.9090506@davea.name> Message-ID: I know, way late to the party... Did you try Ctrl-Break? In Windows that is usually how you interrupt a program... From mail at timgolden.me.uk Thu Oct 17 17:46:55 2013 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 17 Oct 2013 16:46:55 +0100 Subject: [Tutor] keyboard interrupt In-Reply-To: References: <519D7025.8030108@davea.name> <519D77BE.9090506@davea.name> Message-ID: <5260066F.8070503@timgolden.me.uk> On 17/10/2013 16:36, Bill wrote: > > I know, way late to the party... > > Did you try Ctrl-Break? In Windows that is usually how you interrupt a > program... Take consolation from the fact that your five-month delay in replying isn't even close to the longest delay I've seen on a Python list. Someone responded, quite coherently and usefully, to a thread which fell within my area of competence. But I hadn't seen the original post go past. I queried the list as to whether there were delivery delays, and someone pointed out that the answer was responding to a post from some *six years* previously! (Which I think I'd answered at the time). TJG From alan.gauld at btinternet.com Thu Oct 17 19:29:28 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 17 Oct 2013 18:29:28 +0100 Subject: [Tutor] Help please In-Reply-To: References: Message-ID: On 17/10/13 14:37, Peter Otten wrote: > Alan Gauld wrote: > > [Ruben Pinedo] > >> def process_file(filename): >> hist = dict() >> fp = open(filename) >> for line in fp: >> process_line(line, hist) >> return hist >> or somebody is just sloppy. But neither work as expected >> right now. (Hint: Consider the return values of each) > > I fail to see the bug. > > process_line() mutates its `hist` argument, so there's no need to return > something. Or did you mean something else that escapes me? Oops, no, you are right, I forgot it's mutable. I don't like that style but that is not a bug... I was expecting to see a hist = process_line(...) and a return hist in there... My bad. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From bicofino at gmail.com Thu Oct 17 21:54:21 2013 From: bicofino at gmail.com (Danilo Chilene) Date: Thu, 17 Oct 2013 16:54:21 -0300 Subject: [Tutor] Parse text with python Message-ID: Hello, I have the text below: CSMP0097I 14.42.12 CPU-B SS-BSS SSU-AA IS-02 -LAL USER CONTROL FILE- MAXIMUM DEFINABLE USERS - 14999 MAXIMUM CONFIGURABLE USERS - 11790 CURRENT NUMBER USERS - 09692 USER FLUSH CRET TIME VALUE - 5 -LAL USER FILE- NAME UORD T/O O OXIT RXIT S MAX INUSE PCT ---------------- ---- --- - ---- ---- - --------- --------- --- J4IB 305 15 A 1700 6666 95 KEYWORDS - TA/J4IB CRTSST DYNTAC HSSPDB DELTAS - OBTAIN 0 RELEASE 0 FLUSH VALUE 0 DR CANDIDATE - N REPORT - N INUSE DATE - 10.17.2013 END OF DISPLAY How I can grab the number 6666? My idea is to find the number 1700(this number never changes) and count 6 chars and the print the next 4 chars. But I didn't find *how to count chars and print next* on python. Any ideas? Best Regards, Danilo F. Chilene -------------- next part -------------- An HTML attachment was scrubbed... URL: From fomcl at yahoo.com Thu Oct 17 22:14:02 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Thu, 17 Oct 2013 13:14:02 -0700 (PDT) Subject: [Tutor] Parse text with python In-Reply-To: References: Message-ID: <1382040842.78581.YahooMailNeo@web163803.mail.gq1.yahoo.com> On Thursday, October 17, 2013 9:54 PM, Danilo Chilene wrote: Hello, > >I have the text below: > >CSMP0097I 14.42.12 CPU-B SS-BSS? SSU-AA?? IS-02 >? >-LAL USER CONTROL FILE- >MAXIMUM DEFINABLE USERS??? - 14999 >MAXIMUM CONFIGURABLE USERS - 11790 >CURRENT NUMBER USERS -?????? 09692 >?USER FLUSH CRET TIME VALUE -??? 5 >-LAL USER FILE- >NAME???????????? UORD T/O O OXIT RXIT S??? MAX????? INUSE?? PCT >---------------- ---- --- - ---- ---- - --------- --------- --- >J4IB????????????? 305? 15???????????? A????? 1700????? 6666? 95 >?KEYWORDS - TA/J4IB CRTSST? DYNTAC? HSSPDB? >?DELTAS - OBTAIN??? 0? RELEASE??? 0 FLUSH VALUE??? 0 >?DR CANDIDATE - N? REPORT - N >?INUSE DATE - 10.17.2013 >? >END OF DISPLAY > > >How I can grab the number 6666? My idea is to find the number 1700(this number never changes) and count 6 chars and the print the next 4 chars. But I didn't find *how to count chars and print next* on python. > >Any ideas? This is one crude way, because the number 1700 might also be somewhere else in a line. Maybe (part of) that line could be written as a regular expression, e.g. J4IB *may* be [A-Z][0-9][A-Z]{2}\b >>> import re >>> lines = """CSMP0097I 14.42.12 CPU-B SS-BSS? SSU-AA?? IS-02 ? -LAL USER CONTROL FILE- MAXIMUM DEFINABLE USERS??? - 14999 MAXIMUM CONFIGURABLE USERS - 11790 CURRENT NUMBER USERS -?????? 09692 ?USER FLUSH CRET TIME VALUE -??? 5 -LAL USER FILE- NAME???????????? UORD T/O O OXIT RXIT S??? MAX????? INUSE?? PCT ---------------- ---- --- - ---- ---- - --------- --------- --- J4IB????????????? 305? 15???????????? A????? 1700????? 6666? 95 ?KEYWORDS - TA/J4IB CRTSST? DYNTAC? HSSPDB ?DELTAS - OBTAIN??? 0? RELEASE??? 0 FLUSH VALUE??? 0 ?DR CANDIDATE - N? REPORT - N ?INUSE DATE - 10.17.2013 ? END OF DISPLAY""".split("\n") >>> for line in lines: ??? record = re.split("\s+", line) ??? if len(record) >= 5 and record[4] == "1700": ??? ??? value_of_interest = record[5] >>> value_of_interest '6666' From breamoreboy at yahoo.co.uk Thu Oct 17 22:23:05 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 17 Oct 2013 21:23:05 +0100 Subject: [Tutor] Parse text with python In-Reply-To: References: Message-ID: On 17/10/2013 20:54, Danilo Chilene wrote: > Hello, > > I have the text below: > > CSMP0097I 14.42.12 CPU-B SS-BSS SSU-AA IS-02 > > -LAL USER CONTROL FILE- > MAXIMUM DEFINABLE USERS - 14999 > MAXIMUM CONFIGURABLE USERS - 11790 > CURRENT NUMBER USERS - 09692 > USER FLUSH CRET TIME VALUE - 5 > -LAL USER FILE- > NAME UORD T/O O OXIT RXIT S MAX INUSE PCT > ---------------- ---- --- - ---- ---- - --------- --------- --- > J4IB 305 15 A 1700 6666 95 > KEYWORDS - TA/J4IB CRTSST DYNTAC HSSPDB > DELTAS - OBTAIN 0 RELEASE 0 FLUSH VALUE 0 > DR CANDIDATE - N REPORT - N > INUSE DATE - 10.17.2013 > > END OF DISPLAY > > > How I can grab the number 6666? My idea is to find the number 1700(this > number never changes) and count 6 chars and the print the next 4 chars. > But I didn't find *how to count chars and print next* on python. > > Any ideas? > > Best Regards, > > Danilo F. Chilene > Use the string find method described here http://docs.python.org/3/library/stdtypes.html#string-methods to get an offset for 1700. Add 6 to it. Print a slice of 4 characters starting from this offset. If you don't know what slicing is please read the appropriate section here http://docs.python.org/3/tutorial/introduction.html#strings. -- Roses are red, Violets are blue, Most poems rhyme, But this one doesn't. Mark Lawrence From dyoo at hashcollision.org Thu Oct 17 22:37:28 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Thu, 17 Oct 2013 13:37:28 -0700 Subject: [Tutor] Parse text with python In-Reply-To: References: Message-ID: Do you have other domain-specific information about this text? Concretely: if you have another similar report, what parts will have to stay the same, and what parts might change? You want to make sure whatever you're using to anchor and search is based on something stable. Otherwise, your program may be too fragile to changes in the input, or worse, may be so general as to accidentally anchor to something that just happens to look like the text you're search for, but in the wrong place! The more you know about the general shape of the thing you're processing, the better chance you have to do a pattern matching that isn't too overly generic or specific. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bicofino at gmail.com Thu Oct 17 22:55:45 2013 From: bicofino at gmail.com (Danilo Chilene) Date: Thu, 17 Oct 2013 17:55:45 -0300 Subject: [Tutor] Parse text with python In-Reply-To: References: Message-ID: Hi, The part that always change is the 6666, it can be 1 digit or 4 digits. Example: 1. The part that never changes is the 1700. On Thu, Oct 17, 2013 at 5:37 PM, Danny Yoo wrote: > Do you have other domain-specific information about this text? > Concretely: if you have another similar report, what parts will have to > stay the same, and what parts might change? > > You want to make sure whatever you're using to anchor and search is based > on something stable. Otherwise, your program may be too fragile to changes > in the input, or worse, may be so general as to accidentally anchor to > something that just happens to look like the text you're search for, but in > the wrong place! > > The more you know about the general shape of the thing you're processing, > the better chance you have to do a pattern matching that isn't too overly > generic or specific. > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dyoo at hashcollision.org Thu Oct 17 23:37:15 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Thu, 17 Oct 2013 14:37:15 -0700 Subject: [Tutor] Parse text with python In-Reply-To: References: Message-ID: > > > The part that always change is the 6666, it can be 1 digit or 4 digits. > Example: 1. > The part that never changes is the 1700. > > You most likely need to be more specific with your pattern matching. Why should we expect no other numbers to be "1700"? I see several fields in the form that look like numbers. For example, you've got "305", "15", "95". Do those ever change? Do they have _any_ possibility to be "1700" in different instances of input? And you also have some kind of NAME field, under which is arbitrary text, it looks like. Is it at all possible for some thing to have a name like "J41B 1700 R2D2" or anything like that? I'm trying to impress the importance of considering the problem not just by looking at a single example. Doing so is almost certainly misleading. You probably need to consider at least three good examples to generalize a robust pattern here. What other examples have you considered? -------------- next part -------------- An HTML attachment was scrubbed... URL: From david at graniteweb.com Thu Oct 17 23:30:55 2013 From: david at graniteweb.com (David Rock) Date: Thu, 17 Oct 2013 16:30:55 -0500 Subject: [Tutor] Parse text with python In-Reply-To: References: Message-ID: <20131017213050.GH31987@wdfs.graniteweb.com> * Danilo Chilene [2013-10-17 17:55]: > Hi, > > The part that always change is the 6666, it can be 1 digit or 4 digits. > Example: 1. > The part that never changes is the 1700. I think the point is we have a hard time believing that 1700 will never change. What do you plan to do when it does down the line? It's generally a bad idea to focus on something that is obviously a data field as an item to key off of. That said, another approach you could take is to use split(). Split each line, check to see if 1700 is in it, then just grab the next field. Inherent dangers: INUSE field may be empty, so you will grab the wrong value 1700 might be somewhere other than where you expect it etc -- David Rock david at graniteweb.com From dyoo at hashcollision.org Thu Oct 17 23:50:53 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Thu, 17 Oct 2013 14:50:53 -0700 Subject: [Tutor] Parse text with python In-Reply-To: <20131017213050.GH31987@wdfs.graniteweb.com> References: <20131017213050.GH31987@wdfs.graniteweb.com> Message-ID: Yes. Concretely, I'm trying to see if it's appropriate to look at this: ############################################################### -LAL USER FILE- NAME UORD T/O O OXIT RXIT S MAX INUSE PCT ---------------- ---- --- - ---- ---- - --------- --------- --- J4IB 305 15 A 1700 6666 95 ############################################################### and think "Ah, I see a LAL User File, with the following structure: ...". If that's appropriate, then a potential structured question we can ask is: "Can we get the INUSE part of any LAL User File record whose MAX is 1700?" That's the kind of targeted question that has a good chance of capturing the actual intent of the user. Figure out intent first, and then hack at it. Doing it the other way around (hack first, then see if it actually matches the what we want) is almost certainly not right. :P -------------- next part -------------- An HTML attachment was scrubbed... URL: From cnsiva.in at gmail.com Thu Oct 17 17:49:49 2013 From: cnsiva.in at gmail.com (Siva Cn) Date: Thu, 17 Oct 2013 21:19:49 +0530 Subject: [Tutor] Tutor Digest, Vol 116, Issue 37 In-Reply-To: References: Message-ID: I guess this may help you -------------------------- import operator from string import whitespace as space from string import punctuation as punc class TextProcessing(object): """.""" def __init__(self): """.""" self.file = None self.sorted_list = [] self.words_and_occurence = {} def __sort_dict_by_value(self): """.""" sorted_in_rev = sorted(self.words_and_occurence.items(), key=lambda x: x[1]) self.sorted_list = sorted_in_rev[::-1] def __validate_words(self, word): """.""" if word in self.words_and_occurence: self.words_and_occurence[word] += 1 else: self.words_and_occurence[word] = 1 def __parse_file(self, file_name): """.""" fp = open(file_name, 'r') line = fp.readline() while line: split_line = [self.__validate_words(word.strip(punc + space)) \ for word in line.split() if word.strip(punc + space)] line = fp.readline() fp.close() def parse_file(self, file_name=None): """.""" if file_name is None: raise Exception("Please pass the file to be parsed") if not file_name.endswith(r".txt"): raise Exception("*** Error *** Not a valid text file") self.__parse_file(file_name) self.__sort_dict_by_value() def print_top_n(self, n): """.""" print "Top {0} words:".format(n), [self.sorted_list[i][0] for i in xrange(n)] def print_unique_words(self): """.""" print "Unique words:", [self.sorted_list[i][0] for i in xrange(len(self.sorted_list))] if __name__ == "__main__": """.""" obj = TextProcessing() obj.parse_file(r'test_input.txt') obj.print_top_n(4) obj.print_unique_words() *-- Regards --* * * * Siva Cn* *Python Developer* * * *+91 9620339598* *http://www.cnsiva.com* --------------------- On Thu, Oct 17, 2013 at 7:58 PM, wrote: > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > https://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Re: Help please (Alan Gauld) > 2. Re: Help please (Peter Otten) > 3. Re: Help please (Dominik George) > 4. Re: Help please (Kengesbayev, Askar) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Thu, 17 Oct 2013 14:13:07 +0100 > From: Alan Gauld > To: tutor at python.org > Subject: Re: [Tutor] Help please > Message-ID: > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 16/10/13 19:49, Pinedo, Ruben A wrote: > > I was given this code and I need to modify it so that it will: > > > > #1. Error handling for the files to ensure reading only .txt file > > I'm not sure what is meant here since your code only ever opens > 'emma.txt', so it is presumably a text file... Or are you > supposed to make the filename a user provided value maybe > (using raw_input maybe?) > > > #2. Print a range of top words... ex: print top 10-20 words > > I assume 'top' here means the most common? Whoever is writing the > specification for this problem needs to be a bit more specific > in their definitions. > > If so you need to fix the bugs in process_line() and > process_file(). I don;t know if these are deliberate bugs > or somebody is just sloppy. But neither work as expected > right now. (Hint: Consider the return values of each) > > Once you've done that you can figure out how to extract > the required number of words from your (unsorted) dictionary. > and put that in a reporting function and print the output. > You might be able to use the two common words functions, > although watch out because they don't do exactly what > you want and one of them is basically broken... > > > #3. Print only the words with > 3 characters > > Modify the above to discard words of 3 letters or less. > > > #4. Modify the printing function to print top 1 or 2 or 3 .... > > I assume this means take a parameter that speciffies the > number of words to print. Or it could be the length of > word to ignore. Again the specification is woolly > In either case its a small modification to your > reporting function. > > > #5. How many unique words are there in the book of length 1, 2, 3 etc > > This is slicing the data slightly differently but > again not that different to the earlier requirement. > > > I am fairly new to python and am completely lost, i looked in my book as > > to how to do number one but i cannot figure out what to modify and/or > > delete to add the print selection. This is the code: > > You need to modify the two brokemn functions and add a > new reporting function. (Despite the reference to a > printing function I'd suggest keeping the data extraction > and printing seperate. > > > import string > > > > def process_file(filename): > > hist = dict() > > fp = open(filename) > > for line in fp: > > process_line(line, hist) > > return hist > > > > def process_line(line, hist): > > line = line.replace('-', ' ') > > for word in line.split(): > > word = word.strip(string.punctuation + string.whitespace) > > word = word.lower() > > hist[word] = hist.get(word, 0) + 1 > > > > def common_words(hist): > > t = [] > > for key, value in hist.items(): > > t.append((value, key)) > > t.sort(reverse=True) > > return t > > > > def most_common_words(hist, num=100): > > t = common_words(hist) > > print 'The most common words are:' > > for freq, word in t[:num]: > > print freq, '\t', word > > hist = process_file('emma.txt') > > print 'Total num of Words:', sum(hist.values()) > > print 'Total num of Unique Words:', len(hist) > > most_common_words(hist, 50) > > > > Any help would be greatly appreciated because i am struggling in this > > class. Thank you in advance > > hth > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.flickr.com/photos/alangauldphotos > > > > ------------------------------ > > Message: 2 > Date: Thu, 17 Oct 2013 15:37:49 +0200 > From: Peter Otten <__peter__ at web.de> > To: tutor at python.org > Subject: Re: [Tutor] Help please > Message-ID: > Content-Type: text/plain; charset="ISO-8859-1" > > Alan Gauld wrote: > > [Ruben Pinedo] > > > def process_file(filename): > > hist = dict() > > fp = open(filename) > > for line in fp: > > process_line(line, hist) > > return hist > > > > def process_line(line, hist): > > line = line.replace('-', ' ') > > > > for word in line.split(): > > word = word.strip(string.punctuation + string.whitespace) > > word = word.lower() > > > > hist[word] = hist.get(word, 0) + 1 > > [Alan Gauld] > > > If so you need to fix the bugs in process_line() and > > process_file(). I don;t know if these are deliberate bugs > > or somebody is just sloppy. But neither work as expected > > right now. (Hint: Consider the return values of each) > > I fail to see the bug. > > process_line() mutates its `hist` argument, so there's no need to return > something. Or did you mean something else that escapes me? > > > > ------------------------------ > > Message: 3 > Date: Thu, 17 Oct 2013 16:17:27 +0200 > From: Dominik George > To: Todd Matsumoto ,tutor at python.org > Subject: Re: [Tutor] Help please > Message-ID: > Content-Type: text/plain; charset=UTF-8 > > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA512 > > Todd Matsumoto schrieb: > >> #1. Error handling for the files to ensure reading only .txt file > >Look up exceptions. > >Find out what the string method endswith() does. > > One should note that the OP probably meant files of the type text/plain > rather than .txt files. File name extensions are a convenience to identify > a file on first glance, but they tell absolutely nothing about the contents. > > So, look up MIME types as well ;)! > > - -nik > -----BEGIN PGP SIGNATURE----- > Version: APG v1.0.8-fdroid > > iQFNBAEBCgA3BQJSX/F3MBxEb21pbmlrIEdlb3JnZSAobW9iaWxlIGtleSkgPG5p > a0BuYXR1cmFsbmV0LmRlPgAKCRAvLbGk0zMOJZxHB/9TGh6F1vRzgZmSMHt48arc > jruTRfvOK9TZ5MWm6L2ZpxqKr3zBP7KSf1ZWSeXIovat9LetETkEwZ9bzHBuN8Ve > m8YsOVX3zR6VWqGkRYYer3MbWo9DCONlJUKGMs/qjB180yxxhQ12Iw9WAHqam1Ti > n0CCWsf4l5B3WBe+t2aTOlQNmo//6RuBK1LfCrnYX0XV2Catv1075am0KaTvbxfB > rfHHnR4tdIYmZ8P/SkO3t+9JzJU9e+H2W90++K9EkMTBJxUhsa4AuZIEr8WqEfSe > EheQMUp23tlMgKRp6UHiRJBljEsQJ0XFuYa+zj6hXCXoru/9ReHTRWcvJEpfXxEC > =hJ0m > -----END PGP SIGNATURE----- > > > > ------------------------------ > > Message: 4 > Date: Thu, 17 Oct 2013 14:21:17 +0000 > From: "Kengesbayev, Askar" > To: "Pinedo, Ruben A" , "tutor at python.org" > > Subject: Re: [Tutor] Help please > Message-ID: > < > 6FAD14604B087B438F6FF64D9875A40C68F5ADCA at atl1ex10mbx4.corp.etradegrp.com> > > Content-Type: text/plain; charset="us-ascii" > > Ruben, > > #1 you can try something like this > try: > with open('my_file.txt') as file: > pass > except IOError as e: > print "Unable to open file" #Does not exist or you do not have > read permission > > #2. I would try to use regular expression push words to array and then you > can manipulate array. Not sure if it is efficient way but it should work. > #3 . easy way would be to use regular expression. Re module. > #4. Once you will have array in #2 you can sort it and print whatever top > words you need. > #5. I am not sure the best way on this but you can play with array from > #2. > > Thanks, > Askar > > From: Pinedo, Ruben A [mailto:rapinedo at miners.utep.edu] > Sent: Wednesday, October 16, 2013 2:49 PM > To: tutor at python.org > Subject: [Tutor] Help please > > I was given this code and I need to modify it so that it will: > > #1. Error handling for the files to ensure reading only .txt file > #2. Print a range of top words... ex: print top 10-20 words > #3. Print only the words with > 3 characters > #4. Modify the printing function to print top 1 or 2 or 3 .... > #5. How many unique words are there in the book of length 1, 2, 3 etc > > I am fairly new to python and am completely lost, i looked in my book as > to how to do number one but i cannot figure out what to modify and/or > delete to add the print selection. This is the code: > > > import string > > def process_file(filename): > hist = dict() > fp = open(filename) > for line in fp: > process_line(line, hist) > return hist > > def process_line(line, hist): > line = line.replace('-', ' ') > > for word in line.split(): > word = word.strip(string.punctuation + string.whitespace) > word = word.lower() > > hist[word] = hist.get(word, 0) + 1 > > def common_words(hist): > t = [] > for key, value in hist.items(): > t.append((value, key)) > > t.sort(reverse=True) > return t > > def most_common_words(hist, num=100): > t = common_words(hist) > print 'The most common words are:' > for freq, word in t[:num]: > print freq, '\t', word > > hist = process_file('emma.txt') > print 'Total num of Words:', sum(hist.values()) > print 'Total num of Unique Words:', len(hist) > most_common_words(hist, 50) > > Any help would be greatly appreciated because i am struggling in this > class. Thank you in advance > > Respectfully, > > Ruben Pinedo > Computer Information Systems > College of Business Administration > University of Texas at El Paso > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20131017/ea525e7b/attachment.html > > > > ------------------------------ > > Subject: Digest Footer > > _______________________________________________ > Tutor maillist - Tutor at python.org > https://mail.python.org/mailman/listinfo/tutor > > > ------------------------------ > > End of Tutor Digest, Vol 116, Issue 37 > ************************************** > -------------- next part -------------- An HTML attachment was scrubbed... URL: From zaidsaeedzaid at gmail.com Thu Oct 17 22:09:22 2013 From: zaidsaeedzaid at gmail.com (Zaid Saeed) Date: Thu, 17 Oct 2013 16:09:22 -0400 Subject: [Tutor] Weird Python Error Message-ID: <000001cecb74$c5daaa90$518fffb0$@gmail.com> First and foremost, here is the code: """ Player Car """ import pygame, random pygame.init() screen = pygame.display.set_mode((640, 480)) class RedCar(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load("red.png") self.image = pygame.transform.scale(self.image,(50,75)) self.rect = self.image.get_rect() if not pygame.mixer: print("problem with sound") else: pygame.mixer.init() self.sndYay = pygame.mixer.Sound("yay.ogg") self.sndThunder = pygame.mixer.Sound("thunder.ogg") def update(self): mousex, mousey = pygame.mouse.get_pos() self.rect.center = (mousex, 430) class GasCan(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load("gas.png") self.image = pygame.transform.scale(self.image,(50, 50)) self.image = self.image.convert_alpha() self.rect = self.image.get_rect() self.reset() self.dy = 5 def update(self): self.rect.centery += self.dy if self.rect.top > screen.get_height(): self.reset() def reset(self): self.rect.top = 0 self.rect.centerx = random.randrange(0, screen.get_width()) class YellowCar(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load("yellow.png") self.image = pygame.transform.scale(self.image,(50, 75)) self.rect = self.image.get_rect() def update(self): self.rect.centery += self.dy #self.rect.centery += random.randrange(5, 20) if self.rect.top > screen.get_height(): self.reset() def reset(self): self.rect.bottom = 0 self.rect.centerx = random.randrange(190, screen.get_width()) self.dy = random.randrange(10, 30) class Bush(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load("bush.png") self.image = pygame.transform.scale(self.image,(50, 50)) self.rect = self.image.get_rect() def update(self): self.rect.centery += 10 if self.rect.top > screen.get_height(): self.reset() def reset(self): self.rect.bottom = 0 self.rect.centerx = random.randrange(0, 150) class Road(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load("road.png") #self.image = pygame.transform.scale(self.image,(640, 480)) self.rect = self.image.get_rect() self.dy = 10 self.reset() def update(self): self.rect.bottom += self.dy if self.rect.top >= 0: self.reset() def reset(self): self.rect.bottom = screen.get_height() class Scoreboard(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.lives = 11 self.score = 0 self.level = 0 self.font = pygame.font.SysFont("None", 50) def update(self): self.text = "Car: %d, score: %d, level: %d" % (self.lives, self.score, self.level) self.image = self.font.render(self.text, 1, (255, 255, 0)) self.rect = self.image.get_rect() def Game(): pygame.display.set_caption("Car") background = pygame.Surface(screen.get_size()) background.fill((0, 0, 0)) screen.blit(background, (0, 0)) redCar = RedCar() gas = GasCan() yellowCar1 = YellowCar() yellowCar2 = YellowCar() yellowCar3 = YellowCar() yellowCar4 = YellowCar() yellowCar5 = YellowCar() bush1 = Bush() bush2 = Bush() bush3 = Bush() road = Road() scoreboard = Scoreboard() goodSprites = pygame.sprite.Group(gas, road, redCar) scoreSprite = pygame.sprite.Group(scoreboard) clock = pygame.time.Clock() keepGoing = True while keepGoing: clock.tick(30) pygame.mouse.set_visible(False) for event in pygame.event.get(): if event.type == pygame.QUIT: keepGoing = False if scoreboard.score < 500: badSprites = pygame.sprite.Group(yellowCar1, yellowCar2, yellowCar3, bush1) scoreboard.level = 1 elif scoreboard.score < 1000: badSprites = pygame.sprite.Group(yellowCar1, yellowCar2, yellowCar3, yellowCar4, bush1, bush2) scoreboard.level = 2 elif scoreboard.score < 1500: badSprites = pygame.sprite.Group(yellowCar1, yellowCar2, yellowCar3, yellowCar4, yellowCar5, bush1, bush2, bush3) scoreboard.level = 3 if redCar.rect.colliderect(gas.rect): redCar.sndYay.play() gas.reset() scoreboard.score += 100 if scoreboard.score % 5 == 0: scoreboard.lives + 1 hitCar = pygame.sprite.spritecollide(redCar, badSprites, False) if hitCar: redCar.sndThunder.play() scoreboard.lives -= 1 if scoreboard.lives <= 0: keepGoing = False for theCar in hitCar: theCar.reset() # allSprites.clear(screen, background) goodSprites.update() badSprites.update() scoreSprite.update() goodSprites.draw(screen) badSprites.draw(screen) scoreSprite.draw(screen) pygame.display.flip() pygame.mouse.set_visible(True) return scoreboard.score def instructions(score): redCar = RedCar() road = Road() allSprites = pygame.sprite.Group(road, redCar) insFont = pygame.font.SysFont(None, 50) instructions = ( "Car Survival. Last score: %d" % score , "Instructions: Drive your car,", "and avoid cars and bushes.", "", "Gain points by driving over the gas cans.", "", "good luck!", "", "click to start, escape to quit..." ) insLabels = [] # Create a rendered list of instructions, ready for display for line in instructions: tempLabel = insFont.render(line, 1, (255, 255, 0)) insLabels.append(tempLabel) keepGoing = True clock = pygame.time.Clock() pygame.mouse.set_visible(False) while keepGoing: clock.tick(30) for event in pygame.event.get(): if event.type == pygame.QUIT: keepGoing = False donePlaying = True # Check for a mouse click if event.type == pygame.MOUSEBUTTONDOWN: keepGoing = False donePlaying = False # .... or a quit elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: keepGoing = False donePlaying = True allSprites.update() allSprites.draw(screen) # Display the instructions for i in range(len(insLabels)): screen.blit(insLabels[i], (50, 30*i)) pygame.display.flip() pygame.mouse.set_visible(True) return donePlaying def main(): donePlaying = False score = 0 while not donePlaying: donePlaying = instructions(score) if not donePlaying: score = Game() pygame.quit() if __name__ == "__main__": main() Now for some reason, it is saying that YellowCar doesn't have a dy variable, when it clearly does. This only happens when it is going from level 1 to level 2, I don't know what happens after level 2 because the program keeps giving me the error. Any help would be appreciated. P.S. I am new to the python language and this is my first game. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dyoo at hashcollision.org Fri Oct 18 03:02:53 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Thu, 17 Oct 2013 18:02:53 -0700 Subject: [Tutor] Weird Python Error In-Reply-To: <000001cecb74$c5daaa90$518fffb0$@gmail.com> References: <000001cecb74$c5daaa90$518fffb0$@gmail.com> Message-ID: Hi Zaid, Your YellowCar will have one once its reset() has been called. However, I don't see it in __init__(), so there might be a period of time where it won't have one. I haven't traced through possible code paths where this happens, but I suspect one of them may. One example may be: c = car() car.update() and that would trigger the kind of error you're seeing. Normally, you want to give all attributes some kind of value in __init__(), just to keep this sort of weird situation from happening. All your other sprites appear to set a 'dy' in their __init__, so symmetry seems appropriate. > ** > > *Now for some reason, it is saying that YellowCar doesn?t have a dy > variable, when it clearly does. This only happens when it is going from > level 1 to level 2, I don?t know what happens after level 2 because the > program keeps giving me the error. Any help would be appreciated.* > > ** > In the future, also make sure to copy and paste the exact error message and stack trace and show that too. Not only does it help explain the problem, but also acts as a way for tutors to make sure they're chasing the same problem as the one you're interested in. Otherwise, we might be looking into other problems that are entirely unrelated to what you're concerned about. It's a matter of making it easier for tutors to reproduce what you're seeing. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Oct 18 10:42:52 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 18 Oct 2013 09:42:52 +0100 Subject: [Tutor] Weird Python Error In-Reply-To: <000001cecb74$c5daaa90$518fffb0$@gmail.com> References: <000001cecb74$c5daaa90$518fffb0$@gmail.com> Message-ID: On 17/10/13 21:09, Zaid Saeed wrote: > class YellowCar(pygame.sprite.Sprite): > > def __init__(self): > pygame.sprite.Sprite.__init__(self) > self.image = pygame.image.load("yellow.png") > self.image = pygame.transform.scale(self.image,(50, 75)) > self.rect = self.image.get_rect() > > def update(self): > self.rect.centery += self.dy > if self.rect.top > screen.get_height(): > self.reset() > > def reset(self): > self.rect.bottom = 0 > self.rect.centerx = random.randrange(190, screen.get_width()) > self.dy = random.randrange(10, 30) Update uses dy but it is only set in reset(). If you call update before reset you will get the error. Now in your Game() code we find: if hitCar: redCar.sndThunder.play() scoreboard.lives -= 1 if scoreboard.lives <= 0: keepGoing = False for theCar in hitCar: theCar.reset() # allSprites.clear(screen, background) goodSprites.update() badSprites.update() scoreSprite.update() So any updated car not in hitcar will not have been reset and so you will have an error. It's best (for your sanity) to initialise all class attributes in __init__. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From corinne.landers at live.com Sat Oct 19 02:13:27 2013 From: corinne.landers at live.com (Corinne Landers) Date: Sat, 19 Oct 2013 11:13:27 +1100 Subject: [Tutor] Nested lists help Message-ID: Hi, I'm trying to create a 3D grid, so I'm using a list of list of lists. However, if I try to make a change to one value, eggrid[0][1][2] = 3, It doesn't just change list[0], it change the 2nd element in the 1st list of every list? I think it's because I've copied lists to get the grid, but could you help me fix this? This is my code, that takes an x,y,z value from user. self.grid_x = xself.grid_y = yself.grid_z = z self.grid = []self.grid2D = [] for i in range(self.grid_y): row = [0]*x self.grid2D.append(row) for k in range(z): self.grid.append(self.grid2D) #Creates list of x by y grids Thank you so muchCorrine -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Sat Oct 19 02:53:29 2013 From: steve at alchemy.com (Steve Willoughby) Date: Fri, 18 Oct 2013 17:53:29 -0700 Subject: [Tutor] Nested lists help In-Reply-To: References: Message-ID: <4153DECA-BED5-4A9F-9F0A-C8968726117C@alchemy.com> On 18-Oct-2013, at 17:13, Corinne Landers wrote: > self.grid_x = x > self.grid_y = y > self.grid_z = z > > self.grid = [] > self.grid2D = [] > So here you create a list, self.grid2D. > for i in range(self.grid_y): > row = [0]*x > self.grid2D.append(row) > Here you are adding more elements to that list. > for k in range(z): > self.grid.append(self.grid2D) #Creates list of x by y grids > But here you keep appending self.grid2D multiple times to self.grid. Not z different copies, but they're all the exact name list object, referenced multiple times. -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Sat Oct 19 06:42:58 2013 From: davea at davea.name (Dave Angel) Date: Sat, 19 Oct 2013 04:42:58 +0000 (UTC) Subject: [Tutor] Nested lists help References: Message-ID: On 18/10/2013 20:13, Corinne Landers wrote: > --> >
Hi, 

I'm trying to create a 3D grid, so I'm using a list of list of lists. 
However, if I try to make a change to one value, eg
grid[0][1][2] = 3, 
It doesn't just change list[0], it change the 2nd element in the 1st list of every list? 
I think it's because I've copied lists to get the grid, but could you help me fix this? 

This is my code, that takes an x,y,z value from user. 

self.grid_x = x
self.grid_y = y
self.grid_z = z

self.grid = []
self.grid2D = []

for i in range(self.grid_y):
            row = [0]*x
            self.grid2D.append(row)

for k in range(z):
            self.grid.append(self.grid2D) #Creates list of x by y grids

Thank you so much
Corrine
> > > Please don't post using html mail. Use text email for a text newsgroup. Not only does it waste space (since the message essentially has two copies of what you type, the html part being much larger than what you typed), but it also can frequently lose all the indentation (as happened to this message in your email program). Indentation matters in Python. Your lines are also run together in places, like the first line of your code, which looks like this: self.grid_x = xself.grid_y = yself.grid_z = z The problem you have, as you have guessed, is that you're making references to the same list multiple times. So when that list is changed, it changes all references. You need to have every item in your nested list be unique. The simplest change is to use myotherlist = mylist[:] to make a copy of each element of the list. That's not necessary at the innermost level, since integers are immutable. I'm not sure what to make of your code, since you say you want a 3d grid, but you're only making 2d. But to make a 3d list, you might use something like (untested): my_3d_list = [] for i in range(x): temp1 = [] for j in range(y): temp2 = [] for k in range(z): temp2.append(0) temp1.append(temp2) my_3d_list.append(temp1) The innermost loop could be replaced by temp2 = [0]*z but I like the symmetry of the way I wrote it. -- DaveA From tr.manish at gmail.com Sat Oct 19 16:29:13 2013 From: tr.manish at gmail.com (Manish Tripathi) Date: Sat, 19 Oct 2013 19:59:13 +0530 Subject: [Tutor] Reading CSV files in Pandas Message-ID: I am trying to import a csv file in Pandas but it throws an error. The format of the data when opened in notepad++ is as follows with first row being column names: "End Customer Organization ID,End Customer Organization Name,End Customer Top Parent Organization ID,End Customer Top Parent Organization Name,Reseller Top Parent ID,Reseller Top Parent Name,Business,Rev Sum Division,Rev Sum Category,Product Family,Version,Pricing Level,Summary Pricing Level,Detail Pricing Level,MS Sales Amount,MS Sales Licenses,Fiscal Year,Sales Date""11027676,Baroda Western Uttar Pradesh Gramin Bankgfhgfnjgfnmjmhgmghmghmghmnghnmghnmhgnmghnghngh,4078446,Bank Of Barodadfhhgfjyjtkyukujkyujkuhykluiluilui;iooi';po'fserwefvegwegf,1809012,""Hcl Infosystems Ltd - Partnerdghftrutyhb frhywer5y5tyu6ui7iukluyj,lgjmfgnhfrgweffw"",Server & CALsdgrgrfgtrhytrnhjdgthjtyjkukmhjmghmbhmgfngdfbndfhtgh,SQL Server & CALdfhtrhtrgbhrghrye5y45y45yu56juhydsgfaefwe,SQL CALdhdfthtrutrjurhjethfdehrerfgwerweqeadfawrqwerwegtrhyjuytjhyj,SQL CALdtrye45y3t434tjkabcjkasdhfhasdjkcbaksmjcbfuigkjasbcjkasbkdfhiwh,2005,Openfkvgjesropiguwe90fujklascnioawfy98eyfuiasdbcvjkxsbhg,Open Lklbjdfoigueroigbjvwioergyuiowerhgosdhvgfoisdhyguiserhguisrh,""Open Stddfm,vdnoghioerivnsdflierohgushdfovhsiodghuiohdbvgsjdhgouiwerho"",125.85,1,FY07,12/28/2006""12835756,Uttam Strips Pvt Ltd,12835756,Uttam Strips Pvt Ltd,12565538,Redington C/O Fortis Financial Services Ltd,MBS,Dynamics ERP,Dynamics NAV,Dynamics NAV Business Essentials,Non-specific,Other,MBS SA,MBS New Customer Enhanc. Def,0,0,FY09,9/15/2008""12233135,Bhagwan Singh Tondon,12233135,Bhagwan Singh Tondon,2652941,H B S Systems Pvt Ltd,Server & CAL,SQL Server & CAL,SQL CAL,SQL CAL,Non-specific,Open,Open L&SA,Deferred Open L&SA - New,0,0,FY09,9/15/2008""11602305,Maya Academy Of Advanced Cinematics,9750934,Maya Entertainment Ltd,336146,Embee Software Pvt Ltd,Server & CAL,Windows Server & CAL,Windows Server HPC,Windows Compute Cluster Server,Non-specific,Open,Open V/MYO - Rec,OLV Perpet L&SA Recur-Def,0,0,FY09,9/25/2008""13336009,Remiel Softech Solution Pvt Ltd,13336009,Remiel Softech Solution Pvt Ltd,13335482,Redington C/O Remiel Softech Solutions Pvt Ltd,MBS,Dynamics ERP,Dynamics NAV,Dynamics NAV Business Essentials,Non-specific,Other,MBS SA,MBS New Customer Enhanc. Def,0,0,FY09,12/23/2008""7872800,Science Application International Corporation,2839760,GOVERNMENT OF KARNATAKA,10237455,Cubic Computing P.L,Server & CAL,SQL Server & CAL,SQL Server Standard,SQL Server Standard Edition,Non-specific,Open,Open SA/UA,Deferred Open SA - Renewal,0,0,FY09,1/15/2009""13096361,Pratham Software Pvt Ltd,13096361,Pratham Software Pvt Ltd,10133086,Krap Computer,Information Worker,Office,Office Standard / Basic,Office Standard,2007,Open,Open L,Open Std,7132.44,28,FY09,9/24/2008""12192276,Texmo Precision Castings,12192276,Texmo Precision Castings,4059430,Quadra Systems. - Partner,Server & CAL,Windows Server & CAL,Windows Standard Server,Windows Server Standard,Non-specific,Open,Open L&SA,Deferred Open L&SA - New,0,0,FY09,11/15/2008" *Kindly note that the same file when double clicked in the csv format opens in excel with comma separated values BUT with NO quotation marks in each line as shown in notepad++.* I have used encoding as UTF-8 which gives the following error: UnicodeDecodeError: 'utf-8' codec can't decode byte 0x91 in position 13: invalid start byte Then used encoding='cp1252' first and then tried with latin1. df=pd.read_csv(filename,encoding='cp1252') or df=pd.read_csv(filename,encoding='latin1') With both the encodings it didn't give any error and the data got imported but as one single column and not as different columns. Does it have to do with the "" marks present before each line in the data? I had a similar csv file with comma separated values, but that didn't have double quotation marks in each line and that got imported correctly both with cp1252 and latin1. But not for UTF-8 even though the file was saved in utf8 format in notepad++. But in this case utf8 doesnt work as usual and other two import it as single column. Please advise. Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Oct 20 00:40:21 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 19 Oct 2013 23:40:21 +0100 Subject: [Tutor] Reading CSV files in Pandas In-Reply-To: References: Message-ID: On 19/10/13 15:29, Manish Tripathi wrote: > I am trying to import a csv file in Pandas but it throws an error. This is the second time I've seen pandas mentioned recedntly I really must go and look it up to find out what it is... Meanwhile can you clarify what you mean by importing the csv file? Are you using a Pandas facility to do this? Or are you using Python code? And if the latter are you using the csv module - striongly recommended for any csv work.... > > |df=pd.read_csv(filename,encoding='cp1252') I'm assuming from this it is some kind of Pandas feature? Have you tried asking on a Pandas mailing list/forum? This group is targetted at standard library and core language, so it will be a matter of luck if you find anyone who uses pandas and can help. ....OK, I found the Pandas page, it's for data analysis/modelling. It has a StackOverflow link for asking questions so if you don't get help here you should try that next. I'm assuming you have read the docs on csv input here: http://pandas.pydata.org/pandas-docs/stable/io.html#io-read-csv-table There are way too many options for me to read through so I'll leave it to those who know! HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From breamoreboy at yahoo.co.uk Sun Oct 20 01:16:28 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 20 Oct 2013 00:16:28 +0100 Subject: [Tutor] Reading CSV files in Pandas In-Reply-To: References: Message-ID: On 19/10/2013 23:40, Alan Gauld wrote: > This is the second time I've seen pandas mentioned recedntly I really > must go and look it up to find out what it is... Just started out myself at http://pandas.pydata.org/ and at first glance it seems quite awesome. -- Roses are red, Violets are blue, Most poems rhyme, But this one doesn't. Mark Lawrence From breamoreboy at yahoo.co.uk Sun Oct 20 02:17:17 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 20 Oct 2013 01:17:17 +0100 Subject: [Tutor] Reading CSV files in Pandas In-Reply-To: References: Message-ID: On 19/10/2013 15:29, Manish Tripathi wrote: You are far more likely to get a response to the identical question that you've already asked on stackoverflow than you are here. -- Roses are red, Violets are blue, Most poems rhyme, But this one doesn't. Mark Lawrence From tr.manish at gmail.com Sun Oct 20 08:53:52 2013 From: tr.manish at gmail.com (Manish Tripathi) Date: Sun, 20 Oct 2013 12:23:52 +0530 Subject: [Tutor] Reading CSV files in Pandas In-Reply-To: References: Message-ID: Thanks Mark. I have already asked this question on StackOverflow but to no avail. So thought of asking here. On Sun, Oct 20, 2013 at 5:47 AM, Mark Lawrence wrote: > On 19/10/2013 15:29, Manish Tripathi wrote: > > You are far more likely to get a response to the identical question that > you've already asked on stackoverflow than you are here. > > > -- > Roses are red, > Violets are blue, > Most poems rhyme, > But this one doesn't. > > Mark Lawrence > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jennyallar at gmail.com Sun Oct 20 06:20:47 2013 From: jennyallar at gmail.com (Jenny Allar) Date: Sun, 20 Oct 2013 00:20:47 -0400 Subject: [Tutor] Passing arguments? Message-ID: I've written the code below the assignment, and I think I have everything covered in terms of asking the user for the information I need and somehow calculating costs, but I'm just ridiculously confused on the order and placement of the functions and components of this program- specifically the shiprate variable. Thank you in advance for any help. This is my assignment: Write a program that asks a user for the name of a product that they are ordering online and its weight. The program must calculate the cost of shipping the product using the following cost structure. If it weighs less than 10 pounds the cost is $1.50 per pound, if it is 10 pounds or more and less than 25 pounds then the cost is $1.45 per pound. If the weight is 25 pounds or more the cost is $1.40 per pound. You may get the data from the user in main. You must print the name of the product, the weight and the cost of shipping in a separate function. **********NOTE: ALWAYS USE ?WHILE LOOPS? To Validate******************** * * # This program uses an if-else statement # It asks for the name of a product and the weight of that product. # It then determines the shipping cost as defined by the weight. # # Variable Type Purpose # product string hold for name of product # weight float hold for weight of product # def main (): product = input("Please enter the name of the product: ") weight = int(input("Please enter the weight of the product: ")) print('Product:', product) print('Weight:', weight) if weight <= 10: shiprate = 1.5 calc_weight_small(weight, shiprate) elif weight >= 10 and weight <= 25: shiprate = 1.45 calc_weight_medium(weight, shiprate) else: shiprate = 1.4 calc_weight_large(weight, shiprate) # Calculate shipping cost for product less than 10 pounds def cacl_weight_small(weight, shiprate): shiprate = 1.5 total = weight * shiprate # Calculate shipping cost for product between 10 and 25 pounds. def calc_weight_medium(weight, shiprate): shiprate = 1.45 total = weight * shiprate # Calculate shipping cost for product over 25 pounds. def calc_weight_large(weight, shiprate): shiprate = 1.4 total = weight * shiprate # #This function calculates and prints the total cost # based on the weight category the product falls into # Variable Type Purpose # weight float weight of product # shiprate float cost per pound # total float total cost to ship product # print () print ("The cost to ship", product, "is: $", format (total, '9,.2f')) main () -------------- next part -------------- An HTML attachment was scrubbed... URL: From nik at naturalnet.de Sun Oct 20 10:31:54 2013 From: nik at naturalnet.de (Dominik George) Date: Sun, 20 Oct 2013 10:31:54 +0200 Subject: [Tutor] Passing arguments? In-Reply-To: References: Message-ID: <20131020083154.GF2559@keks.naturalnet.de> Hi, > I've written the code below the assignment, and I think I have everything > covered in terms of asking the user for the information I need and somehow > calculating costs, but I'm just ridiculously confused on the order and > placement of the functions and components of this program- specifically the > shiprate variable. Thank you in advance for any help. so, you are confused. Cool ?! But, what is your question ;)? Your subject suggests it has something to do with passing arguments to a script, but, umm? I do not see what this has to do with the rest of your mail ;). Also, please reformat your code in a readable manner, i.e. remove the many empty lines, reformat function calls according to style guide, etc. Cheers, Nik -- Auf welchem Server liegt das denn jetzt?? Wenn es nicht ?bers Netz kommt bei Hetzner, wenn es nicht gelesen wird bei STRATO, wenn es klappt bei manitu. PGP-Fingerprint: 3C9D 54A4 7575 C026 FB17 FD26 B79A 3C16 A0C4 F296 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 905 bytes Desc: Digital signature URL: From nik at naturalnet.de Sun Oct 20 10:34:17 2013 From: nik at naturalnet.de (Dominik George) Date: Sun, 20 Oct 2013 10:34:17 +0200 Subject: [Tutor] Auto-response for your message to the "Tutor" mailing list In-Reply-To: References: Message-ID: <20131020083417.GG2559@keks.naturalnet.de> > Your message for tutor at python.org, the Python programming tutor list, > has been received and is being delivered. This automated response is > sent to those of you new to the Tutor list, to point out a few > resources that can help with answering your own questions, or improve > the chances of getting a useful answer from the other subscribers. Thank you, but? ?I have been a member of the list for many weeks now and have posted quite a few messages. Is there a reason I am receiving this friendly greeter more than once? -nik -- # apt-assassinate --help Usage: apt-assassinate [upstream|maintainer] PGP-Fingerprint: 3C9D 54A4 7575 C026 FB17 FD26 B79A 3C16 A0C4 F296 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 905 bytes Desc: Digital signature URL: From breamoreboy at yahoo.co.uk Sun Oct 20 11:20:24 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 20 Oct 2013 10:20:24 +0100 Subject: [Tutor] Passing arguments? In-Reply-To: <20131020083154.GF2559@keks.naturalnet.de> References: <20131020083154.GF2559@keks.naturalnet.de> Message-ID: On 20/10/2013 09:31, Dominik George wrote: > Hi, > > Also, please reformat your code in a readable manner, i.e. remove the > many empty lines, reformat function calls according to style guide, etc. > > Cheers, > Nik > Not another case of the infamous double spaced google disease? If yes it can be cured by reading, digesting and actioning this https://wiki.python.org/moin/GoogleGroupsPython. Better still use a decent email client like Thunderbird. -- Roses are red, Violets are blue, Most poems rhyme, But this one doesn't. Mark Lawrence From chigga101 at gmail.com Sun Oct 20 12:30:31 2013 From: chigga101 at gmail.com (Matthew Ngaha) Date: Sun, 20 Oct 2013 11:30:31 +0100 Subject: [Tutor] Reading CSV files in Pandas In-Reply-To: References: Message-ID: Does pandas do the same thing numpy does? I've never used them and unsure of what they are about. From breamoreboy at yahoo.co.uk Sun Oct 20 14:07:14 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 20 Oct 2013 13:07:14 +0100 Subject: [Tutor] Reading CSV files in Pandas In-Reply-To: References: Message-ID: On 20/10/2013 11:30, Matthew Ngaha wrote: > Does pandas do the same thing numpy does? I've never used them and > unsure of what they are about. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > Pandas uses numpy, as does many other Python packages. From http://pandas.pydata.org/ "pandas is an open source, BSD-licensed library providing high-performance, easy-to-use data structures and data analysis tools for the Python programming language." From http://www.numpy.org/ "NumPy is the fundamental package for scientific computing with Python. It contains among other things: a powerful N-dimensional array object sophisticated (broadcasting) functions tools for integrating C/C++ and Fortran code useful linear algebra, Fourier transform, and random number capabilities" -- Roses are red, Violets are blue, Most poems rhyme, But this one doesn't. Mark Lawrence From davea at davea.name Sun Oct 20 16:24:27 2013 From: davea at davea.name (Dave Angel) Date: Sun, 20 Oct 2013 14:24:27 +0000 (UTC) Subject: [Tutor] Passing arguments? References: Message-ID: On 20/10/2013 00:20, Jenny Allar wrote: Earlier, you have managed to send your emails as text, but this time you blew it and used html. That's probably what makes the code doublespaced in the newsgroup. It also means that most of us see > I've written the code below the assignment, and I think I have everything > covered in terms of asking the user for the information I need and somehow > calculating costs, but I'm just ridiculously confused on the order and > placement of the functions and components of this program- specifically the > shiprate variable. Thank you in advance for any help. > > This is my assignment: > > Write a program that asks a user for the name of a product that they are > ordering online and its weight. The program must calculate the cost of > shipping the product using the following cost structure. If it weighs less > than 10 pounds the cost is $1.50 per pound, if it is 10 pounds or more and > less than 25 pounds then the cost is $1.45 per pound. If the weight is 25 > pounds or more the cost is $1.40 per pound. You may get the data from the > user in main. You must print the name of the product, the weight and the > cost of shipping in a separate function. > > > > **********NOTE: ALWAYS USE ?WHILE LOOPS? To Validate******************** > > * > * > > > > > > > > # This program uses an if-else statement > > # It asks for the name of a product and the weight of that product. > > # It then determines the shipping cost as defined by the weight. > > # > > # Variable Type Purpose > > # product string hold for name of product > > # weight float hold for weight of product > > # > > > def main (): > > > > product = input("Please enter the name of the product: ") > > weight = int(input("Please enter the weight of the product: ")) > > > print('Product:', product) > > print('Weight:', weight) > > > > if weight <= 10: > > shiprate = 1.5 > > calc_weight_small(weight, shiprate) > > elif weight >= 10 and weight <= 25: > > shiprate = 1.45 > > calc_weight_medium(weight, shiprate) > > else: > > shiprate = 1.4 > > calc_weight_large(weight, shiprate) > > > # Calculate shipping cost for product less than 10 pounds > > def cacl_weight_small(weight, shiprate): > > shiprate = 1.5 > > total = weight * shiprate > > # Calculate shipping cost for product between 10 and 25 pounds. > > def calc_weight_medium(weight, shiprate): > > shiprate = 1.45 > > total = weight * shiprate > > # Calculate shipping cost for product over 25 pounds. > > def calc_weight_large(weight, shiprate): > > shiprate = 1.4 If you had removed this line, the function would have served the need, and you wouldn't need the other two. One function called calc_weight would do it. > > total = weight * shiprate > > > > # > > #This function calculates and prints the total cost > > # based on the weight category the product falls into > > # Variable Type Purpose > > # weight float weight of product > > # shiprate float cost per pound > > # total float total cost to ship product > > # > > > > > > print () > > print ("The cost to ship", product, "is: $", format (total, > '9,.2f')) > > > > > > > > > > > > main () > > 'Weight:', weight)

>



? ? if weight <= 10:

? ? ? ? shiprate = 1.5

? ? ? ? calc_weight_small(weight, shiprate)

>

? ? elif weight >= 10 and weight <= 25:

? ? ? ? shiprate = 1.45

? ? ? ? calc_weight_medium(weight, shiprate)

? ? else:

-- DaveA From davea at davea.name Sun Oct 20 16:26:36 2013 From: davea at davea.name (Dave Angel) Date: Sun, 20 Oct 2013 14:26:36 +0000 (UTC) Subject: [Tutor] Auto-response for your message to the "Tutor" mailing list References: <20131020083417.GG2559@keks.naturalnet.de> Message-ID: On 20/10/2013 04:34, Dominik George wrote: >> Your message for tutor at python.org, the Python programming tutor list, >> has been received and is being delivered. This automated response is >> sent to those of you new to the Tutor list, to point out a few >> resources that can help with answering your own questions, or improve >> the chances of getting a useful answer from the other subscribers. > > Thank you, but? > > ?I have been a member of the list for many weeks now and have posted > quite a few messages. Is there a reason I am receiving this friendly > greeter more than once? > Don't worry about it. I've been a member for many years, and I still get it periodically. Sometimes it happens if I haven't posted for a few weeks, and sometimes it just seems gratuitous. -- DaveA From alan.gauld at btinternet.com Sun Oct 20 20:05:37 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 20 Oct 2013 19:05:37 +0100 Subject: [Tutor] Reading CSV files in Pandas In-Reply-To: References: Message-ID: On 20/10/13 11:30, Matthew Ngaha wrote: > Does pandas do the same thing numpy does? Pandas is more about analysis of big data volumes rather than complex calculations. eg statistical analysis and data mining. As such it's closer to R than to numpy in its function, so far as I can tell. (Although it uses numpy under the covers). -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From jugurtha.hadjar at gmail.com Sun Oct 20 16:04:53 2013 From: jugurtha.hadjar at gmail.com (Jugurtha Hadjar) Date: Sun, 20 Oct 2013 15:04:53 +0100 Subject: [Tutor] Passing arguments? In-Reply-To: References: Message-ID: <5263E305.4090007@gmail.com> Hello, > the data from the user in main. You must print the name of the product, > the weight and the cost of shipping in a separate function. Your code printed that in main. > print('Product:', product) > > print('Weight:', weight) Also, you have an int(input("weight:")) Weight seldom is an integer. There's also no need to create three functions (calc_weight_[small|medium|large]) that do the exact same thing: i.e multiply the ship rate by the weight. Also, there is overlap in your calculations: if weight<=10 shiprate = 1.5 ... elif weight >=10 shiprate = 1.45 What if weight = 10 pounds ? Is the shiprate 1.5 or 1.45 ? In other words, you have to exclude one. (The second, to get the most money). if weight<=10 shiprate = 1.5 elif weight>10 shiprate = 1.45 Now for the code: Why not make one function that does things: Warning: I'm on Python 2.7, so take into account raw_input() and print() differences. Also, I haven't modified the type of product_weight and let it integer. You might want to change that. I haven't sanitized the inputs, neither. --code starts here-- def calc_shiprate(product_name, product_weight): # Takes two (2) arguments: "product_name" and "product_weight". # Returns "amount_to_pay" by applying ship-rates depending on # "product_weight". # Following are the ship-rates in $/pound shiprate_small = 1.5 shiprate_medium = 1.45 shiprate_large = 1.4 if product_weight <=10: shiprate = shiprate_small elif (product_weight > 10) and (product_weight <= 25): shiprate = shiprate_medium else: shiprate = shiprate_large amount_to_pay = product_weight * shiprate print "Total to pay for product %s weighing %d pounds is: %d " % (product_name, product_weight, amount_to_pay) product_name = raw_input("Product name: ") product_weight = int(raw_input("Product weight: ")) calc_shiprate(product_name, product_weight) --code ends here-- -- ~Jugurtha Hadjar, From johnsteedman360 at gmail.com Sun Oct 20 20:19:35 2013 From: johnsteedman360 at gmail.com (John Steedman) Date: Sun, 20 Oct 2013 19:19:35 +0100 Subject: [Tutor] Reading CSV files in Pandas In-Reply-To: References: Message-ID: I have in front of me a copy an (unread, borrowed) copy of "Python for Data Analysis". Well, on page 104, there is the start of an answer. Pandas : has two useful functions: read_csv and read_table Numpy : see np.loadtxt and np.genfromtxt There is an example for using the first numpy function: arr = np.loadtxt ( fileName, delimiter = ',' ) This information from Python for Data Analysis , author: Wes McKinney published by O'Reilly - a succinct, useful-looking book. On Sun, Oct 20, 2013 at 7:05 PM, Alan Gauld wrote: > On 20/10/13 11:30, Matthew Ngaha wrote: >> >> Does pandas do the same thing numpy does? > > > Pandas is more about analysis of big data volumes rather than complex > calculations. eg statistical analysis and data mining. > > As such it's closer to R than to numpy in its function, so far as I can > tell. (Although it uses numpy under the covers). > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.flickr.com/photos/alangauldphotos > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Sun Oct 20 20:26:22 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 20 Oct 2013 19:26:22 +0100 Subject: [Tutor] Passing arguments? In-Reply-To: References: Message-ID: On 20/10/13 05:20, Jenny Allar wrote: > I've written the code below the assignment, and I think I have > everything covered in terms of asking the user for the information I > need and somehow calculating costs, but I'm just ridiculously confused > on the order and placement of the functions and components of this > program- specifically the shiprate variable. Its pretty much fine except that you define shiprate inside the function which overwrites the value you pass in. You should define the value before you call the function 9which you are doing) but not set it inside the function. Then you only need to define one function which accepts the shiprate as an argument. One little extra is that you could define a default value for the parameter to save you sup[plying it in the most common case: def calc_weight(weight, shiprate=1.5): total = weight * shiprate Although the name does not describe what the function does so a better name is probably calc_cost() > if weight <= 10: > shiprate = 1.5 > calc_weight_small(weight, shiprate) Notice you call calc_weight_small() here.... > def cacl_weight_small(weight, shiprate): But you define cacl_weight_small() here. That won't work so either you did not send us your real code or you have a bug waiting to bite... HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From fomcl at yahoo.com Sun Oct 20 20:53:57 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sun, 20 Oct 2013 11:53:57 -0700 (PDT) Subject: [Tutor] Reading CSV files in Pandas In-Reply-To: Message-ID: <1382295237.42953.YahooMailBasic@web163801.mail.gq1.yahoo.com> On Sun, 10/20/13, Mark Lawrence wrote: Subject: Re: [Tutor] Reading CSV files in Pandas To: tutor at python.org Date: Sunday, October 20, 2013, 1:16 AM On 19/10/2013 23:40, Alan Gauld wrote: > This is the second time I've seen pandas mentioned recedntly I really > must go and look it up to find out what it is... Just started out myself at http://pandas.pydata.org/ and at first glance it seems quite awesome. Yeah, I've read the Pandas book and I was amazed too. It's R (as in CRAN R) on steroids. From ricaraoz at gmail.com Mon Oct 21 00:01:15 2013 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sun, 20 Oct 2013 19:01:15 -0300 Subject: [Tutor] Fwd: Re: Passing arguments? In-Reply-To: <5263E7F0.1040301@gmail.com> References: <5263E7F0.1040301@gmail.com> Message-ID: <526452AB.3060600@gmail.com> Sorry, I sent this answer to the OP directly and not to the list. -------- Mensaje original -------- Asunto: Re: [Tutor] Passing arguments? Fecha: Sun, 20 Oct 2013 11:25:52 -0300 De: Ricardo Ar?oz A: Jenny Allar El 20/10/13 01:20, Jenny Allar escribi?: > I've written the code below the assignment, and I think I have > everything covered in terms of asking the user for the information I > need and somehow calculating costs, but I'm just ridiculously confused > on the order and placement of the functions and components of this > program- specifically the shiprate variable. Thank you in advance for > any help. > Ok, just a couple of things first. - Your assignment specifically says 'always use "while loops" to validate' but I see no loop at all in your code. You might want to look into it. - What your assignment points to when it says to use "while loops" is that you should validate that what the user inputs is a valid number. If the user will input something else than a number as the weight then when you apply the int() function an exception will be flagged and your program will terminate ungracefully. You may validate input using "exceptions" and "while loops" (look it up). - Your functions should do what their name imply, and preferably do only one thing. Having a function named calc_weight_large() that also prints the shipping cost is not good. - Your if asks for >= 10 and your elif for <= 10 when the "= 10" case was already handled by the first if, that is a mistake. Besides which it might be better looking (though this is a matter of personal preference) if you :: if weight > 25 # do something elif weight > 10 # do something else else # do something entirely different - I would structure the program in the following way :: def main(): product = in_product() weight = in_weight() if weight > 25 total = calc_shipping(1.40, weight) elif weight > 10 total = calc_shipping(1.45, weight) else total = calc_shipping(1.50, weight) print_data(product, weight, total) > This is my assignment: > > Write a program that asks a user for the name of a product that they > are ordering online and its weight. The program must calculate the > cost of shipping the product using the following cost structure. If > it weighs less than 10 pounds the cost is $1.50 per pound, if it is 10 > pounds or more and less than 25 pounds then the cost is $1.45 per > pound. If the weight is 25 pounds or more the cost is $1.40 per > pound. You may get the data from the user in main. You must print > the name of the product, the weight and the cost of shipping in a > separate function. > > *_*********NOTE: ALWAYS USE "WHILE LOOPS" To Validate*******************_* > > # This program uses an if-else statement > > # It asks for the name of a product and the weight of that product. > # It then determines the shipping cost as defined by the weight. > # > # Variable Type Purpose > # product string hold for name of product > # weight float hold for weight of product > # > > def main (): > product = input("Please enter the name of the product: ") > weight = int(input("Please enter the weight of the product: ")) > > print('Product:', product) > print('Weight:', weight) > > if weight <= 10: > shiprate = 1.5 > calc_weight_small(weight, shiprate) > elif weight >= 10 and weight <= 25: > shiprate = 1.45 > calc_weight_medium(weight, shiprate) > else: > shiprate = 1.4 > calc_weight_large(weight, shiprate) > > # Calculate shipping cost for product less than 10 pounds > def cacl_weight_small(weight, shiprate): > shiprate = 1.5 > total = weight * shiprate > # Calculate shipping cost for product between 10 and 25 pounds. > def calc_weight_medium(weight, shiprate): > shiprate = 1.45 > total = weight * shiprate > # Calculate shipping cost for product over 25 pounds. > # > #This function calculates and prints the total cost > # based on the weight category the product falls into > # Variable Type Purpose > > # weight float weight of product > # shiprate float cost per pound > # total float total cost to ship product > # > def calc_weight_large(weight, shiprate): > shiprate = 1.4 > total = weight * shiprate > print () > print ("The cost to ship", product, "is: $", format (total, > '9,.2f')) > > main () > -------------- next part -------------- An HTML attachment was scrubbed... URL: From corsam28 at hotmail.com Mon Oct 21 02:16:12 2013 From: corsam28 at hotmail.com (Sammy Cornet) Date: Sun, 20 Oct 2013 19:16:12 -0500 Subject: [Tutor] string list in alphabetical! Message-ID: Hello!I'm using python 2.7.5 version and I'm trying to write a program related to a file named unsorted_fruits.txt contains a list of 26 fruits, each one with a name that begins with a different letter of the alphabet. My program's goal is to read in the fruits from the file unsorted_fruits.txt and writes them out in alphabetical order to a file named sorted_fruits.txt while I'm using while loop For this assignment you must incorporate the use of a list, for loop and / or while loop.so here is what I have on my script: infile = open('Desktop/unsorted_fruits.docx' ,"r")outfile = open('Desktop/sorted_fruits.docx', 'w') def find(): index = 0 while index < 26: list < 26 list = ["a", "b", "c", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n" "o", "p", "q", "r", "s", "t", "u", "v", "w", "z", "y", "z"] if index[0] == list[0]: infile = list + 1 print infile index += 1 infile.close() outfile.close() And here is my output: Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32Type "copyright", "credits" or "license()" for more information.>>> ================================ RESTART ================================>>> Traceback (most recent call last): File "F:/7.real.py", line 1, in infile = open('Desktop/unsorted_fruits.docx' ,"r")IOError: [Errno 2] No such file or directory: 'Desktop/unsorted_fruits.docx'>>> I'm not sure if I write the program correctly, but I can't get my file wich is on my desktop to the program. CAn someone help me please? -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Mon Oct 21 02:30:05 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 21 Oct 2013 11:30:05 +1100 Subject: [Tutor] string list in alphabetical! In-Reply-To: References: Message-ID: <20131021003004.GI7989@ando> On Sun, Oct 20, 2013 at 07:16:12PM -0500, Sammy Cornet wrote: > Hello!I'm using python 2.7.5 version and I'm trying to write a program > related to a file named unsorted_fruits.txt contains a list of 26 .........................^^^^^^^^^^^^^^^^^^^^^ Here you say the file is called unsorted_fruits.txt > infile = open('Desktop/unsorted_fruits.docx' ,"r") ................^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Here you try to open a file called unsorted_fruits.docx And likewise for the file you are writing to. -- Steven From breamoreboy at yahoo.co.uk Mon Oct 21 03:20:09 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 21 Oct 2013 02:20:09 +0100 Subject: [Tutor] string list in alphabetical! In-Reply-To: References: Message-ID: On 21/10/2013 01:16, Sammy Cornet wrote: > Hello! > > I'm using python 2.7.5 version and I'm trying to write a program related > to a file named unsorted_fruits.txt contains a list of 26 fruits, each > one with a name that begins with a different letter of the alphabet. My > program's goal is to read in the fruits from the file > unsorted_fruits.txt and writes them out in alphabetical order to a file > named sorted_fruits.txt while I'm using while loop > > For this assignment you must incorporate the use of a list, for loop and > / or while loop. > > so here is what I have on my script: > > > infile = open('Desktop/unsorted_fruits.docx' ,"r") > > outfile = open('Desktop/sorted_fruits.docx', 'w') > > > def find(): > > index = 0 > > while index < 26: > > list < 26 > > list = ["a", "b", "c", "e", "f", "g", "h", "i", "j", "k", "l", > "m", "n" "o", "p", "q", "r", "s", "t", "u", "v", "w", "z", "y", "z"] > > if index[0] == list[0]: > > infile = list + 1 > > print infile > > index += 1 > > infile.close() > > outfile.close() > > > And here is my output: > > Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit > (Intel)] on win32 > Type "copyright", "credits" or "license()" for more information. > >>> ================================ RESTART > ================================ > >>> > > Traceback (most recent call last): > File "F:/7.real.py", line 1, in > infile = open('Desktop/unsorted_fruits.docx' ,"r") > IOError: [Errno 2] No such file or directory: 'Desktop/unsorted_fruits.docx' > >>> > Once you have fixed the file name error which Steven has already pointed out, do you intend to call the function find that you have defined? If yes can I suggest that you use paper and pencil to work out what it does, or more accurately doesn't do, as it's strewn with errors. -- Python is the second best programming language in the world. But the best has yet to be invented. Christian Tismer Mark Lawrence From nsivaram.net at gmail.com Mon Oct 21 05:03:18 2013 From: nsivaram.net at gmail.com (Sivaram Neelakantan) Date: Mon, 21 Oct 2013 08:33:18 +0530 Subject: [Tutor] Reading CSV files in Pandas References: Message-ID: <87mwm3l409.fsf@gmail.com> On Sun, Oct 20 2013,Mark Lawrence wrote: > On 19/10/2013 23:40, Alan Gauld wrote: > >> This is the second time I've seen pandas mentioned recedntly I really >> must go and look it up to find out what it is... > > Just started out myself at http://pandas.pydata.org/ and at first > glance it seems quite awesome. The data handling framework is very good; it cuts out large swathes of code from a normal procedural coding POV. That is, instead of lists, tuples etc. you work with a conceptual dataframe, like R. sivaram -- From nsivaram.net at gmail.com Mon Oct 21 05:05:45 2013 From: nsivaram.net at gmail.com (Sivaram Neelakantan) Date: Mon, 21 Oct 2013 08:35:45 +0530 Subject: [Tutor] Reading CSV files in Pandas References: Message-ID: <87iowrl3w6.fsf@gmail.com> On Sat, Oct 19 2013,Manish Tripathi wrote: > I am trying to import a csv file in Pandas but it throws an error. The > format of the data when opened in notepad++ is as follows with first row > being column names: you could try the following newsgroup or mailing list for more specialised help. gmane.org:gmane.comp.python.pydata [snipped 82 lines] sivaram -- From breamoreboy at yahoo.co.uk Mon Oct 21 09:17:21 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 21 Oct 2013 08:17:21 +0100 Subject: [Tutor] Reading CSV files in Pandas In-Reply-To: <87iowrl3w6.fsf@gmail.com> References: <87iowrl3w6.fsf@gmail.com> Message-ID: On 21/10/2013 04:05, Sivaram Neelakantan wrote: > > you could try the following newsgroup or mailing list for more > specialised help. > > gmane.org:gmane.comp.python.pydata > > sivaram > -- Thanks for this, it explains why I couldn't find pandas there :) -- Python is the second best programming language in the world. But the best has yet to be invented. Christian Tismer Mark Lawrence From corsam28 at hotmail.com Mon Oct 21 04:15:05 2013 From: corsam28 at hotmail.com (Sammy Cornet) Date: Sun, 20 Oct 2013 21:15:05 -0500 Subject: [Tutor] string list in alphabetical! In-Reply-To: References: Message-ID: Thank you for help Steven! I intend to correct it. But also I would like to know if I wrote the correctly in order to the output that I'm looking for? On Oct 20, 2013, at 19:22, "Sammy Cornet" wrote: > Hello! > > I'm using python 2.7.5 version and I'm trying to write a program related to a file named unsorted_fruits.txt contains a list of 26 fruits, each one with a name that begins with a different letter of the alphabet. My program's goal is to read in the fruits from the file unsorted_fruits.txt and writes them out in alphabetical order to a file named sorted_fruits.txt while I'm using while loop > > For this assignment you must incorporate the use of a list, for loop and / or while loop. > > so here is what I have on my script: > > > > infile = open('Desktop/unsorted_fruits.docx' ,"r") > > outfile = open('Desktop/sorted_fruits.docx', 'w') > > > > def find(): > > index = 0 > > while index < 26: > > list < 26 > > list = ["a", "b", "c", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n" "o", "p", "q", "r", "s", "t", "u", "v", "w", "z", "y", "z"] > > if index[0] == list[0]: > > infile = list + 1 > > print infile > > index += 1 > > infile.close() > > outfile.close() > > > And here is my output: > > Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32 > Type "copyright", "credits" or "license()" for more information. > >>> ================================ RESTART ================================ > >>> > > Traceback (most recent call last): > File "F:/7.real.py", line 1, in > infile = open('Desktop/unsorted_fruits.docx' ,"r") > IOError: [Errno 2] No such file or directory: 'Desktop/unsorted_fruits.docx' > >>> > > > I'm not sure if I write the program correctly, but I can't get my file wich is on my desktop to the program. CAn someone help me please? > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Mon Oct 21 11:46:13 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 21 Oct 2013 10:46:13 +0100 Subject: [Tutor] string list in alphabetical! In-Reply-To: References: Message-ID: On 21/10/13 01:16, Sammy Cornet wrote: > so here is what I have on my script: OK some comments below... > infile = open('Desktop/unsorted_fruits.docx' ,"r") > outfile = open('Desktop/sorted_fruits.docx', 'w') You probably want to use txt files. > def find(): > index = 0 > while index < 26: > list < 26 You haven't created list yet so you can't compare it to anything. But even if you had this line does nothing useful. > list = ["a", "b", "c", "e", "f", "g", "h", "i", "j", "k", "l", > "m", "n" "o", "p", "q", "r", "s", "t", "u", "v", "w", "z", "y", "z"] OK, Now you've created list... Although its a bad choice of name because it hides the list() operation in Python. So you can't now convert things to lists. > if index[0] == list[0]: This will fail since index is a number and list is a list. You can't index a number. I'm not sure what you thought you were comparing? > infile = list + 1 I don't know what you think this does but what it does in practice is throws away your open file and tries to add 1 to your list which is an error. You can't add lists and numbers. > print infile > index += 1 > > infile.close() > outfile.close() Since you haven't read anything from infile or written anything to outfile this doesn't achieve much. I think you need to sit down with a pen and paper and work out how you would solve this problem then convert that to Python. As it is you have a long way to go. I also think you may be making the exercise much harder than it should be. Take a look at the documentation for the sort() method of lists, that should help. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From steve at pearwood.info Mon Oct 21 13:16:52 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 21 Oct 2013 22:16:52 +1100 Subject: [Tutor] string list in alphabetical! In-Reply-To: References: Message-ID: <20131021111652.GJ7989@ando> On Sun, Oct 20, 2013 at 09:15:05PM -0500, Sammy Cornet wrote: > Thank you for help Steven! I intend to correct it. But also I would > like to know if I wrote the correctly in order to the output that I'm > looking for? I don't know, I didn't study your code in that much detail. Why don't you fix the problems you already know about, then try running it, and see if it works as you expect? That is the normal process of programming: 1) write some code 2) fix the bugs until it will run 3) test if it works correctly 4) repeat until done -- Steven From lu.nemec at gmail.com Mon Oct 21 13:21:59 2013 From: lu.nemec at gmail.com (Lukas Nemec) Date: Mon, 21 Oct 2013 13:21:59 +0200 Subject: [Tutor] string list in alphabetical! In-Reply-To: <20131021111652.GJ7989@ando> References: <20131021111652.GJ7989@ando> Message-ID: <52650E57.10204@gmail.com> On 10/21/2013 01:16 PM, Steven D'Aprano wrote: > On Sun, Oct 20, 2013 at 09:15:05PM -0500, Sammy Cornet wrote: >> Thank you for help Steven! I intend to correct it. But also I would >> like to know if I wrote the correctly in order to the output that I'm >> looking for? > I don't know, I didn't study your code in that much detail. > > Why don't you fix the problems you already know about, then try running > it, and see if it works as you expect? > > That is the normal process of programming: > > 1) write some code > 2) fix the bugs until it will run > 3) test if it works correctly > 4) repeat until done > > I'd like to upgrade that process :D ... 1) think about your problem 2) if there are some heplful libraries that can make it way easier, use them 3) write some code 4) fix the bugs until it'll run 5) write unittests 6) test if it works correctly and if unittests pass 7) repeat until done Bye :) From corsam28 at hotmail.com Mon Oct 21 16:40:11 2013 From: corsam28 at hotmail.com (Sammy Cornet) Date: Mon, 21 Oct 2013 09:40:11 -0500 Subject: [Tutor] string list in alphabetical! In-Reply-To: References: Message-ID: I appreciate your help and advices in concern of my challenge. In fact, I'm confuse because I was sent a lot of lesson in comparison to what I usually have for each week. I will try it the you told me. Think you for all of your email. On Oct 21, 2013, at 4:08, "Sammy Cornet" wrote: > Thank you for help Steven! I intend to correct it. But also I would like to know if I wrote the correctly in order to the output that I'm looking for? > > > > On Oct 20, 2013, at 19:22, "Sammy Cornet" wrote: > >> Hello! >> >> I'm using python 2.7.5 version and I'm trying to write a program related to a file named unsorted_fruits.txt contains a list of 26 fruits, each one with a name that begins with a different letter of the alphabet. My program's goal is to read in the fruits from the file unsorted_fruits.txt and writes them out in alphabetical order to a file named sorted_fruits.txt while I'm using while loop >> >> For this assignment you must incorporate the use of a list, for loop and / or while loop. >> >> so here is what I have on my script: >> >> >> >> infile = open('Desktop/unsorted_fruits.docx' ,"r") >> >> outfile = open('Desktop/sorted_fruits.docx', 'w') >> >> >> >> def find(): >> >> index = 0 >> >> while index < 26: >> >> list < 26 >> >> list = ["a", "b", "c", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n" "o", "p", "q", "r", "s", "t", "u", "v", "w", "z", "y", "z"] >> >> if index[0] == list[0]: >> >> infile = list + 1 >> >> print infile >> >> index += 1 >> >> infile.close() >> >> outfile.close() >> >> >> And here is my output: >> >> Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32 >> Type "copyright", "credits" or "license()" for more information. >> >>> ================================ RESTART ================================ >> >>> >> >> Traceback (most recent call last): >> File "F:/7.real.py", line 1, in >> infile = open('Desktop/unsorted_fruits.docx' ,"r") >> IOError: [Errno 2] No such file or directory: 'Desktop/unsorted_fruits.docx' >> >>> >> >> >> I'm not sure if I write the program correctly, but I can't get my file wich is on my desktop to the program. CAn someone help me please? >> >> >> >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor From cnsiva.in at gmail.com Mon Oct 21 18:16:37 2013 From: cnsiva.in at gmail.com (Siva Cn) Date: Mon, 21 Oct 2013 21:46:37 +0530 Subject: [Tutor] Tutor] string list in alphabetical! Message-ID: Hi Sammy, Try this this may help you ! ---------------------------------------------------------------------------------- def sort_file1_to_file2(file1, file2): """.""" input_content = [] with open(file1, 'r') as fp: input_content = fp.read() input_content = input_content.splitlines() _dict = {ele[0].lower(): ele for ele in input_content} out_content = "\n".join([_dict[chr(idx)] for idx in range(97, 123) if chr(idx) in _dict]) with open(file2, 'w') as fp: fp.write(out_content) sort_file1_to_file2('file1.txt', 'file2.txt') ------------------------------------------------------------------------------------ *-- Regards --* * * * Siva Cn* *Python Developer* * * *http://www.cnsiva.com* --------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From dyoo at hashcollision.org Mon Oct 21 19:52:38 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 21 Oct 2013 10:52:38 -0700 Subject: [Tutor] Reading CSV files in Pandas In-Reply-To: References: Message-ID: On Sat, Oct 19, 2013 at 7:29 AM, Manish Tripathi wrote: > > I am trying to import a csv file in Pandas but it throws an error. The format of the data when opened in notepad++ is as follows with first row being column names: > > "End Customer Organization ID,End Customer Organization Name,End Customer Top Parent Organization ID,End Customer Top Parent Organization Name,Reseller Top Parent ID,Reseller Top Parent Name,Business,Rev Sum Division,Rev Sum Category,Product Family,Version,Pricing Level,Summary Pricing Level,Detail Pricing Level,MS Sales Amount,MS Sales Licenses,Fiscal Year,Sales Date" > "11027676,Baroda Western Uttar Pradesh Gramin Bankgfhgfnjgfnmjmhgmghmghmghmnghnmghnmhgnmghnghngh,4078446,Bank Of Barodadfhhgfjyjtkyukujkyujkuhykluiluilui;iooi';po'fserwefvegwegf,1809012,""Hcl Infosystems Ltd - Partnerdghftrutyhb frhywer5y5tyu6ui7iukluyj,lgjmfgnhfrgweffw"",Server & CALsdgrgrfgtrhytrnhjdgthjtyjkukmhjmghmbhmgfngdfbndfhtgh,SQL Server & CALdfhtrhtrgbhrghrye5y45y45yu56juhydsgfaefwe,SQL CALdhdfthtrutrjurhjethfdehrerfgwerweqeadfawrqwerwegtrhyjuytjhyj,SQL CALdtrye45y3t434tjkabcjkasdhfhasdjkcbaksmjcbfuigkjasbcjkasbkdfhiwh,2005,Openfkvgjesropiguwe90fujklascnioawfy98eyfuiasdbcvjkxsbhg,Open Lklbjdfoigueroigbjvwioergyuiowerhgosdhvgfoisdhyguiserhguisrh,""Open Stddfm,vdnoghioerivnsdflierohgushdfovhsiodghuiohdbvgsjdhgouiwerho"",125.85,1,FY07,12/28/2006" > "12835756,Uttam Strips Pvt Ltd,12835756,Uttam Strips Pvt Ltd,12565538,Redington C/O Fortis Financial Services Ltd,MBS,Dynamics ERP,Dynamics NAV,Dynamics NAV Business Essentials,Non-specific,Other,MBS SA,MBS New Customer Enhanc. Def,0,0,FY09,9/15/2008" > "12233135,Bhagwan Singh Tondon,12233135,Bhagwan Singh Tondon,2652941,H B S Systems Pvt Ltd,Server & CAL,SQL Server & CAL,SQL CAL,SQL CAL,Non-specific,Open,Open L&SA,Deferred Open L&SA - New,0,0,FY09,9/15/2008" > "11602305,Maya Academy Of Advanced Cinematics,9750934,Maya Entertainment Ltd,336146,Embee Software Pvt Ltd,Server & CAL,Windows Server & CAL,Windows Server HPC,Windows Compute Cluster Server,Non-specific,Open,Open V/MYO - Rec,OLV Perpet L&SA Recur-Def,0,0,FY09,9/25/2008" > "13336009,Remiel Softech Solution Pvt Ltd,13336009,Remiel Softech Solution Pvt Ltd,13335482,Redington C/O Remiel Softech Solutions Pvt Ltd,MBS,Dynamics ERP,Dynamics NAV,Dynamics NAV Business Essentials,Non-specific,Other,MBS SA,MBS New Customer Enhanc. Def,0,0,FY09,12/23/2008" > "7872800,Science Application International Corporation,2839760,GOVERNMENT OF KARNATAKA,10237455,Cubic Computing P.L,Server & CAL,SQL Server & CAL,SQL Server Standard,SQL Server Standard Edition,Non-specific,Open,Open SA/UA,Deferred Open SA - Renewal,0,0,FY09,1/15/2009" > "13096361,Pratham Software Pvt Ltd,13096361,Pratham Software Pvt Ltd,10133086,Krap Computer,Information Worker,Office,Office Standard / Basic,Office Standard,2007,Open,Open L,Open Std,7132.44,28,FY09,9/24/2008" > "12192276,Texmo Precision Castings,12192276,Texmo Precision Castings,4059430,Quadra Systems. - Partner,Server & CAL,Windows Server & CAL,Windows Standard Server,Windows Server Standard,Non-specific,Open,Open L&SA,Deferred Open L&SA - New,0,0,FY09,11/15/2008" > > Kindly note that the same file when double clicked in the csv format opens in excel with comma separated values BUT with NO quotation marks in each line as shown in notepad++. > > I have used encoding as UTF-8 which gives the following error: Questions: * Where is this data coming from? * Who or what is generating this file? * Is it being automatically generated, or is someone manually typing in the file's content? Knowing the answers to these questions may help to isolate what the actual problem is. The source of this input, if they are a good, responsible party, should be saying up front how to interpret its bytes. Otherwise you are being put into a position of having to guess the proper interpretation. Guessing can be fun sometimes, I suppose, but I personally don't like doing it unless I have no choice. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dyoo at hashcollision.org Mon Oct 21 20:02:44 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 21 Oct 2013 11:02:44 -0700 Subject: [Tutor] Reading CSV files in Pandas In-Reply-To: References: Message-ID: > > * Where is this data coming from? > * Who or what is generating this file? Just to be more specific about this: I have a very strong suspicion that whatever is generating the input that you're trying to read is doing something ad-hoc with regards to CSV file format. Knowing what generated the file, whether it be Excel, or some custom script, is very helpful in diagnosing where the problem's originating from. Your suspicion about the quotes around entire rows: > Does it have to do with the "" marks present before each line in the data? sounds reasonable. I expect quotes around individual fields, but not around entire rows. Such a feature sounds anomalous because it doesn't fit the description of known CSV formats: http://en.wikipedia.org/wiki/Comma-separated_values -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Mon Oct 21 20:10:32 2013 From: bgailer at gmail.com (bob gailer) Date: Mon, 21 Oct 2013 14:10:32 -0400 Subject: [Tutor] Tutor] string list in alphabetical! In-Reply-To: References: Message-ID: <52656E18.9040905@gmail.com> On 10/21/2013 12:16 PM, Siva Cn wrote: > Hi Sammy, > > Try this this may help you ! > > ---------------------------------------------------------------------------------- > def sort_file1_to_file2(file1, file2): > """.""" > input_content = [] > with open(file1, 'r') as fp: > input_content = fp.read() > > input_content = input_content.splitlines() > > _dict = {ele[0].lower(): ele for ele in input_content} > > out_content = "\n".join([_dict[chr(idx)] > for idx in range(97, 123) > if chr(idx) in _dict]) > > with open(file2, 'w') as fp: > fp.write(out_content) > > sort_file1_to_file2('file1.txt', 'file2.txt') > ------------------------------------------------------------------------------------ I am surprised to see this program. It seems unnecessarily complex and somewhat hard to read. Especially for a rank beginner (the OP) Also has an unnecessary statement (input_content = []) IMHO it is more customary and a lot simpler to process the lines in a file thusly: for line in open(file1, 'r'): process the line -- Bob Gailer 919-636-4239 Chapel Hill NC From fomcl at yahoo.com Mon Oct 21 21:23:31 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Mon, 21 Oct 2013 12:23:31 -0700 (PDT) Subject: [Tutor] string list in alphabetical! In-Reply-To: <52650E57.10204@gmail.com> Message-ID: <1382383411.45645.YahooMailBasic@web163802.mail.gq1.yahoo.com> -------------------------------------------- On Mon, 10/21/13, Lukas Nemec wrote: Subject: Re: [Tutor] string list in alphabetical! To: tutor at python.org Date: Monday, October 21, 2013, 1:21 PM On 10/21/2013 01:16 PM, Steven D'Aprano wrote: > On Sun, Oct 20, 2013 at 09:15:05PM -0500, Sammy Cornet wrote: >> Thank you for help Steven! I intend to correct it. But also I would >> like to know if I wrote the correctly in order to the output that I'm >> looking for? > I don't know, I didn't study your code in that much detail. > > Why don't you fix the problems you already know about, then try running > it, and see if it works as you expect? > > That is the normal process of programming: > > 1) write some code > 2) fix the bugs until it will run > 3) test if it works correctly > 4) repeat until done > > I'd like to upgrade that process :D ... 1) think about your problem 2) if there are some heplful libraries that can make it way easier, use them 3) write some code 4) fix the bugs until it'll run 5) write unittests 6) test if it works correctly and if unittests pass 7) repeat until done step 5 might also precede step 3 From glez_b at comunidad.unam.mx Mon Oct 21 21:38:31 2013 From: glez_b at comunidad.unam.mx (Boris Vladimir Comi) Date: Mon, 21 Oct 2013 19:38:31 +0000 Subject: [Tutor] How to add a new column to a hierarchical dataframe grouped by groupby Message-ID: The following script try to calculate the resulting average of the direction and magnitude of the wind. My monthly dataframe has the following column: data Fecha Hora DirViento MagViento Temperatura Humedad PreciAcu 0 2011/07/01 00:00 318 6.6 21.22 100 1.7 1 2011/07/01 00:15 342 5.5 21.20 100 1.7 2 2011/07/01 00:30 329 6.6 21.15 100 4.8 3 2011/07/01 00:45 279 7.5 21.11 100 4.2 4 2011/07/01 01:00 318 6.0 21.16 100 2.5 The first thing I do is convert to radians the DirViento column dir_rad=[] for i in range(0, len(data['DirViento'])): dir_rad.append(data['DirViento'][i]*(pi/180.0)) data['DirViento']=around(dir_rad,1) Now get the columns of the components: u and v wind and add to data Uviento=[] Vviento=[] for i in range(0,len(data['MagViento'])): Uviento.append(data['MagViento'][i]*sin(data[DirViento][i])) Vviento.append(data['MagViento'][i]*cos(data[DirViento][i])) data['u']=around(Uviento,1) data['v']=around(Vviento,1) data Data columns: Fecha 51 non-null values Hora 51 non-null values DirViento 51 non-null values MagViento 51 non-null values Temperatura 51 non-null values Humedad 51 non-null values PreciAcu 51 non-null values u 51 non-null values v 51 non-null values dtypes: float64(6), int64(2), object(2) Now we indexed the dataframe and grouped index=data.set_index(['Fecha','Hora'],inplace=True) grouped = index.groupby(level=0) data['u'] Fecha Hora 2011/07/01 00:00 -4.4 00:15 -1.7 00:30 -3.4 00:45 -7.4 01:00 -4.0 2011/07/02 00:00 -4.5 00:15 -4.2 00:30 -7.6 00:45 -3.8 01:00 -2.0 2011/07/03 00:00 -6.3 00:15 -13.7 00:30 -0.3 00:45 -2.5 01:00 -2.7 Now get resultant wind direction for each day grouped.apply(lambda x: ((scipy.arctan2(mean(x['uu']),mean(x['vv'])))/(pi/180.0))) Fecha 2011/07/01 -55.495677 2011/07/02 -39.176537 2011/07/03 -51.416339 The result obtained, I need to apply the following conditions for i in grouped.apply(lambda x: ((scipy.arctan2(mean(x['uu']),mean(x['vv'])))/(pi/180.0))): if i < 180: i=i+180 else: if i > 180: i=i-180 else: i=i print i 124.504323033 140.823463279 128.5836605 How to add the previous result to the next dictionary stat_cea = grouped.agg({'DirRes':np.mean,'Temperatura':np.mean,'Humedad':np.mean,'PreciAcu':np.sum}) stat_cea Fecha DirRes Humedad PreciAcu Temperatura 2011/07/01 100.000000 30.4 21.367059 2011/07/02 99.823529 18.0 21.841765 2011/07/03 99.823529 4.0 21.347059 -------------- next part -------------- An HTML attachment was scrubbed... URL: From dyoo at hashcollision.org Mon Oct 21 23:42:29 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 21 Oct 2013 14:42:29 -0700 Subject: [Tutor] Reading CSV files in Pandas In-Reply-To: References: Message-ID: On Mon, Oct 21, 2013 at 11:57 AM, Manish Tripathi wrote: > It's pipeline data so must have been generated through Siebel and sent as > excel csv. > > I am assuming that you are talking about "Siebel Analytics", some kind of analysis software from Oracle: http://en.wikipedia.org/wiki/Siebel_Systems That would be fine, except that knowing it comes out of Siebel is no guarantee that the output you're consuming is well-formed Excel CSV. For example, I see things like this: http://spendolini.blogspot.com/2006/04/custom-export-to-csv.html where the generated output is "ad-hoc". ----------- Hmmm... but let's assume for the moment that your data is ok. Could the problem be in pandas? Let's follow this line of logic, and see where it takes us. Given the structure of the error you're seeing, I have to assume that pandas is trying to decode the bytes, and runs into an issue, though the exact position where it's running into an error is in question. In fact, looking at: https://github.com/pydata/pandas/blob/master/pandas/io/parsers.py#L1357 for example, the library appears to be trying to decode line-by-line under certain situations. If it runs into an error, it will report an offset into a particular line. Wow. That can be very bad, if I'm reading that right. It does not give that offset from the perspective of the whole file. But it's worse because it's unsound. The code _should_ be doing the decoding from the perspective of the whole file, not at the level of single lines. It needs to be using codecs.open(), and let codecs.open() handle the details of byte->unicode-string decoding. Otherwise, by that time, it's way too late: we've just taken an interpretation of the bytes that's potentially invalid. Example: if we're working with UTF-16, and we got into this code path, it'd be really bad. It's hard to tell whether or not we're taking that code path. I'm following the definition of read_csv from: https://github.com/pydata/pandas/blob/master/pandas/io/parsers.py#L409 to: https://github.com/pydata/pandas/blob/master/pandas/io/parsers.py#L282 to: https://github.com/pydata/pandas/blob/master/pandas/io/parsers.py#L184 to: https://github.com/pydata/pandas/blob/master/pandas/io/common.py#L100 Ok, at that point, they appear to try to decode the entire file. Somewhat good so far. Though, technically, pandas should be using codecs.open(): http://docs.python.org/2/howto/unicode.html#reading-and-writing-unicode-data and because they aren't, they appears to suck the entire file into memory with StringIO. Yikes. Now the pandas library must make sure _not_ to decode() again, because decoding is not an idempotent operation. As a concrete example: ############################################################## >>> 'foobar'.decode('utf-16') u'\u6f66\u626f\u7261' >>> 'foobar'.decode('utf-16').decode('utf-16') Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.7/encodings/utf_16.py", line 16, in decode return codecs.utf_16_decode(input, errors, True) UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128) ############################################################## This is reminiscent of the kind of error you're encountering, though I'm not sure if this is the same situation. Unfortunately, I'm running out of time to analyze this further. If you could upload your data file somewhere, someone else here may have time to investigate the error you're seeing in more detail. From reading the Pandas code, I'm discouraged by the code quality: I do think that there's a potential of a bug in the library. The code is a heck of a lot more complicated than I think it needs to be. -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Mon Oct 21 23:56:23 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 21 Oct 2013 22:56:23 +0100 Subject: [Tutor] How to add a new column to a hierarchical dataframe grouped by groupby In-Reply-To: References: Message-ID: On 21/10/2013 20:38, Boris Vladimir Comi wrote: This is the Python tutor mailing list so it is essentially aimed at beginners to programming and/or Python, so please ask your pandas specific question on the google group here https://groups.google.com/forum/#!forum/pydata or the equivalent mailing list at gmane.comp.python.pydata. -- Python is the second best programming language in the world. But the best has yet to be invented. Christian Tismer Mark Lawrence From breamoreboy at yahoo.co.uk Tue Oct 22 00:01:27 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 21 Oct 2013 23:01:27 +0100 Subject: [Tutor] Reading CSV files in Pandas In-Reply-To: References: Message-ID: On 21/10/2013 22:42, Danny Yoo wrote: > This question has now been placed on the correct forum here http://article.gmane.org/gmane.comp.python.pydata/2294 so I see little sense in us attempting to follow it up. -- Python is the second best programming language in the world. But the best has yet to be invented. Christian Tismer Mark Lawrence From tr.manish at gmail.com Mon Oct 21 20:57:07 2013 From: tr.manish at gmail.com (Manish Tripathi) Date: Tue, 22 Oct 2013 00:27:07 +0530 Subject: [Tutor] Reading CSV files in Pandas In-Reply-To: References: Message-ID: It's pipeline data so must have been generated through Siebel and sent as excel csv. On Mon, Oct 21, 2013 at 11:32 PM, Danny Yoo wrote: > > > > * Where is this data coming from? > > * Who or what is generating this file? > > > Just to be more specific about this: I have a very strong suspicion that > whatever is generating the input that you're trying to read is doing > something ad-hoc with regards to CSV file format. Knowing what generated > the file, whether it be Excel, or some custom script, is very helpful in > diagnosing where the problem's originating from. > > > Your suspicion about the quotes around entire rows: > > > Does it have to do with the "" marks present before each line in the > data? > > sounds reasonable. I expect quotes around individual fields, but not > around entire rows. Such a feature sounds anomalous because it doesn't fit > the description of known CSV formats: > > http://en.wikipedia.org/wiki/Comma-separated_values > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Oct 22 00:58:39 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 21 Oct 2013 23:58:39 +0100 Subject: [Tutor] Tutor] string list in alphabetical! In-Reply-To: References: Message-ID: On 21/10/13 17:16, Siva Cn wrote: > Hi Sammy, > > Try this this may help you ! Siva, the list policy is not to provide full solutions for homework type questions. It's better to provide some hints and let the OP figure it out for him/her self. That having been said there are a few issues with the code below... > ---------------------------------------------------------------------------------- > def sort_file1_to_file2(file1, file2): > """.""" A docstring with a dot is pretty useless, unless there's some Python magic going on that I'm unaware of > input_content = [] This is not needed since you initialise it below > with open(file1, 'r') as fp: > input_content = fp.read() > input_content = input_content.splitlines() It would be easier to use readlines to get each line in a list. And given we know there are only 26 lines memory usage is not an issue. > _dict = {ele[0].lower(): ele for ele in input_content} > > out_content = "\n".join([_dict[chr(idx)] > for idx in range(97, 123) > if chr(idx) in _dict]) And this is way more complicated than need be. We know the lines start with unique letters of the alphabet so we can just use the built in sort() method or sorted() function to get outcontent = "".join(sorted(input_content)) # readlines preserves \n? If the first letters are mixed case there would need a slight tweak to account for that but there is no suggestion from the OP that that is an issue. > with open(file2, 'w') as fp: > fp.write(out_content) HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From steve at pearwood.info Tue Oct 22 01:07:03 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 22 Oct 2013 10:07:03 +1100 Subject: [Tutor] string list in alphabetical! In-Reply-To: <52650E57.10204@gmail.com> References: <20131021111652.GJ7989@ando> <52650E57.10204@gmail.com> Message-ID: <20131021230703.GK7989@ando> On Mon, Oct 21, 2013 at 01:21:59PM +0200, Lukas Nemec wrote: > On 10/21/2013 01:16 PM, Steven D'Aprano wrote: > >That is the normal process of programming: > > > >1) write some code > >2) fix the bugs until it will run > >3) test if it works correctly > >4) repeat until done > > > > > I'd like to upgrade that process :D ... > > 1) think about your problem > 2) if there are some heplful libraries that can make it way easier, use them > 3) write some code > 4) fix the bugs until it'll run > 5) write unittests > 6) test if it works correctly and if unittests pass > 7) repeat until done Heh, very true! But the most important step is step 1, think about your problem. The biggest mistake in programming is to start writing code without thinking the problem through first. Instead, a good start is to think about how you would solve the problem if you were doing it by hand. -- Steven From alan.gauld at btinternet.com Tue Oct 22 01:42:13 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 22 Oct 2013 00:42:13 +0100 Subject: [Tutor] [OT] Programming practice was: Re: string list in alphabetical! In-Reply-To: <20131021230703.GK7989@ando> References: <20131021111652.GJ7989@ando> <52650E57.10204@gmail.com> <20131021230703.GK7989@ando> Message-ID: On 22/10/13 00:07, Steven D'Aprano wrote: >> I'd like to upgrade that process :D ... >> >> 1) think about your problem >> 2) if there are some heplful libraries that can make it way easier, use them >> 3) write some code >> 4) fix the bugs until it'll run >> 5) write unittests >> 6) test if it works correctly and if unittests pass >> 7) repeat until done > > > Heh, very true! But the most important step is step 1, I agree. I've recently started coaching the son of a friend in computing for his new school (he is effectively a year behind his new classmates). They use VB6 but at a level I can cope with! :-) The interesting thing however is that the schools have not taught any kind of approach to problem solving, they just give a homework assignment and expect them to produce code. My friend wants to dive into Vuisual Studio to start work immediately. I've been trying to get him to adopt a workflow where he writes on paper an informal "use case" description of the solution and if necessary a pseudo code design. But it's been a real challenge to get him to slow down and understand exactly what he is being asked to do before diving into code. (Some of that is just natural youthful impatience, but mostly it's lack of instruction in an alternative! :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From dyoo at hashcollision.org Tue Oct 22 04:50:45 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 21 Oct 2013 19:50:45 -0700 Subject: [Tutor] [OT] Programming practice was: Re: string list in alphabetical! In-Reply-To: References: <20131021111652.GJ7989@ando> <52650E57.10204@gmail.com> <20131021230703.GK7989@ando> Message-ID: > > > I agree. I've recently started coaching the son of a friend in computing > for his new school (he is effectively a year behind > his new classmates). They use VB6 but at a level I can cope with! :-) > > The interesting thing however is that the schools have not taught > any kind of approach to problem solving, they just give a homework > assignment and expect them to produce code. I feel like we've had this conversation a long, long time ago. :P This is the sort of thing that we should be expect out of math classes. Polya's "How to Solve It" gives an approach that I wish I had seen during my own grade schooling. I ended up being exposed to the book from a recommendation that said something to the effect of: "If you want to be a good programmer, read this!" Another place where I'm seeing the act of problem solving being explicitly taught is in "How to Design Programs": http://www.ccs.neu.edu/home/matthias/HtDP2e/ (Note: I have worked with the authors of this book.) They use the term "Design Recipe", which is a similar shape to Steven's approach. Though I'd say to Steven: move the "write unittests" part from point 5 up to right after point 1. Then we'll be in more agreement. :P -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Oct 22 09:55:58 2013 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Tue, 22 Oct 2013 08:55:58 +0100 (BST) Subject: [Tutor] [OT] Programming practice was: Re: string list in alphabetical! In-Reply-To: References: <20131021111652.GJ7989@ando> <52650E57.10204@gmail.com> <20131021230703.GK7989@ando> Message-ID: <1382428558.39910.YahooMailNeo@web186002.mail.ir2.yahoo.com> The interesting thing however is that the schools have not taught >>any kind of approach to problem solving, they just give a homework assignment and expect them to produce code. > > >I feel like we've had this conversation a long, long time ago. ?:P > > >This is the sort of thing that we should be expect out of math classes. ?| >Polya's "How to Solve It" gives an approachYou're right Danny, we have had similar discussions a while back.? In fact I bought Polya's book after your recommendation :-) But in my friend's case he does not do math at his school - they have? made it an optional subject after second grade apparently!? Add to this the fact that English is not his first language and? that his old school was a year behind his current school and? you can see why computing science is a challenge for him! Another place where I'm seeing the act of problem solving being explicitly taught is in "How to Design Programs": > > > >? ? http://www.ccs.neu.edu/home/matthias/HtDP2e/ >Yes I really like this, even though their approach does rely? on recursion (being based in Scheme) so doesn't always work for other languages. It's also very math oriented in the problems? they solve which wouldn't work for my young mathless friend.. Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jennyallar at gmail.com Tue Oct 22 04:23:51 2013 From: jennyallar at gmail.com (Jenny Allar) Date: Mon, 21 Oct 2013 22:23:51 -0400 Subject: [Tutor] Fwd: Re: Passing arguments? In-Reply-To: <526452AB.3060600@gmail.com> References: <5263E7F0.1040301@gmail.com> <526452AB.3060600@gmail.com> Message-ID: Thank you all for your help with this program. Each of your answers helped me piece together an understanding of the assignment. After several days and clearly over-thinking the entire process, I ended up using the following code: def main (): name = input("Please enter the name of the product: ") weight = float(input("Please enter the weight of the product in pounds: ")) cal_shiprate (name, weight) def cal_shiprate(product_name, product_weight): if product_weight < 10: ship_rate = 1.5 elif product_weight >= 10 and product_weight < 25: ship_rate = 1.45 else: ship_rate = 1.4 total = product_weight * ship_rate print("") print(product_name, "weight in pounds ", format (product_weight, '9,.2f')) print ("Your total to ship", product_name, "is: $", format (total, '9,.2f')) main () On Sun, Oct 20, 2013 at 6:01 PM, Ricardo Ar?oz wrote: > Sorry, I sent this answer to the OP directly and not to the list. > > -------- Mensaje original -------- Asunto: Re: [Tutor] Passing arguments? Fecha: > Sun, 20 Oct 2013 11:25:52 -0300 De: Ricardo Ar?oz A: > Jenny Allar > > > El 20/10/13 01:20, Jenny Allar escribi?: > > I've written the code below the assignment, and I think I have > everything covered in terms of asking the user for the information I need > and somehow calculating costs, but I'm just ridiculously confused on the > order and placement of the functions and components of this program- > specifically the shiprate variable. Thank you in advance for any help. > > > Ok, just a couple of things first. > > - Your assignment specifically says 'always use "while loops" to validate' > but I see no loop at all in your code. You might want to look into it. > > - What your assignment points to when it says to use "while loops" is > that you should validate that what the user inputs is a valid number. If > the user will input something else than a number as the weight then when > you apply the int() function an exception will be flagged and your program > will terminate ungracefully. You may validate input using "exceptions" and > "while loops" (look it up). > > - Your functions should do what their name imply, and preferably do only > one thing. Having a function named calc_weight_large() that also prints the > shipping cost is not good. > > - Your if asks for >= 10 and your elif for <= 10 when the "= 10" case was > already handled by the first if, that is a mistake. Besides which it might > be better looking (though this is a matter of personal preference) if you :: > if weight > 25 > # do something > elif weight > 10 > # do something else > else > # do something entirely different > > - I would structure the program in the following way :: > def main(): > product = in_product() > weight = in_weight() > > if weight > 25 > total = calc_shipping(1.40, weight) > elif weight > 10 > total = calc_shipping(1.45, weight) > else > total = calc_shipping(1.50, weight) > print_data(product, weight, total) > > This is my assignment: > > Write a program that asks a user for the name of a product that they are > ordering online and its weight. The program must calculate the cost of > shipping the product using the following cost structure. If it weighs less > than 10 pounds the cost is $1.50 per pound, if it is 10 pounds or more and > less than 25 pounds then the cost is $1.45 per pound. If the weight is 25 > pounds or more the cost is $1.40 per pound. You may get the data from the > user in main. You must print the name of the product, the weight and the > cost of shipping in a separate function. > > > > **********NOTE: ALWAYS USE ?WHILE LOOPS? To Validate******************** > # This program uses an if-else statement > > # It asks for the name of a product and the weight of that product. > # It then determines the shipping cost as defined by the weight. > # > # Variable Type Purpose > # product string hold for name of product > # weight float hold for weight of product > # > > def main (): > product = input("Please enter the name of the product: ") > weight = int(input("Please enter the weight of the product: ")) > > print('Product:', product) > print('Weight:', weight) > > if weight <= 10: > shiprate = 1.5 > calc_weight_small(weight, shiprate) > elif weight >= 10 and weight <= 25: > shiprate = 1.45 > calc_weight_medium(weight, shiprate) > else: > shiprate = 1.4 > calc_weight_large(weight, shiprate) > > # Calculate shipping cost for product less than 10 pounds > def cacl_weight_small(weight, shiprate): > shiprate = 1.5 > total = weight * shiprate > > > # Calculate shipping cost for product between 10 and 25 pounds. > def calc_weight_medium(weight, shiprate): > shiprate = 1.45 > total = weight * shiprate > > > # Calculate shipping cost for product over 25 pounds. > # > #This function calculates and prints the total cost > # based on the weight category the product falls into > # Variable Type Purpose > > # weight float weight of product > # shiprate float cost per pound > # total float total cost to ship product > # > def calc_weight_large(weight, shiprate): > shiprate = 1.4 > total = weight * shiprate > print () > print ("The cost to ship", product, "is: $", format (total, > '9,.2f')) > > main () > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From s.shall at virginmedia.com Tue Oct 22 14:42:43 2013 From: s.shall at virginmedia.com (Sydney Shall) Date: Tue, 22 Oct 2013 13:42:43 +0100 Subject: [Tutor] [OT] Programming practice was: Re: string list in alphabetical! In-Reply-To: References: <20131021111652.GJ7989@ando> <52650E57.10204@gmail.com> <20131021230703.GK7989@ando> Message-ID: <526672C3.5030002@virginmedia.com> On 22/10/2013 00:42, Alan Gauld wrote: > On 22/10/13 00:07, Steven D'Aprano wrote: > >>> I'd like to upgrade that process :D ... >>> >>> 1) think about your problem >>> 2) if there are some heplful libraries that can make it way easier, >>> use them >>> 3) write some code >>> 4) fix the bugs until it'll run >>> 5) write unittests >>> 6) test if it works correctly and if unittests pass >>> 7) repeat until done >> >> >> Heh, very true! But the most important step is step 1, > > I agree. I've recently started coaching the son of a friend in > computing for his new school (he is effectively a year behind > his new classmates). They use VB6 but at a level I can cope with! :-) > > The interesting thing however is that the schools have not taught > any kind of approach to problem solving, they just give a homework > assignment and expect them to produce code. My friend wants to > dive into Vuisual Studio to start work immediately. I've been > trying to get him to adopt a workflow where he writes on paper > an informal "use case" description of the solution and if > necessary a pseudo code design. But it's been a real challenge > to get him to slow down and understand exactly what he is being > asked to do before diving into code. (Some of that is just > natural youthful impatience, but mostly it's lack of instruction > in an alternative! :-) > Alan, I am a newcomer to Python programing. Could you please explain exactly what you mean by 'an informal "use case" description of the solution ..'? I am not clear how this differs from pseudo code design. Thanks to you all for your generous and always invaluable help. Sydney -- Sydney Shall -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Tue Oct 22 15:13:24 2013 From: bgailer at gmail.com (bob gailer) Date: Tue, 22 Oct 2013 09:13:24 -0400 Subject: [Tutor] [OT] Programming practice was: Re: string list in alphabetical! In-Reply-To: <1382428558.39910.YahooMailNeo@web186002.mail.ir2.yahoo.com> References: <20131021111652.GJ7989@ando> <52650E57.10204@gmail.com> <20131021230703.GK7989@ando> <1382428558.39910.YahooMailNeo@web186002.mail.ir2.yahoo.com> Message-ID: <526679F4.3010807@gmail.com> I am glad we are having this discussion. It helps me understand the plight of some of our posters. I had the benefit of a good school system, plus attending a technical high school and a college of engineering. In the early 90's I was an adjunct professor at the University of Denver's "University College" - evening school for adults seeking an MBA. Each class met for 2 hours once a week for 5 weeks. No labs. My job was to teach Pascal as a first programming language. My students had taken one prerequisite - Introduction To Programming. I built my class based on the students' having met the prerequisite. One class of mine were struggling with certain fundamental concepts. Turns out the Intro class had failed to do its job! One outcome is that I was fired for failing to teach Pascal. BTW Python did not exist then, and I have always disliked Pascal. As adjunct professor for a similar program at Regis University (Denver) I was given an Analysis class to teach. My supervisor created a brand new course. The first time I saw the materials was the first night of the class! No one had a chance to examine the materials beforehand! That class was -`difficult for me and the students. On the bright side in the 80's I taught daytime adult classes in computing for the Boeing company. I was free to change classes that had poor materials to (IMHO) good materials. It was almost always fun and I almost always got really good evaluations. I recall one student struggling with his first Basic program. I recommended he walk thru it line by line, and I demonstrated that technique. Amazed he exclaimed "In that much detail?". -- Bob Gailer 919-636-4239 Chapel Hill NC From alan.gauld at btinternet.com Tue Oct 22 15:14:28 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 22 Oct 2013 14:14:28 +0100 Subject: [Tutor] Fwd: Re: Passing arguments? In-Reply-To: References: <5263E7F0.1040301@gmail.com> <526452AB.3060600@gmail.com> Message-ID: On 22/10/13 03:23, Jenny Allar wrote: > I ended up using the following code: One wee improvement you could consider: > def cal_shiprate(product_name, product_weight): > if product_weight < 10: > ship_rate = 1.5 > elif product_weight >= 10 and product_weight < 25: > ship_rate = 1.45 > else: > ship_rate = 1.4 > > total = product_weight * ship_rate > > print("") > print(product_name, "weight in pounds ", format > (product_weight, '9,.2f')) > print ("Your total to ship", product_name, "is: $", format > (total, '9,.2f')) The function is called cal_shiprate but it does more than that it prints it out too. Its usually a bad idea to mix calculations and display in the same function so maybe you could just return the total and do the printing in the main function? That way you don't need to pass in the product name, which is not required for the calculation. Also for the printing part the string formatting mechanism in Python doesn't work quite the way you have it. format() is a method of the string not a separate function. So your main() would end up looking something like: def main (): name = input("Please enter the name of the product: ") weight = float(input("Enter weight of product in pounds: ")) cost = cal_shiprate (weight) print("{} weight in pounds {:<9.2f}".format( product_name,product_weight)) print("Your total to ship {} is: {:>10}{:<9.2f}".format( product_name, '$', cost)) Just a minor tweak. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From ricaraoz at gmail.com Tue Oct 22 15:21:17 2013 From: ricaraoz at gmail.com (=?windows-1252?Q?Ricardo_Ar=E1oz?=) Date: Tue, 22 Oct 2013 10:21:17 -0300 Subject: [Tutor] Fwd: Re: Passing arguments? In-Reply-To: References: <5263E7F0.1040301@gmail.com> <526452AB.3060600@gmail.com> Message-ID: <52667BCD.8020807@gmail.com> - Did you notice your assignment specifically asks for a "while" loop for validation? That means you are expected to validate input. Run your program and when the program asks "Please enter the weight of the product in pounds: " answer "123...this is a mistake", what does it happen? Your program should answer "That is not a valid weight" and ask for the weight again. Does it? (tip: you should be using "while" and "on error") - You have a function named cal_shiprate(), according to it's name this function should calculate the shipping rate NO MORE. But your function also prints not only the shipping rate but some other info too. So you either name your function cal_shiprate_and_print_with_prodname_and_weightf() or your function should ONLY calculate the shipping rate and you should have ANOTHER function to print the info. The recommended approach would be the second one. El 21/10/13 23:23, Jenny Allar escribi?: > Thank you all for your help with this program. Each of your answers > helped me piece together an understanding of the assignment. After > several days and clearly over-thinking the entire process, I ended up > using the following code: > > def main (): > name = input("Please enter the name of the product: ") > weight = float(input("Please enter the weight of the product in > pounds: ")) > > cal_shiprate (name, weight) > > def cal_shiprate(product_name, product_weight): > > if product_weight < 10: > ship_rate = 1.5 > elif product_weight >= 10 and product_weight < 25: > ship_rate = 1.45 > else: > ship_rate = 1.4 > > total = product_weight * ship_rate > > print("") > print(product_name, "weight in pounds ", format > (product_weight, '9,.2f')) > print ("Your total to ship", product_name, "is: $", format > (total, '9,.2f')) > > > main () > > > > > On Sun, Oct 20, 2013 at 6:01 PM, Ricardo Ar?oz > wrote: > > Sorry, I sent this answer to the OP directly and not to the list. > > -------- Mensaje original -------- > Asunto: Re: [Tutor] Passing arguments? > Fecha: Sun, 20 Oct 2013 11:25:52 -0300 > De: Ricardo Ar?oz > A: Jenny Allar > > > > El 20/10/13 01:20, Jenny Allar escribi?: >> I've written the code below the assignment, and I think I have >> everything covered in terms of asking the user for the >> information I need and somehow calculating costs, but I'm just >> ridiculously confused on the order and placement of the functions >> and components of this program- specifically the shiprate >> variable. Thank you in advance for any help. >> > > Ok, just a couple of things first. > > - Your assignment specifically says 'always use "while loops" to > validate' but I see no loop at all in your code. You might want to > look into it. > > - What your assignment points to when it says to use "while > loops" is that you should validate that what the user inputs is a > valid number. If the user will input something else than a number > as the weight then when you apply the int() function an exception > will be flagged and your program will terminate ungracefully. You > may validate input using "exceptions" and "while loops" (look it up). > > - Your functions should do what their name imply, and preferably > do only one thing. Having a function named calc_weight_large() > that also prints the shipping cost is not good. > > - Your if asks for >= 10 and your elif for <= 10 when the "= 10" > case was already handled by the first if, that is a mistake. > Besides which it might be better looking (though this is a matter > of personal preference) if you :: > if weight > 25 > # do something > elif weight > 10 > # do something else > else > # do something entirely different > > - I would structure the program in the following way :: > def main(): > product = in_product() > weight = in_weight() > > if weight > 25 > total = calc_shipping(1.40, weight) > elif weight > 10 > total = calc_shipping(1.45, weight) > else > total = calc_shipping(1.50, weight) > print_data(product, weight, total) > >> This is my assignment: >> >> Write a program that asks a user for the name of a product that >> they are ordering online and its weight. The program must >> calculate the cost of shipping the product using the following >> cost structure. If it weighs less than 10 pounds the cost is >> $1.50 per pound, if it is 10 pounds or more and less than 25 >> pounds then the cost is $1.45 per pound. If the weight is 25 >> pounds or more the cost is $1.40 per pound. You may get the data >> from the user in main. You must print the name of the product, >> the weight and the cost of shipping in a separate function. >> >> *_*********NOTE: ALWAYS USE ?WHILE LOOPS? To >> Validate*******************_* >> >> # This program uses an if-else statement >> >> # It asks for the name of a product and the weight of that product. >> # It then determines the shipping cost as defined by the weight. >> # >> # Variable Type Purpose >> # product string hold for name of product >> # weight float hold for weight of product >> # >> >> def main (): >> product = input("Please enter the name of the product: ") >> weight = int(input("Please enter the weight of the product: ")) >> >> print('Product:', product) >> print('Weight:', weight) >> >> if weight <= 10: >> shiprate = 1.5 >> calc_weight_small(weight, shiprate) >> elif weight >= 10 and weight <= 25: >> shiprate = 1.45 >> calc_weight_medium(weight, shiprate) >> else: >> shiprate = 1.4 >> calc_weight_large(weight, shiprate) >> >> # Calculate shipping cost for product less than 10 pounds >> def cacl_weight_small(weight, shiprate): >> shiprate = 1.5 >> total = weight * shiprate > >> # Calculate shipping cost for product between 10 and 25 pounds. >> def calc_weight_medium(weight, shiprate): >> shiprate = 1.45 >> total = weight * shiprate > >> # Calculate shipping cost for product over 25 pounds. >> # >> #This function calculates and prints the total cost >> # based on the weight category the product falls into >> # Variable Type Purpose >> >> # weight float weight of product >> # shiprate float cost per pound >> # total float total cost to ship product >> # >> def calc_weight_large(weight, shiprate): >> shiprate = 1.4 >> total = weight * shiprate >> print () >> print ("The cost to ship", product, "is: $", format >> (total, '9,.2f')) >> >> main () >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Oct 22 15:25:48 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 22 Oct 2013 14:25:48 +0100 Subject: [Tutor] [OT] Programming practice was: Re: string list in alphabetical! In-Reply-To: <526672C3.5030002@virginmedia.com> References: <20131021111652.GJ7989@ando> <52650E57.10204@gmail.com> <20131021230703.GK7989@ando> <526672C3.5030002@virginmedia.com> Message-ID: On 22/10/13 13:42, Sydney Shall wrote: >> trying to get him to adopt a workflow where he writes on paper >> an informal "use case" description of the solution and if >> necessary a pseudo code design. > Could you please explain exactly what you mean by 'an informal "use > case" description of the solution ..'? > I am not clear how this differs from pseudo code design. OK, a use case is a requirements capture technique frequently used by software engineers to capture the behaviour of systems from the users perspective. There are whole books written on this stuff so for my student I've greatly simplified the technique. A normal use case is written like a dialog between the user and system, like so: 1)User starts system 2)System presents login screen 3)User enters name and password 4)System presents main screen 5)User Select File->New 6)System presents list of templates 7)User selects New Blodgit 8)System resents blodgit config screen ... And so on. It doesn't say anything about how the system will do these things but it presents a visualisation of how the system should present itself and interact wit the user. In the industrialised version we would also list alternate steps after the "happy path" case has been described such as 4a) System displays error message and login scren 4b) User logs in with correct data 4c) continue at 4 I haven't tried that aspect with my student yet. Once you have the interaction clear you can look at each step the computer does and design it in pseudo code. Search wikipedia for lots more on use cases and their finer points. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Tue Oct 22 15:44:42 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 22 Oct 2013 14:44:42 +0100 Subject: [Tutor] Fwd: Re: Passing arguments? In-Reply-To: <52667BCD.8020807@gmail.com> References: <5263E7F0.1040301@gmail.com> <526452AB.3060600@gmail.com> <52667BCD.8020807@gmail.com> Message-ID: On 22/10/13 14:21, Ricardo Ar?oz wrote: > - Did you notice your assignment specifically asks for a "while" loop > for validation? ... (tip: you should be using "while" and "on > error") on error? You're not thinking of VB by any chance? :-) In Python it would be a try/except block or maybe a straight if/else test for a beginner. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From ricaraoz at gmail.com Tue Oct 22 15:55:55 2013 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Tue, 22 Oct 2013 10:55:55 -0300 Subject: [Tutor] Fwd: Re: Passing arguments? In-Reply-To: References: <5263E7F0.1040301@gmail.com> <526452AB.3060600@gmail.com> <52667BCD.8020807@gmail.com> Message-ID: <526683EB.8020208@gmail.com> El 22/10/13 10:44, Alan Gauld escribi?: > On 22/10/13 14:21, Ricardo Ar?oz wrote: >> - Did you notice your assignment specifically asks for a "while" loop >> for validation? ... (tip: you should be using "while" and "on >> error") > > on error? > You're not thinking of VB by any chance? :-) > > In Python it would be a try/except block or maybe a straight if/else > test for a beginner. > LOL and blush. Sorry, meant try/except (I was thinking VFP). Wouldn't if/else be more difficult when validating if an input is a valid float? I find try/except easier. From breamoreboy at yahoo.co.uk Tue Oct 22 17:33:34 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 22 Oct 2013 16:33:34 +0100 Subject: [Tutor] Fwd: Re: Passing arguments? In-Reply-To: References: <5263E7F0.1040301@gmail.com> <526452AB.3060600@gmail.com> Message-ID: On 22/10/2013 03:23, Jenny Allar wrote: Plenty of sound advice as always so I'll just point out that... > elif product_weight >= 10 and product_weight < 25: can be written as elif 10 <= product_weight < 25: -- Python is the second best programming language in the world. But the best has yet to be invented. Christian Tismer Mark Lawrence From shennig93 at googlemail.com Tue Oct 22 16:25:59 2013 From: shennig93 at googlemail.com (Sven Hennig) Date: Tue, 22 Oct 2013 16:25:59 +0200 Subject: [Tutor] Beginner Question Message-ID: Hello, I would like to learn a programming language and have decided to use Python. I have some programming experience and doing well in Python. What really causes me problems is OOP. I'm just dont get it... I'm missing a really Practical example. In every book I've read are the examples of such Class Dog and the function is bark. Has anyone an OOP example for me as it is really used in real code, so I can better understand the concept? I do not know why this is so hard for me. Greetings Sven -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Oct 22 19:01:44 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 22 Oct 2013 18:01:44 +0100 Subject: [Tutor] Fwd: Re: Passing arguments? In-Reply-To: <526683EB.8020208@gmail.com> References: <5263E7F0.1040301@gmail.com> <526452AB.3060600@gmail.com> <52667BCD.8020807@gmail.com> <526683EB.8020208@gmail.com> Message-ID: On 22/10/13 14:55, Ricardo Ar?oz wrote: > Sorry, meant try/except (I was thinking VFP). > Wouldn't if/else be more difficult when validating if an input is a > valid float? I find try/except easier. Maybe, but typical programming classes don't teach try/except till much later in the course. Since the OP is evidently a very new beginner I doubt if they've covered it yet... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Tue Oct 22 19:06:33 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 22 Oct 2013 18:06:33 +0100 Subject: [Tutor] Beginner Question In-Reply-To: References: Message-ID: On 22/10/13 15:25, Sven Hennig wrote: > Hello, I would like to learn a programming language and have decided to > use Python. I have some programming experience and doing well in Python. > What really causes me problems is OOP. Don't worry this is common. The problem with OOP is that it only really becomes useful when you get to bigger programs than a beginner has typically met. So its value is not obvious. For some (slightly) more real world examples try the OOP page in my tutorial with examples using shapes and bank accounts. (see .sig) The other big area where it is used is in GUI programming. On-screen widgets like buttons, menus, sliders etc are naturally modelled as objects. You can then attach methods like onPress to a button or onMove() or position() to a slider. Then as you build your GUI screen you will have klots of instanmces of the objects, multiple buttons, labels, text fields etc. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From amckenzie4 at gmail.com Tue Oct 22 19:26:08 2013 From: amckenzie4 at gmail.com (Andy McKenzie) Date: Tue, 22 Oct 2013 13:26:08 -0400 Subject: [Tutor] Beginner Question In-Reply-To: References: Message-ID: On Tue, Oct 22, 2013 at 10:25 AM, Sven Hennig wrote: > Hello, I would like to learn a programming language and have decided to > use Python. I have some programming experience and doing well in Python. > What really causes me problems is OOP. > I'm just dont get it... I'm missing a really Practical example. In every > book I've read are the examples of such Class Dog and the function is bark > . Has anyone an OOP example for me as it is really used in real code, so > I can better understand the concept? I do not know why this is so hard for > me. > > Greetings > Sven > > The actual code I have is in PHP, so it's not exactly useful to post here, but I can give you an outline of a class I used and found useful. The class was created to help me manipulate network subnets in an interface to handle DHCP and DNS on a server. class subnet: def __init__(cidr): # Do some stuff with the CIDR notation of the subnet (1.2.3.0/24syntax) def netmask: # Calculate the netmask and return it (ie, 255.255.255.0) def first_ip: # Calculate and return the first IP in the range. def last_ip: # Calculate and return the last IP in the range def number_of_addresses: # Calculate the number of usable addresses in the range and return that value The benefit to me was that I could create an instance of the subnet object for a group (say, "lab_1"), and then pull out various information. Calling "lab_1.first_ip()" returns the first possible IP address. That was a lot more readable and a lot more concise than something like "first_ip( 1.2.3.0/24)". I hope this helps! Andy -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Tue Oct 22 19:55:29 2013 From: davea at davea.name (Dave Angel) Date: Tue, 22 Oct 2013 17:55:29 +0000 (UTC) Subject: [Tutor] Beginner Question References: Message-ID: On 22/10/2013 10:25, Sven Hennig wrote: > Hello, I would like to learn a programming language and have decided to use > Python. I have some programming experience and doing well in Python. What > really causes me problems is OOP. > I'm just dont get it... I'm missing a really Practical example. In every > book I've read are the examples of such Class Dog and the function is bark. Has > anyone an OOP example for me as it is really used in real code, so I can > better understand the concept? I do not know why this is so hard for me. > What you may not realize is you're already doing OOP, just by using the standard library. When you open a file (or many other things that can produce a stream of bytes), you get an instance of class file. When you use that instance, you're calling methods of that instance. So when you say: infile = open("myfile.txt,"r") data = infile.readline() you're doing object oriented programming. You don't have to know what kind of thing "infile" is, you just have to know it has methods read(), readline(), close(), etc. When you want to write your own classes, or when you want to make a new class that's related but different from one of the thousands that are standard, that's when it gets interesting. As Alan says, GUI is one place where you'll be wrting your own classes, usually by deriving from one of the GUI library classes. At its most fundamental, a class is a description of how to create and how to manipulate instances. An instance has methods (functions), and attributes (data). When one class is derived from another, it can share some or most of the attributes and behavior of the parent class, but make changes. This helps avoid duplicating code when two things are similar. You're familiar with list and tuple. Those are built-in collection classes, supported explicitly by the language. But if you want your own collection, you may want to make a class for it. The Dog bark() example may seem silly, but a Dog has lots of other methods besides that one, and has lots of attributes (color, breed, health state, owner, etc.). In a sense those attributes are like a list within the Dog, but you want them to have nice names, instead of remembering that the 3rd one is owner. -- DaveA From gregory.key at siemens.com Tue Oct 22 21:20:25 2013 From: gregory.key at siemens.com (Key, Gregory E (E S SF RNA FSF 1 C)) Date: Tue, 22 Oct 2013 19:20:25 +0000 Subject: [Tutor] comma in an assignment Message-ID: <5C28117E8FDB0E4F999E3CB30775EF5901F9A5@USLZUA0EM21MSX.ww017.siemens.net> I understand that a comma in Python is a separator and not an operator. In some of the MatPlotLib examples I see code like this: line1, = ax1.plot(t, y1, lw=2, color='red', label='1 HZ') What does the comma do in an assignment statement? Greg Key This message and any attachments are solely for the use of intended recipients. The information contained herein may include trade secrets, protected health or personal information, privileged or otherwise confidential information. Unauthorized review, forwarding, printing, copying, distributing, or using such information is strictly prohibited and may be unlawful. If you are not an intended recipient, you are hereby notified that you received this email in error, and that any review, dissemination, distribution or copying of this email and any attachment is strictly prohibited. If you have received this email in error, please contact the sender and delete the message and any attachment from your system. Thank you for your cooperation -------------- next part -------------- An HTML attachment was scrubbed... URL: From ml at fam-goebel.de Tue Oct 22 23:21:20 2013 From: ml at fam-goebel.de (Ulrich Goebel) Date: Tue, 22 Oct 2013 23:21:20 +0200 Subject: [Tutor] Howto handle pictures with pyqt Message-ID: <5266EC50.9070307@fam-goebel.de> Hello, for my first python program I try to build a user interface for a litle address database. Therefor I use pyqt to build the formular, and later I will connect it to an existing SQLite DB, using APSW. Besides the "normal" things as name, address, email and others I want to store an image. Normaly that will be given as a file (.jpg, .png, or other type). I would let the user find the picture with a QFileDialog.getOpenFileName() dialog. But what to do after that? Here are my questions: Which widget is able to show the picture? How to show the picture? That means: howto put the picture from the file into the widget? How to put the picture data into an blob(?) column in the database? How to get the data back from there and bring it in the widget? May be there is a tutorial which I didn't find yet? Thank's a lot for any help! Greetings Ulrich -- Ulrich Goebel Paracelsusstr. 120, 53177 Bonn From shennig93 at googlemail.com Tue Oct 22 20:18:28 2013 From: shennig93 at googlemail.com (Sven Hennig) Date: Tue, 22 Oct 2013 20:18:28 +0200 Subject: [Tutor] Beginner Question In-Reply-To: References: Message-ID: Thank you! You guys helped me out alot. @Alan your website is great! Really clearly written. Especially the "Things to remember" part. If you have exercises for me or have a Website with exercises, bring it on. I think this is the best way to learn. 2013/10/22 Dave Angel > On 22/10/2013 10:25, Sven Hennig wrote: > > > Hello, I would like to learn a programming language and have decided to > use > > Python. I have some programming experience and doing well in Python. What > > really causes me problems is OOP. > > I'm just dont get it... I'm missing a really Practical example. In every > > book I've read are the examples of such Class Dog and the function is > bark. Has > > anyone an OOP example for me as it is really used in real code, so I can > > better understand the concept? I do not know why this is so hard for me. > > > > What you may not realize is you're already doing OOP, just by using the > standard library. When you open a file (or many other things that can > produce a stream of bytes), you get an instance of class file. When you > use that instance, you're calling methods of that instance. So when you > say: > > infile = open("myfile.txt,"r") > data = infile.readline() > > you're doing object oriented programming. You don't have to know what > kind of thing "infile" is, you just have to know it has methods read(), > readline(), close(), etc. > > When you want to write your own classes, or when you want to make a new > class that's related but different from one of the thousands that are > standard, that's when it gets interesting. As Alan says, GUI is one > place where you'll be wrting your own classes, usually by deriving from > one of the GUI library classes. > > At its most fundamental, a class is a description of how to create and > how to manipulate instances. An instance has methods (functions), and > attributes (data). When one class is derived from another, it can share > some or most of the attributes and behavior of the parent class, but > make changes. This helps avoid duplicating code when two things are > similar. > > You're familiar with list and tuple. Those are built-in > collection classes, supported explicitly by the language. But if you > want your own collection, you may want to make a class for it. The Dog > bark() example may seem silly, but a Dog has lots of other methods > besides that one, and has lots of attributes (color, breed, health > state, owner, etc.). In a sense those attributes are like a list within > the Dog, but you want them to have nice names, instead of remembering > that the 3rd one is owner. > > > -- > DaveA > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Oct 23 01:51:17 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 23 Oct 2013 00:51:17 +0100 Subject: [Tutor] comma in an assignment In-Reply-To: <5C28117E8FDB0E4F999E3CB30775EF5901F9A5@USLZUA0EM21MSX.ww017.siemens.net> References: <5C28117E8FDB0E4F999E3CB30775EF5901F9A5@USLZUA0EM21MSX.ww017.siemens.net> Message-ID: On 22/10/13 20:20, Key, Gregory E (E S SF RNA FSF 1 C) wrote: > I understand that a comma in Python is a separator and not an operator. > In some of the MatPlotLib examples I see code like this: > line1, = ax1.plot(t, y1, lw=2, color='red', label='1 HZ') > What does the comma do in an assignment statement? Caveat: I know nothing about MatPlotLib... But a comma after a name like that usually means its part of a tuple (a single element tuple) so you could rewrite it like: (line1,) = ax1.plot(t, y1, lw=2, color='red', label='1 HZ') But I've no idea why you'd want to do that or why MatPlotLib apparently does. Maybe someone who uses MatPlotLib will reveal all... A wee bit of experimenting suggests ou can use it to unpack a single valued tuple. So presumably ax1.plot() returns a single value tuple. Without the comma line1 would also be a tuple but with the comma it takes on the value inside instead... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Wed Oct 23 01:54:22 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 23 Oct 2013 00:54:22 +0100 Subject: [Tutor] Beginner Question In-Reply-To: References: Message-ID: On 22/10/13 19:18, Sven Hennig wrote: > Thank you! You guys helped me out alot. > > @Alan your website is great! Really clearly written. Especially the > "Things to remember" part. Glad you like it. Someday (soon!) I'll get round to finishing the v3 version... So much to do, so little time! > If you have exercises for me There are exercises but they are buried in the text. ie suggestions for the reader to try to extend the examples or to write other parallel examples for themselves. There is also a page with suggested projects near the end. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Wed Oct 23 01:56:11 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 23 Oct 2013 00:56:11 +0100 Subject: [Tutor] Howto handle pictures with pyqt In-Reply-To: <5266EC50.9070307@fam-goebel.de> References: <5266EC50.9070307@fam-goebel.de> Message-ID: On 22/10/13 22:21, Ulrich Goebel wrote: > for my first python program I try to build a user interface for a litle > address database. Therefor I use pyqt to build the formular, and later I > will connect it to an existing SQLite DB, using APSW. This list is for beginners to the python language and standard library. Your question is mainly about Qt so will likely get a better response on a Qt or pyQt list/forum. However, I know some readers here do use Qt so you may be in luck... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From sunithanc at gmail.com Wed Oct 23 03:04:57 2013 From: sunithanc at gmail.com (SM) Date: Tue, 22 Oct 2013 21:04:57 -0400 Subject: [Tutor] How to Terminate a Popen call? Message-ID: Hello! I am trying to terminate a Popen session using Popen.terminate() ( using the info at http://docs.python.org/library/subprocess.html and some relevant answers from Stack Overflow). But it doesn't seem to work for me. I am calling Popen to run a command (which runs for a long time) from one thread (thread1) and trying to stop the execution from another thread (thread2) which is running in a loop. In response to a pushButton, the second thread (thread2) invokes the stop method of the first thread which in turn, invokes the terminate() call. Here is the code snippet: class thread1(threading.Thread): def __init__(self, ....): ... ... super(bcThread_allrep_all, self).__init__() self.stoprequest = threading.Event() self.process = None def stopped(self): return self.stoprequest.isSet() def run(self): (process, err) = Popen(self.fwcmd, stdout=PIPE, stderr=PIPE).communicate() if len(err) > 0: # print("Error") # Error handling code else: # print("Success") def stop(self): if self.process is not None: print("TERMINATING THREAD") self.process.terminate() #Popen.terminate(self.process) else: print("process IS NONE ") >From thread2 I am invoking thread1.stop() method, in order to terminate the Popen call. So thread1.stop() is getting invoked, but I see that self.process (which is the value Popen has to return) will have "None" before it finishes. The python.org document suggests to use Popen.terminate() call. So I also tried calling Popen.terminate (as in the commented line above), but it returns the following error (due to the same reason that self.process is None): File "bc_reports_tab.py", line 1733, in stop Popen.terminate(self.process) File "/usr/lib/python3.2/subprocess.py", line 1581, in terminate self.send_signal(signal.SIGTERM) AttributeError: 'NoneType' object has no attribute 'send_signal' So how would I terminate Popen before it has finished executing?? Appreciate any help. Thanks! -Sm -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Wed Oct 23 03:35:06 2013 From: eryksun at gmail.com (eryksun) Date: Tue, 22 Oct 2013 21:35:06 -0400 Subject: [Tutor] comma in an assignment In-Reply-To: <5C28117E8FDB0E4F999E3CB30775EF5901F9A5@USLZUA0EM21MSX.ww017.siemens.net> References: <5C28117E8FDB0E4F999E3CB30775EF5901F9A5@USLZUA0EM21MSX.ww017.siemens.net> Message-ID: On Tue, Oct 22, 2013 at 3:20 PM, Key, Gregory E (E S SF RNA FSF 1 C) wrote: > I understand that a comma in Python is a separator and not an operator. In The comma operator creates a tuple. It has low precedence, so you usually need parentheses. But sometimes the parentheses are redundant such as with a return statement like `return (x, y, z)` vs `return x, y, z`, or on the right-hand side of an assignment: >>> y = 1, 2, 3 >>> y (1, 2, 3) > some of the MatPlotLib examples I see code like this: > > line1, = ax1.plot(t, y1, lw=2, color='red', label='1 HZ') > > What does the comma do in an assignment statement? For an assignment target list, CPython doesn't actually create a tuple. It's a notational tuple used by the compiler. It's present in the abstract syntax tree (creating an AST is an intermediate step in the compilation process); however, the final bytecode does sequence unpacking directly to the target names. Here's the AST for `y, = x`: >>> print ast.dump(ast.parse('y, = x').body[0]) Assign(targets=[Tuple(elts=[Name(id='y', ctx=Store())], ctx=Store())], value=Name(id='x', ctx=Load())) The AST Tuple in the assignment consists of one item, a Name with a Store context. In this case, the compiler generates bytecode to unpack a length 1 sequence and store the item to the name "y". In practice this is pretty simple and intuitive: >>> y, = [1] >>> y 1 >>> x, y, z = 1, 2, 3 >>> x, y, z (1, 2, 3) You can use compile() and dis to see the bytecode itself: >>> dis.dis(compile('y, = x', '', 'exec')) 1 0 LOAD_NAME 0 (x) 3 UNPACK_SEQUENCE 1 6 STORE_NAME 1 (y) 9 LOAD_CONST 0 (None) 12 RETURN_VALUE The argument in UNPACK_SEQUENCE(1) is the number of items to unpack to the frame's stack. For stack-based operations, think of using an RPN calculator. An operator -- in this case a bytecode instruction -- pops its operands off the stack and then pushes the result back on in their place. The more complex the expression, the bigger the stack needs to grow (think of a stack of plates) in order to hold temporary results. Unpacking can also handle more complex structures such as `t, (x, y) = z`: >>> z = [1, [2, 3]] >>> t, (x, y) = z >>> t, x, y (1, 2, 3) If you prefer, you can use square brackets on the left-hand side. The compiled bytecode is the same, whether the left-hand side has Tuple or List types in the AST: >>> [t, [x, y]] = z >>> t, x, y (1, 2, 3) Bytecode comparison: >>> dis.dis(compile('t, (x, y) = z', '', 'exec')) 1 0 LOAD_NAME 0 (z) 3 UNPACK_SEQUENCE 2 6 STORE_NAME 1 (t) 9 UNPACK_SEQUENCE 2 12 STORE_NAME 2 (x) 15 STORE_NAME 3 (y) 18 LOAD_CONST 0 (None) 21 RETURN_VALUE >>> dis.dis(compile('[t, [x, y]] = z', '', 'exec')) 1 0 LOAD_NAME 0 (z) 3 UNPACK_SEQUENCE 2 6 STORE_NAME 1 (t) 9 UNPACK_SEQUENCE 2 12 STORE_NAME 2 (x) 15 STORE_NAME 3 (y) 18 LOAD_CONST 0 (None) 21 RETURN_VALUE After the first unpack, item 0 is popped off the stack and stored to t. Next item 1 (a length 2 sequence) is popped, unpacked, and stored to x and y. From steve at pearwood.info Wed Oct 23 03:50:01 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 23 Oct 2013 12:50:01 +1100 Subject: [Tutor] comma in an assignment In-Reply-To: <5C28117E8FDB0E4F999E3CB30775EF5901F9A5@USLZUA0EM21MSX.ww017.siemens.net> References: <5C28117E8FDB0E4F999E3CB30775EF5901F9A5@USLZUA0EM21MSX.ww017.siemens.net> Message-ID: <20131023015000.GO7989@ando> On Tue, Oct 22, 2013 at 07:20:25PM +0000, Key, Gregory E (E S SF RNA FSF 1 C) wrote: > I understand that a comma in Python is a separator and not an > operator. In some of the MatPlotLib examples I see code like this: > > line1, = ax1.plot(t, y1, lw=2, color='red', label='1 HZ') > > What does the comma do in an assignment statement? It does "sequence unpacking". On the right hand side, commas create a tuple: py> x = 100, 200, 300 py> print(x, type(x)) (100, 200, 300) On the left hand side, you can think of it as if it creates a tuple of names, then assigns to each name with the corresponding item from the other side: py> a, b, c = 100, 200, 300 py> print(a, b, c) 100 200 300 So this example is conceptually like: # make a tuple of names (a, b, c) # line them up with a sequence on the right hand side (a, b, c) = (100, 200, 300) # unpack the sequence on the right and assign item-by-item a <-- item 0 = 100 b <-- item 1 = 200 c <-- item 2 = 300 So a single comma on the left, like this: a, = function(args, more_args) is equivalent to this: temp <-- function(args, more_args) a <-- temp[0] delete temp except of course the name "temp" isn't literally used. The values on the right don't have to be a tuple, any sequence will do, such as strings, lists, or iterators: py> a, b, c = "XYZ" py> print(a, b, c) X Y Z However, there does have to be the same number of items on both sides: py> a, b, c = "xy" Traceback (most recent call last): File "", line 1, in ValueError: need more than 2 values to unpack -- Steven From eryksun at gmail.com Wed Oct 23 04:33:56 2013 From: eryksun at gmail.com (eryksun) Date: Tue, 22 Oct 2013 22:33:56 -0400 Subject: [Tutor] How to Terminate a Popen call? In-Reply-To: References: Message-ID: On Tue, Oct 22, 2013 at 9:04 PM, SM wrote: > def run(self): > (process, err) = Popen(self.fwcmd, stdout=PIPE, > stderr=PIPE).communicate() > if len(err) > 0: > # print("Error") > # Error handling code > else: > # print("Success") Store the Popen() instance before calling its communicate() method: p = self.process = Popen(self.fwcmd, stdout=PIPE, stderr=PIPE) out, err = p.communicate() if p.returncode: raise CalledProcessError(p.returncode, self.fwcmd, (out, err)) communicate() sets returncode; an error is indicated by a non-zero value. Some programs write non-error information to stderr, so use the return code to detect an error. From eryksun at gmail.com Wed Oct 23 05:05:55 2013 From: eryksun at gmail.com (eryksun) Date: Tue, 22 Oct 2013 23:05:55 -0400 Subject: [Tutor] comma in an assignment In-Reply-To: <20131023015000.GO7989@ando> References: <5C28117E8FDB0E4F999E3CB30775EF5901F9A5@USLZUA0EM21MSX.ww017.siemens.net> <20131023015000.GO7989@ando> Message-ID: On Tue, Oct 22, 2013 at 9:50 PM, Steven D'Aprano wrote: > However, there does have to be the same number of items on both sides: > > py> a, b, c = "xy" > Traceback (most recent call last): > File "", line 1, in > ValueError: need more than 2 values to unpack 3.x extends sequence unpacking to support starred expressions: >>> a, b, *c = 'xy' >>> a, b, c ('x', 'y', []) >>> a, b, *c = 'xyz' >>> a, b, c ('x', 'y', ['z']) >>> a, b, c, *rest = 'xyzpdq' >>> a, b, c, rest ('x', 'y', 'z', ['p', 'd', 'q']) http://www.python.org/dev/peps/pep-3132 From steve at pearwood.info Wed Oct 23 05:27:21 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 23 Oct 2013 14:27:21 +1100 Subject: [Tutor] Beginner Question In-Reply-To: References: Message-ID: <20131023032720.GP7989@ando> On Tue, Oct 22, 2013 at 04:25:59PM +0200, Sven Hennig wrote: > Hello, I would like to learn a programming language and have decided to use > Python. I have some programming experience and doing well in Python. What > really causes me problems is OOP. > I'm just dont get it... I'm missing a really Practical example. In every > book I've read are the examples of such Class Dog and the function is bark. Has > anyone an OOP example for me as it is really used in real code, so I can > better understand the concept? I do not know why this is so hard for me. I can sympathise. You wouldn't believe how long it took me to really grok object-oriented programming. I just didn't get it, until I started thinking of OOP as being just syntax for keeping functions (called "methods") close to the data they belong with. There is more to OOP than that, but that was my first step: OOP helps you keep your functions close to the data they work with. In conventional procedural languages, if you had a function that operates on a string, you would write something like this: Struct string = ... # define a string here # later in the file, perhaps many pages later: function upper(some_string): result = make a new string for char in some_string: if char = 'a': add 'A' to result if char = 'b': add 'B' to result ... if char = 'z': add 'Z' to result else add char to result return result (Aside: don't program uppercase like that! There are more efficient ways, and in Python, it is already provided!) So the problem with this is that your data (say, strings) and the functions that operate on your data (say, upper, lower, and many others) can end up being defined far away from each other, which makes editing the code painful. With OOP, the first change is that the syntax is changed to bring the functions (called "methods") together with their data: class string: # put code here to define the "string" data class # now define all the functions that work on strings def upper(self): # code for "upper" goes here def lower(self): # code for "lower" goes here # any other string methods go here Then, later, instead of writing: mystring = "blah blah blah" print upper(mystring) # this doesn't work since upper is a method we have a slightly different syntax: print mystring.upper() # use this instead That's all you need to know to start using object oriented programming in Python! Many operations are implemented as methods, for instance strings have upper and lower methods, lists have append and remove methods, and many more. You'll soon learn the operations like len() that aren't methods, but old-school functions. As I said, there is a lot more to OOP than just making it easier to organise your program files, but that was the realisation that helped me get OOP. The next step is to understand "inheritance". Inheritance means that you can create a new class (the subclass) which inherits -- borrows -- data and methods from another class (the super class). Here is a stupid example: class StupidStr(str): # inherit from str def upper(self): return "***" This class StupidStr is exactly like the ordinary string, except the upper() method has been replaced to do something trivial and stupid: py> s = StupidStr("Hello World") py> s.lower() # inherits the behaviour of normal str 'hello world' py> s.upper() # overrides the normal upper method for my stupid one '***' Why would you do this? Well, obviously you wouldn't do something so stupid except as an exercise. It's hard to give *simple* real life examples that aren't contrived, but here's one that works for me: Suppose you're writing software to control a model car. You might start off by collecting some basic defaults: class DefaultModelCar: model = "Unknown" BRAKE_COMMAND = "B" FORWARD_COMMAND = "F" REVERSE_COMMAND = "R" ACCELERATE_COMMAND = "A" TURN_LEFT_COMMAND = "TL" TURN_RIGHT_COMMAND = "TR" def send_command(self, command): # Send a command to the model car. # Put the code here to actually communicate with the car. ... def forward(self): # Drive forward. if self.direction == "Reverse": # Brake first, then move forward. self.stop() self.send_command(self.FORWARD_COMMAND) self.send_command(self.ACCELERATE_COMMAND) self.direction = "Forward" def reverse(self): if self.direction == "Forward": self.stop() self.send_command(self.REVERSE_COMMAND) self.send_command(self.ACCELERATE_COMMAND) self.direction = "Reverse" def stop(self): self.send_command(self.BRAKE_COMMAND) self.direction = "Stopped" and so on. Now, this default set of commands probably won't work for any actual model car, but at least you can run it and test that it works as you expect: car = DefaultModelCar() # Create a car instance car.forward() if car.direction == "Forward": print("Okay, car is moving forward") else: print("There's a problem...") car.stop() Now you want to control a couple of specific models: class SpeedyCar(DefaultModelCar): model = "Speedy Car Model X" BRAKE_COMMAND = "10" FORWARD_COMMAND = "11" REVERSE_COMMAND = "12" ACCELERATE_COMMAND = "34" TURN_LEFT_COMMAND = "41" TURN_RIGHT_COMMAND = "42" class MegaCar13(DefaultModelCar): model = "Mega Car Model M13" BRAKE_COMMAND = "%9" FORWARD_COMMAND = "%1" REVERSE_COMMAND = "%2" ACCELERATE_COMMAND = "%6" TURN_LEFT_COMMAND = "%7" TURN_RIGHT_COMMAND = "%8" And that's it! If you've done your programming right, most of the hard work has been done in the default class, and all you need to do is change a few settings, and it should just work. (In reality, each model car will probably have it's own special way of receiving commands. But let's just pretend that all model cars accept commands the same way, only the commands themselves are different.) Sometimes you'll find that you need to override a method with one a little different: class MegaCar14(MegaCar13): model = "Mega Car Model M14" # Brakes are crap on the M14. def stop(self): for i in range(5): self.send_command(self.BRAKE_COMMAND) self.direction = "Stopped" But everything else works just as before. Now you can have a race: a = SpeedyCar() b = MegaCar13 c = MegaCar14 cars = [a, b, c] # Start the cars, let them drive for 10 seconds, and see which gets # further. for car in cars: car.forward() time.sleep(10) for car in cars: car.stop() Notice that even though each model car needs different commands to control it, all those details are hidden away inside the class. From the outside, you use exactly the same commands to control it: forward, stop, reverse, etc. -- Steven From fomcl at yahoo.com Wed Oct 23 09:58:26 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Wed, 23 Oct 2013 00:58:26 -0700 (PDT) Subject: [Tutor] Beginner Question In-Reply-To: <20131023032720.GP7989@ando> Message-ID: <1382515106.92431.YahooMailBasic@web163801.mail.gq1.yahoo.com> -------------------------------------------- On Wed, 10/23/13, Steven D'Aprano wrote: Subject: Re: [Tutor] Beginner Question To: tutor at python.org Date: Wednesday, October 23, 2013, 5:27 AM On Tue, Oct 22, 2013 at 04:25:59PM +0200, Sven Hennig wrote: >? Hello, I would like to learn a programming language and have decided to use > Python. I have some programming experience and doing well in Python. What > really causes me problems is OOP. > I'm just dont get it... I'm missing a really Practical example. In every > book I've read are the examples of such Class Dog and the function is bark. Has > anyone an OOP example for me as it is really used in real code, so I can > better understand the concept? I do not know why this is so hard for me. I can sympathise. You wouldn't believe how long it took me to really grok object-oriented programming. I just didn't get it, until I started thinking of OOP as being just syntax for keeping functions (called "methods") close to the data they belong with. There is more to OOP than that, but that was my first step: OOP helps you keep your functions close to the data they work with. That's all you need to know to start using object oriented programming in Python! Many operations are implemented as methods, for instance strings have upper and lower methods, lists have append and remove methods, and many more. You'll soon learn the operations like len() that aren't methods, but old-school functions. ==> This reminded me of a text by Guido van Rossum (I can't find the original page): http://effbot.org/pyfaq/why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list.htm So the built-in 'len()' is *really* a function, but calls to len() implemented by __len__ are method calls *disguised* as function calls? I sometimes find it easier to write calls to special methods the "normal" way, e.g. instead of "x + y" just write it like "x.__add__(y)" This makes special methods more like other methods and therefore easier to understand, to me at least. Albert-Jan PS: sorry about the lack of quoting. Yahoo mail was "upgraded" and now all sorts of stuff stops working, times out, etc. From corinne.landers at live.com Wed Oct 23 09:25:42 2013 From: corinne.landers at live.com (Corinne Landers) Date: Wed, 23 Oct 2013 18:25:42 +1100 Subject: [Tutor] Beginner question on classes Message-ID: Hi guys, I need a bit of help. I'm writing a class, and in the main function I'm trying to say if this method gets called, do this. I'm trying things like: program = AnimalClass(x,y,z)for i in range(x): for j in range(y): for k in range(z): animal = program.animal() if animal: if isinstance(animal,moose): print("There is a moose here") It's clearly not correct because it's giving me all sorts of grief, but if anyone knows how to do this correctly I'd very much appreciate it! Corrine -------------- next part -------------- An HTML attachment was scrubbed... URL: From oscar.j.benjamin at gmail.com Wed Oct 23 11:20:56 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Wed, 23 Oct 2013 10:20:56 +0100 Subject: [Tutor] Beginner Question In-Reply-To: <1382515106.92431.YahooMailBasic@web163801.mail.gq1.yahoo.com> References: <20131023032720.GP7989@ando> <1382515106.92431.YahooMailBasic@web163801.mail.gq1.yahoo.com> Message-ID: On 23 October 2013 08:58, Albert-Jan Roskam wrote: > So the built-in 'len()' is *really* a function, but calls to len() implemented by __len__ are method calls *disguised* as function calls? I sometimes find it easier to write calls to special methods the "normal" way, e.g. instead of "x + y" just write it like "x.__add__(y)" This makes special methods more like other methods and therefore easier to understand, to me at least. Please don't do that. Firstly it looks horrible. Secondly they're not equivalent. The equivalent of x + y is operator.add(x, y) but don't use that either. It's not easier to understand and it's less efficient. When you wrate a+b the interpreter actually calls a bunch of different methods: a.__add__(b), b.__radd__(a), a.__coerce__(b) etc. I don't know the full sequence and it's not consistent across Python implementations. Eryksun recently posted a good example showing how a == b is handled: https://mail.python.org/pipermail/tutor/2013-July/097110.html Oscar From alan.gauld at btinternet.com Wed Oct 23 11:26:53 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 23 Oct 2013 10:26:53 +0100 Subject: [Tutor] Beginner question on classes In-Reply-To: References: Message-ID: On 23/10/13 08:25, Corinne Landers wrote: > Hi guys, > > I need a bit of help. > I'm writing a class, and in the main function I'm trying to say if this > method gets called, do this. What you are actually doing is "if the method returns a truth-like value do this." Not quite the same thing, but much easier! > I'm trying things like: > > program = AnimalClass(x,y,z) > for i in range(x): > for j in range(y): > for k in range(z): > animal = program.animal() > if animal: > if isinstance(animal,moose): > print("There is a moose here") The block below for k... needs more indentation and The final print needs yet another level of indentation... > It's clearly not correct because it's giving me all sorts of grief, Could you be more specific? What kind of grief? Error messages? Then send the full message here. Your computer crashes? It doesn't print a message you expected? While you are at it which Python version and OS are you using? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From oscar.j.benjamin at gmail.com Wed Oct 23 11:27:45 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Wed, 23 Oct 2013 10:27:45 +0100 Subject: [Tutor] Beginner question on classes In-Reply-To: References: Message-ID: On 23 October 2013 08:25, Corinne Landers wrote: > Hi guys, Hi Corrine, > I need a bit of help. > I'm writing a class, and in the main function I'm trying to say if this > method gets called, do this. > I'm trying things like: > > program = AnimalClass(x,y,z) > for i in range(x): > for j in range(y): > for k in range(z): > animal = program.animal() > if animal: > if isinstance(animal,moose): > print("There is a moose here") > > It's clearly not correct because it's giving me all sorts of grief, but if > anyone knows how to do this correctly I'd very much appreciate it! I'm sure someone will help you but you haven't really given enough information yet. Is the code you posted the whole of your program? If so please say so explicitly because it looks like only part of a program to me and you should show the whole code for anyone to understand what you're doing. Also you say that it is giving you grief but we need more than that. Is it showing an error message? If so please copy/paste the whole error message and traceback. Here's an example showing what happens when I run your program as shown above (saved into a file called tmp.py): $ python tmp.py File "tmp.py", line 5 animal = program.animal() ^ IndentationError: expected an indented block What that error means is that you need to indent everything inside the 3rd for loop on line 5. Oscar From davea at davea.name Wed Oct 23 12:45:46 2013 From: davea at davea.name (Dave Angel) Date: Wed, 23 Oct 2013 10:45:46 +0000 (UTC) Subject: [Tutor] Beginner question on classes References: Message-ID: On 23/10/2013 03:25, Corinne Landers wrote: > --> >
Hi guys, 

I need a bit of help. 
I'm writing a class, and in the main function I'm trying to say if this method gets called, do this. 
I'm trying things like:

program = AnimalClass(x,y,z)
for i in range(x):
   for j in range(y):
      for k in range(z):
      animal = program.animal()
      if animal: 
          if isinstance(animal,moose):
          print("There is a moose here")

It's clearly not correct because it's giving me all sorts of grief, but if anyone knows how to do this correctly I'd very much appreciate it!

Corrine

> > Hi, and welcome to Python, and to the Python tutor list. Please start by telling us what Python version you're using, and what OS. Please post here using a text message, not html, as many email programs (apparently including yours) cannot correctly convert the html to text. Your entire program fragment appears on one line in my newsreader. And people like me can see the html, but not display it. This is a text newsgroup. Studying other people's responses that do have html abilities, I can see that you did post an indented code fragment, so I'll copy that here and comment on it. > program = AnimalClass(x,y,z) > for i in range(x): > for j in range(y): > for k in range(z): > animal = program.animal() > if animal: > if isinstance(animal,moose): > print("There is a moose here") Your problem statement was: "if this method gets called, do this" No idea which of these is "this method," nor what you intend by "do this." And you needn't test whether it's being called, since presumably you're calling it. Usually, you test the return value of a method, but that's not what you're saying. Just looking at the code in isolation, I can see that you'll get an indentation error on the line assigning to animal. You have to indent the body of any for statement. Next, it appears you don't use i, j and k. So are you intending to just do the same thing x*y*z times? If so, then you just should use one loop, and multiple them together. Does program.animal() return the same value each time, or is it somehow supposed to guess the values of i, j, and k ? Is moose a class name, defined elsewhere that you didn't include? Then it ought to be capitalized, to make that obvious. It's just a convention, but following conventions will make your code easier to read. I know that many classes in the standard lib are not capitalized, but that's mostly because the names were established many many years ago, some perhaps before there was the ability to write user classes. Pep-8 is the place where such conventions are described. -- DaveA From sunithanc at gmail.com Wed Oct 23 13:13:55 2013 From: sunithanc at gmail.com (SM) Date: Wed, 23 Oct 2013 07:13:55 -0400 Subject: [Tutor] How to Terminate a Popen call? In-Reply-To: References: Message-ID: Hello eryksun, Thanks, very much, for the very quick and helpful reply. It fixed my problem. -Sm On Tue, Oct 22, 2013 at 10:33 PM, eryksun wrote: > On Tue, Oct 22, 2013 at 9:04 PM, SM wrote: > > def run(self): > > (process, err) = Popen(self.fwcmd, stdout=PIPE, > > stderr=PIPE).communicate() > > if len(err) > 0: > > # print("Error") > > # Error handling code > > else: > > # print("Success") > > Store the Popen() instance before calling its communicate() method: > > p = self.process = Popen(self.fwcmd, stdout=PIPE, stderr=PIPE) > out, err = p.communicate() > if p.returncode: > raise CalledProcessError(p.returncode, self.fwcmd, (out, err)) > > communicate() sets returncode; an error is indicated by a non-zero > value. Some programs write non-error information to stderr, so use the > return code to detect an error. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From glester at avant.ca Wed Oct 23 18:01:24 2013 From: glester at avant.ca (Glenn Lester) Date: Wed, 23 Oct 2013 11:01:24 -0500 Subject: [Tutor] The meaning of self Message-ID: I have come across the term "self" in a number of Python scripts and as a beginner to the language I am wondering if it has any specific meaning. It is usually used in the same manner as in this example by Steven D'Aprano. class DefaultModelCar: model = "Unknown" BRAKE_COMMAND = "B" FORWARD_COMMAND = "F" REVERSE_COMMAND = "R" ACCELERATE_COMMAND = "A" TURN_LEFT_COMMAND = "TL" TURN_RIGHT_COMMAND = "TR" def send_command(self, command): # Send a command to the model car. # Put the code here to actually communicate with the car. ... def forward(self): # Drive forward. if self.direction == "Reverse": # Brake first, then move forward. self.stop() self.send_command(self. FORWARD_COMMAND) self.send_command(self.ACCELERATE_COMMAND) self.direction = "Forward" def reverse(self): if self.direction == "Forward": self.stop() self.send_command(self.REVERSE_COMMAND) self.send_command(self.ACCELERATE_COMMAND) self.direction = "Reverse" def stop(self): self.send_command(self.BRAKE_COMMAND) self.direction = "Stopped" -- *Glenn Lester* Software Tester *Avant Systems Group*** *voice: *204.789.9596 x19* **|** fax: *204.789.9598* **|** email: * glester at avant.ca*|** web: *www.avant.ca** *Quality People Delivering Quality Solutions* CONFIDENTIALITY NOTICE: This correspondence and any attachment(s) may contain confidential information that is legally privileged. If you are not the intended recipient, or the person responsible for delivering it, you are hereby notified that any disclosure, copying, distribution or use of any of the aforementioned information is STRICTLY PROHIBITED. If you have received this transmission in error, please permanently delete the original transmission and its attachments without reading or saving in any manner. -------------- next part -------------- An HTML attachment was scrubbed... URL: From i.sheeha at gmail.com Wed Oct 23 16:47:57 2013 From: i.sheeha at gmail.com (Ismar Sehic) Date: Wed, 23 Oct 2013 16:47:57 +0200 Subject: [Tutor] export postgresql to unified, templated xml Message-ID: Hello all.i have a quite big task, but i have a feeling it could be easily solved using python. The thing is, i need to export the whole company DB(Postgresql) to an XML template provided by another company. the template looks like this(just a fragment) : ?xml version="1.0" encoding="utf-8"?>
... i've never done anything like that.i'm familiar with psycopg2 module, also, i'm familiar with xml parsing(ElementTree, lxml). is there some way to use the provided xml as a template, then parse all the data according to the template, what is the moyt pythonic way to do this? Thx. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Oct 23 19:20:52 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 23 Oct 2013 18:20:52 +0100 Subject: [Tutor] The meaning of self In-Reply-To: References: Message-ID: On 23/10/13 17:01, Glenn Lester wrote: > I have come across the term "self" in a number of Python scripts and as > a beginner to the language I am wondering if it has any specific > meaning. Technically no, the name is arbitrary but self is used by (very strong) tradition. As to what it is used for the explanation depends on your background. If you already know languages like C++, Java or JavaScript then the simple explanation is that self is the equivalent of 'this' in those languages except Python requires yopu to explicitly specify it as the first parameter in any method. The other languages do this implicitly. If you don;t know those other languages then can I suggest you try reading my explanation in my tutorial here... http://www.alan-g.me.uk/l2p/tutclass.htm About 15-20% of the way down there is a heading 'What is self?' If that still makes no sense then come back and ask again, ideally with some more specific aspects to the bits that puzzle you. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From shelby.martin at gmail.com Wed Oct 23 23:39:00 2013 From: shelby.martin at gmail.com (Shelby Martin) Date: Wed, 23 Oct 2013 14:39:00 -0700 Subject: [Tutor] Want to keep to two decimal places for currency Message-ID: I've looked online but I'm confused - I need to keep it so that the following program limits the output to two decimal places since it deals in currency. How do I incorporate that into my current code below? The textbook I'm using doesn't describe how to do that. Thanks in advance. #Challenge Chapter 2 #Question number three print("This program helps you to determine a tip amount of either") print("15 or 20 percent.") bill=float(input("\nHow much was your restaurant bill total (in dollars)? ")) fifteen=float(bill*0.15) twenty=float(bill*0.2) print("\n15% tip = $", fifteen) print("\n20% tip = $", twenty) input("\n\nPress the enter key to exit.") -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Oct 24 01:13:25 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 24 Oct 2013 00:13:25 +0100 Subject: [Tutor] Want to keep to two decimal places for currency In-Reply-To: References: Message-ID: On 23/10/13 22:39, Shelby Martin wrote: > I've looked online but I'm confused - I need to keep it so that the > following program limits the output to two decimal places since it deals > in currency. Its generally a bad idea to use floats when dealing with currency since they can introduce small errors which can accumulate over time. It's better to either use the Decimal module or to convert money to cents/.pennies and then convertback to dollars for display purposes. However, for the purposes of your homework we will ignore that. > How do I incorporate that into my current code below? The textbook I'm > using doesn't describe how to do that. Thanks in advance. You need tobdistinguish between storage and display. You want to maintain the data stored in its full accuracy but display it with only 2 decimal digits. One waty to do that is with the string format method (I'm assuming Python v3). Check the Python docs for string formatting and you will find several options you can use to control the display of floating point numbers. The basic form is print( "Here is a float: {}".format(123.456789) ) We can limit the field length to 7 digit swith print( "Here is a float: {:15f}".format(123.456789) ) And adjust the number of digits after the point like so: print( "Here is a float: {:7.3f}".format(123.456789) ) You can also specify justification, zero padding and other aspects. Read the docs... HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From dyoo at hashcollision.org Thu Oct 24 05:44:04 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Wed, 23 Oct 2013 20:44:04 -0700 Subject: [Tutor] Want to keep to two decimal places for currency In-Reply-To: References: Message-ID: On Wed, Oct 23, 2013 at 4:13 PM, Alan Gauld wrote: > On 23/10/13 22:39, Shelby Martin wrote: > >> I've looked online but I'm confused - I need to keep it so that the >> following program limits the output to two decimal places since it deals >> in currency. >> > > Its generally a bad idea to use floats when dealing with currency since > they can introduce small errors which can accumulate over time. It's better > to either use the Decimal module or to convert money to cents/.pennies and > then convertback to dollars for display purposes. > Hi Shelby, If you want to read some gory details, you can find the reasons for why it's unsafe to represent currency with "floating point" numbers. There's a classic paper called "What Every Computer Scientist Should Know About Floating-Point Arithmetic": http://www.validlab.com/goldberg/paper.pdf and you probably don't want to read the whole thing. :P A rough gist of the problem: traditional, engineering-focused computer math has a particular trade-off that most programmers do not realize at first: it trades accuracy for speed. The native hardware of your computer does calculations in base-2 rather than base-10 arithmetic. Unfortunately, that means that fractional quantities take a representational hit: your computer cannot accurately represent certain decimals in base-2. It turns out that this floating point arithmetic limitation is not so bad for a lot of important applications. But it doesn't bode well at all for applications that deal with money. There are libraries in Python that avoid using the built-in floating point hardware, such as the Decimal library that Alan noted. Computations with it are slower, but that's an acceptable price for getting the dollars and cents right. If we would do this sort of thing in the real world, we'd use something like the Decimal library. You'll see equivalent kinds of libraries in other programming languages, like the BigDecimal class in Java. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ivanthamjunhoe at gmail.com Thu Oct 24 12:57:18 2013 From: ivanthamjunhoe at gmail.com (ivantham@raspberrypi) Date: Thu, 24 Oct 2013 18:57:18 +0800 Subject: [Tutor] Translate word to number Message-ID: <20131024105626.GA4066@raspberrypi> Hi, I'm new to programming. I'm using python 3 and Debian Linux. My name is Ivan. I'm bad in for loops, I can't complete the following code: > input_word = input("Word to translate --> ") How to change this to for loops? > a, b, c, d, e, f, g, h = 1, 2, 3, 4, 5, 6, 7, 8 > i, j, k, l, m, n, o, p = 9, 10, 11, 12, 13, 14, 15, 16 > q, r, s, t, u, v, w, x, y, z = 17, 18, 19, 20, 21, 22, 23, 24, 25, 26 How to change the word to number in for loops? > for words in input_word: > words[0] = number[1] # The loops before in a to z > word += 1 # Change the word from a to z > number += 1 # And the number to so that 1 = a, 2 = b > # Then, add the numbers together How to take the output to a .txt file with new line for each word with numbers in this format? eg. abc = 6 eg. good = 41 > delimeter = " = " # for joining the input word and number > together > line = input_word + delimeter + number # save as this format Thanks, sorry for my English as English is not the main language that I speak. From jackiexxduh at yahoo.com Thu Oct 24 04:12:24 2013 From: jackiexxduh at yahoo.com (Jackie Canales) Date: Wed, 23 Oct 2013 19:12:24 -0700 (PDT) Subject: [Tutor] Count Help Message-ID: <1382580744.48073.YahooMailNeo@web121704.mail.ne1.yahoo.com> let say i have a file with random letters of ?A, AB, C, CD, AC, A, D, CD, DD, C, B, AB, CD, AB How do i count the occurrence of each individual item. def occurence(name): ? ? infile = open('bloodtype1.txt', 'r') ? ? lst = infile.read() ? ? infile.close() ? ? print(lst.count('AB')) # 3 ? ? print(lst.count('CD')) # 2 ? ? print(lst.count('DD'))# 1 i know i can do lst.count("AB") it will give me 3 but if i were to do lst.count("A") it would give me 6 what I am having trouble with is just getting the occurrence of the A by itself to give me 1 since there is just one occurrence of it and would need to do the same for c and d with out it counting the them in the occurrence of AC and DD or CD. From konrad.korzel at gmail.com Thu Oct 24 14:07:40 2013 From: konrad.korzel at gmail.com (=?UTF-8?Q?Konrad_Kor=C5=BCel?=) Date: Thu, 24 Oct 2013 13:07:40 +0100 Subject: [Tutor] export postgresql to unified, templated xml In-Reply-To: References: Message-ID: Using PostgreSQL XML functions will be more efficient here, check http://stackoverflow.com/questions/4967117/create-xml-from-postgresql/10399117#10399117for examples. You can try to do this in Python (by creating SQL selects for every table and then parsing each return row into XML), but for it to work correctly you would basically have to recreate those functions, which will take more effort than just learning how to use them. Choose right tool for the job :-) Konrad On 23 October 2013 15:47, Ismar Sehic wrote: > Hello all.i have a quite big task, but i have a feeling it could be easily > solved using python. > The thing is, i need to export the whole company DB(Postgresql) to an XML > template provided by another company. > the template looks like this(just a fragment) : > > ?xml version="1.0" encoding="utf-8"?> > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > ... > > > > i've never done anything like that.i'm familiar with psycopg2 module, > also, i'm familiar with xml parsing(ElementTree, lxml). > is there some way to use the provided xml as a template, then parse all > the data according to the template, what is the moyt pythonic way to do > this? > > Thx. > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From paradox at pobox.com Thu Oct 24 17:38:51 2013 From: paradox at pobox.com (Paradox) Date: Thu, 24 Oct 2013 11:38:51 -0400 Subject: [Tutor] Argparse and how best to use it Message-ID: <52693F0B.301@pobox.com> I am trying to learn about argparse and how best to incorporate it into my scripts. I am using Python 2.7.5 on Ubuntu 13.10. It seems from the argparse tutorial that all the arguments are processed as global variables. Is that the standard way to do it or do you normally (when doing real projects and not writing tutorials) process the arguments in the main loop of the script? thomas From davea at davea.name Thu Oct 24 18:01:52 2013 From: davea at davea.name (Dave Angel) Date: Thu, 24 Oct 2013 16:01:52 +0000 (UTC) Subject: [Tutor] Count Help References: <1382580744.48073.YahooMailNeo@web121704.mail.ne1.yahoo.com> Message-ID: On 23/10/2013 22:12, Jackie Canales wrote: > let say i have a file with random letters of ?A, AB, C, CD, AC, A, D, CD, DD, C, B, AB, CD, AB > How do i count the occurrence of each individual item. > > def occurence(name): > ? ? infile = open('bloodtype1.txt', 'r') > ? ? lst = infile.read() read() doesn't return a list, it returns a string. So the name is poorly chosen. Probably you wanted a list, with each item containing one or two letters. You can use split(",") to break the string into a list, based on commas. And you can use strip() on each item of that list to get rid of whitespace. > ? ? infile.close() > > ? ? print(lst.count('AB')) # 3 > ? ? print(lst.count('CD')) # 2 > ? ? print(lst.count('DD'))# 1 > > > i know i can do lst.count("AB") it will give me 3 but if i were to do lst.count("A") it would give me 6 what I am having trouble with is just getting the occurrence of the A by itself to give me 1 since there is just one occurrence of it and would need to do the same for c and d with out it counting the them in the occurrence of AC and DD or CD. When searching the original string, you have that problem. Making an actual list will fix it. -- DaveA From davea at davea.name Thu Oct 24 18:33:47 2013 From: davea at davea.name (Dave Angel) Date: Thu, 24 Oct 2013 16:33:47 +0000 (UTC) Subject: [Tutor] Translate word to number References: <20131024105626.GA4066@raspberrypi> Message-ID: On 24/10/2013 06:57, ivantham at raspberrypi wrote: > Hi, I'm new to programming. I'm using python 3 and Debian Linux. My > name is Ivan. I'm bad in for loops, I can't complete the following code: Welcome to Python, and to the tutor newsgroup. This is the right place to ask this sort of question. And thanks for using text email instead of html. There are a whole bunch of methods of the str type. You can see them in the interactive interpreter by typing help(str) > >> input_word = input("Word to translate --> ") First thing is to make sure the word is both alphabetic and lowercase: if input_word.isalpha() and input_word.islower(): xxxx else; yyyy > > How to change this to for loops? >> a, b, c, d, e, f, g, h = 1, 2, 3, 4, 5, 6, 7, 8 >> i, j, k, l, m, n, o, p = 9, 10, 11, 12, 13, 14, 15, 16 >> q, r, s, t, u, v, w, x, y, z = 17, 18, 19, 20, 21, 22, 23, 24, 25, 26 Not sure what those equal signs are supposed to represent. But if you want to convert "a" to 1, and "b" to 2, etc., look at the ord() function. print(ord("c")) will print a 99. See if you adjust that to be 3 instead. > > How to change the word to number in for loops? >> for words in input_word: If you loop through a string, you get characters, not words. That's probably what you want, but you'd be better off using a better-named variable. Hint. At any time you're not sure what a function returns, you can test it in the interpreter. So try: >>> for x in "abcd": ... print(type(x)) ... print(x) Once you have a letter, you can use the expression you figured out above to convert it to a number. >> words[0] = number[1] # The loops before in a to z >> word += 1 # Change the word from a to z >> number += 1 # And the number to so that 1 = a, 2 = b >> # Then, add the numbers together None of those make any sense to me. I'd just build a list of numbers, and then use the sum() function on it. Assign the result to the new variable 'number'. > > How to take the output to a .txt file with new line for each word with > numbers in this format? > eg. abc = 6 > eg. good = 41 >> delimeter = " = " # for joining the input word and number >> together >> line = input_word + delimeter + number # save as this format You'll need str(number), so you get the number into printable form. > > Thanks, sorry for my English as English is not the main language that I > speak. > -- DaveA From JATINSHR001 at e.ntu.edu.sg Thu Oct 24 18:38:42 2013 From: JATINSHR001 at e.ntu.edu.sg (#PATHANGI JANARDHANAN JATINSHRAVAN#) Date: Thu, 24 Oct 2013 16:38:42 +0000 Subject: [Tutor] Python and memory allocation Message-ID: <4d9f0ebe72ca4454a0d5f0cf2bb70152@SIXPR01MB093.apcprd01.prod.exchangelabs.com> Hello All, Before starting to learn python, I first learnt C and C++ for a couple of years. In C/C++, the choice to assign memory during compile time or during execution time, i.e. assigning memory from the stack or the heap lay with the programmer right? But in Python, I have only seen examples of using heap memory in programs. Like list.append(x) and so on. So, is there a concept of heap and stack in python or is it abstracted? And does python being an interpreted language have to do anything with this? Thanks and sorry for the newbie doubt :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Thu Oct 24 18:50:34 2013 From: davea at davea.name (Dave Angel) Date: Thu, 24 Oct 2013 16:50:34 +0000 (UTC) Subject: [Tutor] Argparse and how best to use it References: <52693F0B.301@pobox.com> Message-ID: On 24/10/2013 11:38, Paradox wrote: > I am trying to learn about argparse and how best to incorporate it into > my scripts. I am using Python 2.7.5 on Ubuntu 13.10. Welcome to python, and to python-tutor mailing list. And thanks for using text mode email, and for supplying both your Python version and OS. > > It seems from the argparse tutorial that all the arguments are processed > as global variables. Is that the standard way to do it or do you > normally (when doing real projects and not writing tutorials) process > the arguments in the main loop of the script? Not sure which tutorial you're using, but the refernce page: http://docs.python.org/3.3/library/argparse.html has some examples that are also at top-level, using globals. I wouldn't recommend that, as I try to minimize the number of non-const globals. The only component that might make sense as a global is the result dictionary, 'args' So the first example would become: import argparse def parse_my_args(): global args parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an integer for the accumulator') parser.add_argument('--sum', dest='accumulate', action='store_const', const=sum, default=max, help='sum the integers (default: find the max)') args = parser.parse_args() Technically, I should just return args, but this is the way I do it for my own code. Although args is technically non-const, by making it a global, I am promising myself that nobody else will modify it once set up. -- DaveA From joel.goldstick at gmail.com Thu Oct 24 18:49:41 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 24 Oct 2013 12:49:41 -0400 Subject: [Tutor] Python and memory allocation In-Reply-To: <4d9f0ebe72ca4454a0d5f0cf2bb70152@SIXPR01MB093.apcprd01.prod.exchangelabs.com> References: <4d9f0ebe72ca4454a0d5f0cf2bb70152@SIXPR01MB093.apcprd01.prod.exchangelabs.com> Message-ID: On Thu, Oct 24, 2013 at 12:38 PM, #PATHANGI JANARDHANAN JATINSHRAVAN# wrote: > Hello All, > > Before starting to learn python, I first learnt C and C++ for a couple > of years. In C/C++, the choice to assign memory during compile time or > during execution time, i.e. assigning memory from the stack or the heap lay > with the programmer right? But in Python, I have only seen examples of using > heap memory in programs. Like list.append(x) and so on. So, is there a > concept of heap and stack in python or is it abstracted? And does python > being an interpreted language have to do anything with this? > Python takes care of memory allocation, so you generally don't need to worry about it. It does its own garbage collection. Also, please use text messages when you post here. HTML style mess up a lot of people experience, so you will get fewer people to help you > > > Thanks and sorry for the newbie doubt :) > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick http://joelgoldstick.com From breamoreboy at yahoo.co.uk Thu Oct 24 19:03:42 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 24 Oct 2013 18:03:42 +0100 Subject: [Tutor] Argparse and how best to use it In-Reply-To: <52693F0B.301@pobox.com> References: <52693F0B.301@pobox.com> Message-ID: On 24/10/2013 16:38, Paradox wrote: > I am trying to learn about argparse and how best to incorporate it into > my scripts. I am using Python 2.7.5 on Ubuntu 13.10. > > It seems from the argparse tutorial that all the arguments are processed > as global variables. Is that the standard way to do it or do you > normally (when doing real projects and not writing tutorials) process > the arguments in the main loop of the script? > > thomas > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > You can save yourself much pain by using the third party docopt, it's absolutely awesome. Download from here https://pypi.python.org/pypi/docopt/ -- Python is the second best programming language in the world. But the best has yet to be invented. Christian Tismer Mark Lawrence From mvillamilb at gmail.com Thu Oct 24 03:42:05 2013 From: mvillamilb at gmail.com (Mauricio Villamil) Date: Wed, 23 Oct 2013 18:42:05 -0700 Subject: [Tutor] checking list position Message-ID: Hello, And thank you for any help. I am writing a little prog. On this part I need to recursively (preferably) write to a list a value only if it's less than 49, else do an operation to make it less than 49, then check which is the next available spot on the list and write there ... so pseudo code would be like: def getGM(seed): ## function Gnumbers = [5] ## list to write to for i in Gnumbers: iterate from begining of list to write to it if (result <= 49): result = math.floor(seed * 1.61803398875) ## find value lesser than 49 place = int(len(Gnumbers)) ## fins how long is the list so far Gnumbers[i] = result ## place result at spot in list print ("this is place :", place) ## see length of list else: ## if number bigger than 49 then divide the number to make it smaller and wrote result = math.floor(seed / 1.61803398875) ## make number smaller if (result <= 49):## if right size write to array Gnumbers[i] = result else: getGM(result)## if not divide again ( this could be a dedicated function ? So ..the biggie is knowing all any time which is the next available place in the list to write to (we don't want to overwirte previous values .... Many thanks for suggestions !! M. -------------- next part -------------- An HTML attachment was scrubbed... URL: From shelby.martin at gmail.com Thu Oct 24 18:37:38 2013 From: shelby.martin at gmail.com (Shelby Martin) Date: Thu, 24 Oct 2013 09:37:38 -0700 Subject: [Tutor] Want to keep to two decimal places for currency In-Reply-To: References: Message-ID: Thank you for your replies. I suspect the solution is a bit more advanced than where I'm at now, which is chapter 2 of a beginner's book. Not sure why the author chose to use examples using money calculations when other calculations that don't need rounding would have sufficed. I will have to revisit this issue when I'm further along. On Wed, Oct 23, 2013 at 8:44 PM, Danny Yoo wrote: > > > > On Wed, Oct 23, 2013 at 4:13 PM, Alan Gauld wrote: > >> On 23/10/13 22:39, Shelby Martin wrote: >> >>> I've looked online but I'm confused - I need to keep it so that the >>> following program limits the output to two decimal places since it deals >>> in currency. >>> >> >> Its generally a bad idea to use floats when dealing with currency since >> they can introduce small errors which can accumulate over time. It's better >> to either use the Decimal module or to convert money to cents/.pennies and >> then convertback to dollars for display purposes. >> > > > Hi Shelby, > > > If you want to read some gory details, you can find the reasons for why > it's unsafe to represent currency with "floating point" numbers. There's a > classic paper called "What Every Computer Scientist Should Know About > Floating-Point Arithmetic": > > http://www.validlab.com/goldberg/paper.pdf > > and you probably don't want to read the whole thing. :P A rough gist of > the problem: traditional, engineering-focused computer math has a > particular trade-off that most programmers do not realize at first: it > trades accuracy for speed. The native hardware of your computer does > calculations in base-2 rather than base-10 arithmetic. Unfortunately, that > means that fractional quantities take a representational hit: your computer > cannot accurately represent certain decimals in base-2. > > It turns out that this floating point arithmetic limitation is not so bad > for a lot of important applications. But it doesn't bode well at all for > applications that deal with money. There are libraries in Python that > avoid using the built-in floating point hardware, such as the Decimal > library that Alan noted. Computations with it are slower, but that's an > acceptable price for getting the dollars and cents right. If we would do > this sort of thing in the real world, we'd use something like the Decimal > library. You'll see equivalent kinds of libraries in other programming > languages, like the BigDecimal class in Java. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Thu Oct 24 19:21:56 2013 From: davea at davea.name (Dave Angel) Date: Thu, 24 Oct 2013 17:21:56 +0000 (UTC) Subject: [Tutor] Python and memory allocation References: <4d9f0ebe72ca4454a0d5f0cf2bb70152@SIXPR01MB093.apcprd01.prod.exchangelabs.com> Message-ID: On 24/10/2013 12:38, #PATHANGI JANARDHANAN JATINSHRAVAN# wrote: > Hello All, > > Before starting to learn python, I first learnt C and C++ for a couple of years. In C/C++, the choice to assign memory during compile time or during execution time, i.e. assigning memory from the stack or the heap lay with the programmer right? But in Python, I have only seen examples of using heap memory in programs. Like list.append(x) and so on. So, is there a concept of heap and stack in python or is it abstracted? And does python being an interpreted language have to do anything with this? > > > > Thanks and sorry for the newbie doubt :) > That's what this group is for, welcome. In C and C++, there are 3 kinds of variable lifetime, rather than 2. If a variable is static, it is created and initialized before your program really starts, and lasts till the program goes away. If a variable is automatic (stack-based), it will be created when the function (or even the scope within a function) begins, and destroyed when the function or scope ends. And this is especially important in C/C++ because when a function is recursive, there may be many named variables on the stack with the same name, and independent values. If a data item is heap-based, it is not really a variable at all, but is a block created by malloc() or equivalent, and *pointed to* by a variable. And it's freed when the corresponding free() or equivalent is called. In Python it's all different. There aren't really any static variables that the user defines, though there are plenty of variables that are defined and initialized long before your code starts running. If you want a surprise, try the following simple program some time. import sys print(sys.modules) when I tried that interactively on 2.7, it printed some 240+ names. As for auto versus heap-based, all values you define are both. What's stored in the 'stack' is references to objects, where the objects are allocated on the heap. And those in turn may have references to other objects, and so on. So if you have a variable x which is a list of size 10, then you have a refernce to a list object, which in turn has references to ten other objects. All these objects are reference counted, and when the count reaches zero, they vanish. And for circular links, there's a garbage collector which operates periodically. These references are referred to as bindings in the python literature. The real point is that when you use a value, you don't have to worry about where it'll be stored, but just on how you'll find it again when you need it. You may have a name bound to it, and also a list item. Even if you reuse the name, the list item will still assure you can find it again. Similarly, if you call sorted() on a list of large strings, you get a new list, but the strings are not duplicated, so it's not nearly the duplication it might look like. -- DaveA From alan.gauld at btinternet.com Thu Oct 24 19:53:20 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 24 Oct 2013 18:53:20 +0100 Subject: [Tutor] Python and memory allocation In-Reply-To: <4d9f0ebe72ca4454a0d5f0cf2bb70152@SIXPR01MB093.apcprd01.prod.exchangelabs.com> References: <4d9f0ebe72ca4454a0d5f0cf2bb70152@SIXPR01MB093.apcprd01.prod.exchangelabs.com> Message-ID: On 24/10/13 17:38, #PATHANGI JANARDHANAN JATINSHRAVAN# wrote: > on. So, is there a concept of heap and stack in python or is it > abstracted? Joel and Dave have given you the answers to this bit.... > And does python being an interpreted language have to do > anything with this? Nothing at all. In fact you can get interpreters for C (not sure about C++) and Python has its own compiler. So interpreting or compiling makes no significant difference to how memory allocation works. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From dyoo at hashcollision.org Thu Oct 24 19:59:54 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Thu, 24 Oct 2013 10:59:54 -0700 Subject: [Tutor] Python and memory allocation In-Reply-To: <4d9f0ebe72ca4454a0d5f0cf2bb70152@SIXPR01MB093.apcprd01.prod.exchangelabs.com> References: <4d9f0ebe72ca4454a0d5f0cf2bb70152@SIXPR01MB093.apcprd01.prod.exchangelabs.com> Message-ID: > And does python being an interpreted language have to do anything with this? I have to interrupt: you mean to say: "And does the C implementation of Python (CPython) have to do anything with this?". There are several implementations of Python out there. Not all of them use an interpreter in the sense that you're thinking of. PyPy and Jython are two concrete examples of Python implementations. As soon as there are at least two _implementations_ of a language which use different strategies for evaluation, the term "interpreted language" loses meaning. It you consider more closely, even C and C++ can be evaluated with an interpreter. And interpreting C is not as silly as it sounds at first. Look at Cling, for example. ( http://root.cern.ch/drupal/content/cling) So try to avoid saying that Python is an interpreted language. "Python has an interpreter" would be a better statement. Try to avoid saying the term "interpreted language" too: it's a conceptual type error. Languages have implementations: they are not themselves implementations. Coming back to your original question: take a brief glance at: http://doc.pypy.org/en/latest/translation.html#escape-analysis-and-stack-allocation That is, there are implementations (at least one in PyPy) that will try to automatically do the stack allocation if it can reason that the values won't escape out of the scope. But allocation is an implementation detail that the Python language does not expose to make life nicer for Python programmers. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dyoo at hashcollision.org Thu Oct 24 20:09:21 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Thu, 24 Oct 2013 11:09:21 -0700 Subject: [Tutor] Want to keep to two decimal places for currency In-Reply-To: References: Message-ID: On Thu, Oct 24, 2013 at 9:37 AM, Shelby Martin wrote: > Thank you for your replies. I suspect the solution is a bit more advanced > than where I'm at now, which is chapter 2 of a beginner's book. > Probably because talking about the gory details would completely derail the conversation, as I did. :P My apologies. > Not sure why the author chose to use examples using money calculations > when other calculations that don't need rounding would have sufficed. I > will have to revisit this issue when I'm further along. > I think it's fine to do it when you're learning the language. Just be aware of it, and you should be ok. Related: I saw a picture the other day on Google+ of an mailing envelope whose zip code was written in scientific notation. By computer, of course. Wish I could find it again... Knowing the appropriate representations for data is something you'll pick up as you learn a programming language. Good luck! -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Thu Oct 24 20:25:24 2013 From: bgailer at gmail.com (bob gailer) Date: Thu, 24 Oct 2013 14:25:24 -0400 Subject: [Tutor] Want to keep to two decimal places for currency In-Reply-To: References: Message-ID: <52696614.3020800@gmail.com> On 10/24/2013 2:09 PM, Danny Yoo wrote: > Related: I saw a picture the other day on Google+ of an mailing > envelope whose zip code was written in scientific notation. That;s odd - since ZIP codes are character, not integer, -- Bob Gailer 919-636-4239 Chapel Hill NC From paradox at pobox.com Thu Oct 24 20:23:50 2013 From: paradox at pobox.com (Paradox) Date: Thu, 24 Oct 2013 14:23:50 -0400 Subject: [Tutor] Argparse and how best to use it :p: In-Reply-To: References: <52693F0B.301@pobox.com> Message-ID: <526965B6.702@pobox.com> On 10/24/2013 12:50 PM, Dave Angel wrote: >> >> Not sure which tutorial you're using, but the refernce page: >> http://docs.python.org/3.3/library/argparse.html Actually I am using 2.7.5, the tutorial found here: http://docs.python.org/2/howto/argparse.html#id1 but the problem is the same. >> import argparse >> >> def parse_my_args(): >> global args >> parser = argparse.ArgumentParser(description='Process some >> integers.') >> parser.add_argument('integers', metavar='N', type=int, >> nargs='+', help='an integer for the accumulator') >> parser.add_argument('--sum', dest='accumulate', >> action='store_const', const=sum, default=max, help='sum the integers >> (default: find the max)') >> args = parser.parse_args() >> >> This is exactly what I needed to un-stick my thinking about this, thanks! thomas From rafael.knuth at gmail.com Thu Oct 24 21:57:07 2013 From: rafael.knuth at gmail.com (Rafael Knuth) Date: Thu, 24 Oct 2013 21:57:07 +0200 Subject: [Tutor] Python 3.3 on OpenSUSE 12.3 Message-ID: Hej, I can't get Python 3.3 up and running (it's properly installed but I can't launch it), and I was wondering if anyone using OpenSUSE 12.3 had similar issues. SUSE community folks weren't really able to help me, so I was wondering I give it a try here. Thanks, Rafael -------------- next part -------------- An HTML attachment was scrubbed... URL: From malaclypse2 at gmail.com Thu Oct 24 22:18:10 2013 From: malaclypse2 at gmail.com (Jerry Hill) Date: Thu, 24 Oct 2013 16:18:10 -0400 Subject: [Tutor] Want to keep to two decimal places for currency In-Reply-To: <52696614.3020800@gmail.com> References: <52696614.3020800@gmail.com> Message-ID: On Thu, Oct 24, 2013 at 2:25 PM, bob gailer wrote: > That;s odd - since ZIP codes are character, not integer, It's not that odd. US Zip codes are a sequence of digits. I've worked with plenty of databases where ZIP codes are held in Numeric columns. It's not the ideal format for ZIP codes, because it's perfectly valid for ZIP codes to start with a 0, and Canadian zip codes have letters in them, but I see it all the time. -- Jerry From marc.tompkins at gmail.com Thu Oct 24 22:21:10 2013 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Thu, 24 Oct 2013 13:21:10 -0700 Subject: [Tutor] Want to keep to two decimal places for currency In-Reply-To: <52696614.3020800@gmail.com> References: <52696614.3020800@gmail.com> Message-ID: On Thu, Oct 24, 2013 at 11:25 AM, bob gailer wrote: > On 10/24/2013 2:09 PM, Danny Yoo wrote: > >> Related: I saw a picture the other day on Google+ of an mailing envelope >> whose zip code was written in scientific notation. >> > That;s odd - since ZIP codes are character, not integer, > You'd like to think that, wouldn't you? I've dealt with a disturbing number of programs (some of them from big enough names that you'd think they'd know better) that chose to represent zip codes as integers. You'd think that the fact that some of them have to be zero-filled would be a big clue... but no. -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Thu Oct 24 22:24:34 2013 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Thu, 24 Oct 2013 13:24:34 -0700 Subject: [Tutor] Want to keep to two decimal places for currency In-Reply-To: References: <52696614.3020800@gmail.com> Message-ID: On Thu, Oct 24, 2013 at 1:21 PM, Marc Tompkins wrote: > On Thu, Oct 24, 2013 at 11:25 AM, bob gailer wrote: > >> On 10/24/2013 2:09 PM, Danny Yoo wrote: >> >>> Related: I saw a picture the other day on Google+ of an mailing envelope >>> whose zip code was written in scientific notation. >>> >> That;s odd - since ZIP codes are character, not integer, >> > > You'd like to think that, wouldn't you? I've dealt with a disturbing > number of programs (some of them from big enough names that you'd think > they'd know better) that chose to represent zip codes as integers. You'd > think that the fact that some of them have to be zero-filled would be a big > clue... but no. > Zip+4 is a HUGE hassle for programs that have chosen to do things this way... Zip+4 has always been optional, but the 5010 format for healthcare billing now requires that all zip codes (except patient's actual home addresses) be represented in 9 glorious digits... that's made a bunch of people scramble, let me tell you! -------------- next part -------------- An HTML attachment was scrubbed... URL: From i.sheeha at gmail.com Thu Oct 24 22:44:12 2013 From: i.sheeha at gmail.com (Ismar Sehic) Date: Thu, 24 Oct 2013 22:44:12 +0200 Subject: [Tutor] python, xml, mongodb Message-ID: hello, me again - the guy with a (mis)fortune of having to deal with a lot of company's in and outgoing xml.I guess they just like xml as a data interchange format, its human readable.i've done my task of exporting the entire postgresql database to some prestructured xml, and i guess i've done the job so well, they want me to develop something like an web service, that will be receiving all kinds of hotel related data, no matter what format(csv, xml, txt, maybe even dBase or whatever)from various clients.my service should be parsing the received data in the prestructed xml format, store everything in one xml file per client, then send to some other service.i really love programming in python and struggling my way through streams of data(i don't like the fact that i'm working in a tourism related company, where clients dictate the terms, but i hope i will change my job some day...) i need some help in the idea of the architecture itself, i'm still a novice in python(started 8 months ago), although i manage to do some nice work, i guess i'm stubborn... so - on the input part ---> i'm receiving a lot of data in various formats, that needs to be validated and parsed in a way i can use it to populate my predefined xml elements.i really dunno what format to expect, no details on that, i just know that 'whatever' i receive will be containing some essential data like hotel id's, occupancies, room details(seaview, room service, prices etc...)is there some way to write a unique parser, that will load a file and look for some pattern of data, then grab it?i will really aprecciate any ideas on that input parsing part. next little problem - what type of database should i use to store the data in.i would prefer something where i can set the default template and then just pass the parsed data to it, so my output xml is already half-way formed(for example, i set a column name like Hotel_name, pass all the hotel names to it, hotel_id - where i just pass all the id's etc) so i can just export it and i have my xml that matches the company's template. i know it's unusual to ask for an idea how to approach a problem - but my project manager and head of the company aren't of much use, they are interested only in clients and financial gain, not really helpful.so they pass me a problem and i have to find the best way to do it.it's my first job, i cannot change any of the terms, i can just go along, or refuse to do it - meaning i'm losing the job.so basically you guys are the best help i can get. so please, give me some ideas, or point me in the right direction.i have like three weeks to complete this. i'll understand if all this is too much to ask, no problem. anyway, thanks :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From jslozier at gmail.com Thu Oct 24 23:45:50 2013 From: jslozier at gmail.com (Jay Lozier) Date: Thu, 24 Oct 2013 17:45:50 -0400 Subject: [Tutor] Python 3.3 on OpenSUSE 12.3 In-Reply-To: References: Message-ID: <1382651150.3623.6.camel@linux-3jah.site> On Thu, 2013-10-24 at 21:57 +0200, Rafael Knuth wrote: > Hej, > I can't get Python 3.3 up and running (it's properly installed but I > can't launch it), and I was wondering if anyone using OpenSUSE 12.3 > had similar issues. SUSE community folks weren't really able to help > me, so I was wondering I give it a try here. > Thanks, > Rafael Rafael, I have both Python 2.7.3 and 3.3.0 installed on openSUSE 12.3. To use 3.3 I enter python3.3 at the prompt. If I enter python it defaults to 2.7.3 In the shebang #!/usr/bin/env python3.3 -- Jay Lozier jslozier at gmail.com From akleider at sonic.net Fri Oct 25 00:45:00 2013 From: akleider at sonic.net (Alex Kleider) Date: Thu, 24 Oct 2013 15:45:00 -0700 Subject: [Tutor] Argparse and how best to use it In-Reply-To: <52693F0B.301@pobox.com> References: <52693F0B.301@pobox.com> Message-ID: <551da6cd569c5a6e6fcc56cbceb579ca@sonic.net> On 2013-10-24 08:38, Paradox wrote: > I am trying to learn about argparse and how best to incorporate it > into my scripts. I am using Python 2.7.5 on Ubuntu 13.10. > > It seems from the argparse tutorial that all the arguments are > processed as global variables. Is that the standard way to do it or > do you normally (when doing real projects and not writing tutorials) > process the arguments in the main loop of the script? Some one on this list recently recommended docopt rather than argparse. I've been playing with it and find it far superior although there are still a few issues that I haven't figured out. From breamoreboy at yahoo.co.uk Fri Oct 25 01:07:50 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 25 Oct 2013 00:07:50 +0100 Subject: [Tutor] Argparse and how best to use it In-Reply-To: <551da6cd569c5a6e6fcc56cbceb579ca@sonic.net> References: <52693F0B.301@pobox.com> <551da6cd569c5a6e6fcc56cbceb579ca@sonic.net> Message-ID: On 24/10/2013 23:45, Alex Kleider wrote: > On 2013-10-24 08:38, Paradox wrote: >> I am trying to learn about argparse and how best to incorporate it >> into my scripts. I am using Python 2.7.5 on Ubuntu 13.10. >> >> It seems from the argparse tutorial that all the arguments are >> processed as global variables. Is that the standard way to do it or >> do you normally (when doing real projects and not writing tutorials) >> process the arguments in the main loop of the script? > > > Some one on this list recently recommended docopt rather than argparse. > I've been playing with it and find it far superior although there are > still a few issues that I haven't figured out. > Alex, if you've still problems I'd be inclined to ask on the main Python mailing list as you're far more likely to get answers than here. Failing that how about approach the author direct? From the Development section here https://github.com/docopt/docopt it's vladimir at keleshev.com -- Python is the second best programming language in the world. But the best has yet to be invented. Christian Tismer Mark Lawrence From davea at davea.name Fri Oct 25 03:32:58 2013 From: davea at davea.name (Dave Angel) Date: Fri, 25 Oct 2013 01:32:58 +0000 (UTC) Subject: [Tutor] checking list position References: Message-ID: On 23/10/2013 21:42, Mauricio Villamil wrote: > Hello, > > And thank you for any help. > Welcome to the python-tutor mailinglist. Please use text emalis, not html. Your email program has lost all the indentation below, making your program really hard to follow. > I am writing a little prog. On this part I need to recursively (preferably) > write to a list a value only if it's less than 49, else do an operation to > make it less than 49, then check which is the next available spot on the > list and write there ... so pseudo code would be like: > > def getGM(seed): ## function > > Gnumbers = [5] ## list to write to > for i in Gnumbers: iterate from begining of list to write to it > if (result <= 49): > > result = math.floor(seed * 1.61803398875) ## find value lesser than 49 > place = int(len(Gnumbers)) ## fins how long is > the list so far > Gnumbers[i] = result ## place result > at spot in list > print ("this is place :", place) ## see length of > list > else: ## if number bigger than 49 then divide the number to make it > smaller and wrote > result = math.floor(seed / 1.61803398875) ## make number smaller > if (result <= 49):## if right size write to array > Gnumbers[i] = result > else: > getGM(result)## if not divide again ( this could be a dedicated function ? > > > So ..the biggie is knowing all any time which is the next available place > in the list to write to (we don't want to overwirte previous values .... > To write to the next place in a list, simply use append. Gnumbers.append(result) No clue what the code you posted is supposed to do. -- DaveA From davea at davea.name Fri Oct 25 03:36:34 2013 From: davea at davea.name (Dave Angel) Date: Fri, 25 Oct 2013 01:36:34 +0000 (UTC) Subject: [Tutor] Argparse and how best to use it :p: References: <52693F0B.301@pobox.com> <526965B6.702@pobox.com> Message-ID: On 24/10/2013 14:23, Paradox wrote: > > On 10/24/2013 12:50 PM, Dave Angel wrote: >>> >>> Not sure which tutorial you're using, but the refernce page: >>> http://docs.python.org/3.3/library/argparse.html > Actually I am using 2.7.5, the tutorial found here: > http://docs.python.org/2/howto/argparse.html#id1 > Yeah, and I'd just thanked you for supplying version, then got confused anyway in my reply. Sorry. -- DaveA From JATINSHR001 at e.ntu.edu.sg Fri Oct 25 14:20:32 2013 From: JATINSHR001 at e.ntu.edu.sg (#PATHANGI JANARDHANAN JATINSHRAVAN#) Date: Fri, 25 Oct 2013 12:20:32 +0000 Subject: [Tutor] Python and memory allocation In-Reply-To: References: <4d9f0ebe72ca4454a0d5f0cf2bb70152@SIXPR01MB093.apcprd01.prod.exchangelabs.com>, Message-ID: <595ce476416b42f5903f9a23bbc1748a@SIXPR01MB093.apcprd01.prod.exchangelabs.com> Hello All, >Similarly, if you call sorted() on a list of large strings, you get a new list, but the strings are not duplicated, so it's not nearly the duplication it might look like. 1. Sorry, but I did not understand the above point. 2. My interpretation of your answer is that the stack memory in Python holds only pointers that hold references to data on the heap. Is this correct? 3. Also, when you spoke about the second type of variable lifetime in C, did you mean the local scope of a variable like: int func(){ int a = 5; printf("a"); return 0; } Here were you talking about 'a' which is removed from the stack when it goes out of scope? Thanking You, Jatin ________________________________________ From: Tutor on behalf of Dave Angel Sent: Friday, October 25, 2013 01:21 AM To: tutor at python.org Subject: Re: [Tutor] Python and memory allocation On 24/10/2013 12:38, #PATHANGI JANARDHANAN JATINSHRAVAN# wrote: > Hello All, > >???? Before starting to learn python, I first learnt C and C++ for a couple of years. In C/C++, the choice to assign memory during compile time or during execution time, i.e. assigning memory from the stack or the heap lay with the programmer right? But in Python, I have only seen examples of using heap memory in programs. Like list.append(x) and so on. So, is there a concept of heap and stack in python or is it abstracted? And does python being an interpreted language have to do anything with this? > > > > Thanks and sorry for the newbie doubt :) > That's what this group is for, welcome. In C and C++, there are 3 kinds of variable lifetime, rather than 2.? If a variable is static, it is created and initialized before your program really starts, and lasts till the program goes away. If a variable is automatic (stack-based), it will be created when the function (or even the scope within a function) begins, and destroyed when the function or scope ends.? And this is especially important in C/C++ because when a function is recursive, there may be many named variables on the stack with the same name, and independent values. If a data item is heap-based, it is not really a variable at all, but is a block created by malloc() or equivalent, and *pointed to* by a variable.? And it's freed when the corresponding free() or equivalent is called. In Python it's all different.? There aren't really any static variables that the user defines, though there are plenty of variables that are defined and initialized long before your code starts running.? If you want a surprise, try the following simple program some time. import sys print(sys.modules) when I tried that interactively on 2.7, it printed some 240+ names. As for auto versus heap-based, all values you define are both.? What's stored in the 'stack' is references to objects, where the objects are allocated on the heap.? And those in turn may have references to other objects, and so on. So if you have a variable x which is a list of size 10, then you have a refernce to a list object, which in turn has references to ten other objects. All these objects are reference counted, and when the count reaches zero, they vanish.? And for circular links, there's a garbage collector which operates periodically. These references are referred to as bindings in the python literature. The real point is that when you use a value, you don't have to worry about where it'll be stored, but just on how you'll find it again when you need it.? You may have a name bound to it, and also a list item. Even if you reuse the name, the list item will still assure you can find it again.? Similarly, if you call sorted() on a list of large strings, you get a new list, but the strings are not duplicated, so it's not nearly the duplication it might look like. -- DaveA _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor From amirfaw at hotmail.com Fri Oct 25 10:13:57 2013 From: amirfaw at hotmail.com (Amir Fawzi) Date: Fri, 25 Oct 2013 10:13:57 +0200 Subject: [Tutor] python question In-Reply-To: References: Message-ID: Hi! I am trying to do an exercise abt classes, but I find it really hard even after reading. I have tryed to start it at the bottom of this document. I hope someone can help me. I have to submit the question by sunday. Exercise 7.4. Make a class for straight lines. Make a class Line whose constructor takes two points p1 and p2 (2- tuples or 2-lists) as input. The line goes through these two points (see function line in Chapter 3.1.7 for the relevant formula of the line). A value(x) method computes a value on the line at the point x. Here is a demo in an interactive session: >>> from Line import Line >>> line = Line((0,-1), (2,4)) >>> print line.value(0.5), line.value(0), line.value(1) 0.25 -1.0 1.5 My answer: class Line: def __init__(self, p1, p2): self.p1 = p1 self.p2 = p2 def value(self, x): p1 = (y1 - y0)/float(x1 -x0) # Formula referred to in chapter 3.1.7 in the book p2 = (y0 - a*x0) # return def line (x0, y0, x1, y1): p1 = (x0 - x1) p2 = (y0 - y1) return p1, p2 Kindest Regards A.F. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Oct 25 18:10:00 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 25 Oct 2013 17:10:00 +0100 Subject: [Tutor] python question In-Reply-To: References: Message-ID: On 25/10/13 09:13, Amir Fawzi wrote: > Exercise 7.4. Make a class for straight lines. > Make a class Line whose constructor takes two points p1 and p2 (2- > tuples or 2-lists) as input. The line goes through these two points (see > function line in Chapter 3.1.7 for the relevant formula of the line). I don;t have the reference but assume it is one of the standard math equations like y=mx+c? So for your class you need to work out m and c and in your value() function apply them to the input x to return y. The trick is that you need to solve the simultaneous equations at p1 and p2 for y=mx+c. I assume you know how to do that in math and then translate that into Python? If not come back with more specific questions. > >>> from Line import Line > >>> line = Line((0,-1), (2,4)) > >>> print line.value(0.5), line.value(0), line.value(1) > 0.25 -1.0 1.5 > > My answer: > > class Line: > def __init__(self, p1, p2): > self.p1 = p1 > self.p2 = p2 > > def value(self, x): > p1 = (y1 - y0)/float(x1 -x0) # Formula referred to in chapter > 3.1.7 in the book > p2 = (y0 - a*x0) # return at point x> I'm guessing that last one should be p2 = y0 - p1*x0 ? But you want to calculate this in the init method and store them as attributes of the line. It might be nice to give them meaniungful names like gradient and, erm, const? Then your y value is just a case of multiplying x by the gradient(p1) and adding the const(p2). > def line (x0, y0, x1, y1): > p1 = (x0 - x1) > p2 = (y0 - y1) > return p1, p2 I'm not sure what this is supposed to be? HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From konrad.korzel at gmail.com Fri Oct 25 17:42:28 2013 From: konrad.korzel at gmail.com (=?UTF-8?Q?Konrad_Kor=C5=BCel?=) Date: Fri, 25 Oct 2013 16:42:28 +0100 Subject: [Tutor] Count Help In-Reply-To: References: <1382580744.48073.YahooMailNeo@web121704.mail.ne1.yahoo.com> Message-ID: It's better to use the "with open" statement to open the file and then process it line by line with occurrence counter, like: def occurence(pathToFile, substring): substringCount = 0 with open(pathToFile, 'r') as src: for line in src: substringCount += line.count(substring) return substringCount On 24 October 2013 17:01, Dave Angel wrote: > On 23/10/2013 22:12, Jackie Canales wrote: > >> let say i have a file with random letters of A, AB, C, CD, AC, A, D, CD, DD, C, B, AB, CD, AB >> How do i count the occurrence of each individual item. >> >> def occurence(name): >> infile = open('bloodtype1.txt', 'r') >> lst = infile.read() > > read() doesn't return a list, it returns a string. So the name is > poorly chosen. Probably you wanted a list, with each item containing > one or two letters. > > You can use split(",") to break the string into a list, based on commas. > And you can use strip() on each item of that list to get rid of > whitespace. > > >> infile.close() >> >> print(lst.count('AB')) # 3 >> print(lst.count('CD')) # 2 >> print(lst.count('DD'))# 1 >> >> >> i know i can do lst.count("AB") it will give me 3 but if i were to do lst.count("A") it would give me 6 what I am having trouble with is just getting the occurrence of the A by itself to give me 1 since there is just one occurrence of it and would need to do the same for c and d with out it counting the them in the occurrence of AC and DD or CD. > > When searching the original string, you have that problem. Making an > actual list will fix it. > > > -- > DaveA > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From davea at davea.name Fri Oct 25 18:34:04 2013 From: davea at davea.name (Dave Angel) Date: Fri, 25 Oct 2013 16:34:04 +0000 (UTC) Subject: [Tutor] Python and memory allocation References: <4d9f0ebe72ca4454a0d5f0cf2bb70152@SIXPR01MB093.apcprd01.prod.exchangelabs.com>, <595ce476416b42f5903f9a23bbc1748a@SIXPR01MB093.apcprd01.prod.exchangelabs.com> Message-ID: On 25/10/2013 08:20, #PATHANGI JANARDHANAN JATINSHRAVAN# wrote: > Hello All, > >>Similarly, if you call sorted() on a list of large strings, > you get a new list, but the strings are not duplicated, so it's not > nearly the duplication it might look like. > > 1. Sorry, but I did not understand the above point. > For example, if you have a list of 100 strings, each 1000 bytes long, the total size of the list is 100,400+ bytes. If you make a new list, by using sorted_list = sorted(mylist) The new one is roughly 400+ bytes, since it doesn't make copies of any of the strings. (The + is intended to represent the overhead, which in some cases is substantial. And the factor of 4 is assuming a 32bit Python implementation) > > 2. My interpretation of your answer is that the stack memory in Python holds only pointers that hold references to data on the heap. Is this correct? > > 3. Also, when you spoke about the second type of variable lifetime in C, did you mean the local scope of a variable like: > > int func(){ > int a = 5; > printf("a"); > return 0; > } > Here were you talking about 'a' which is removed from the stack when it goes out of scope? > Variable a is an auto variable, created on the stack when the function is entered, and removed when the function returns. -- Signature file not found From rafael.knuth at gmail.com Fri Oct 25 19:08:20 2013 From: rafael.knuth at gmail.com (Rafael Knuth) Date: Fri, 25 Oct 2013 19:08:20 +0200 Subject: [Tutor] Python 3.3 on OpenSUSE 12.3 In-Reply-To: <1382651150.3623.6.camel@linux-3jah.site> References: <1382651150.3623.6.camel@linux-3jah.site> Message-ID: Hello Jay, thanks for your reply. On Thu, Oct 24, 2013 at 11:45 PM, Jay Lozier wrote: > On Thu, 2013-10-24 at 21:57 +0200, Rafael Knuth wrote: > > Hej, > > I can't get Python 3.3 up and running (it's properly installed but I > > can't launch it), and I was wondering if anyone using OpenSUSE 12.3 > > had similar issues. SUSE community folks weren't really able to help > > me, so I was wondering I give it a try here. > > Thanks, > > Rafael > > Rafael, > > I have both Python 2.7.3 and 3.3.0 installed on openSUSE 12.3. To use > 3.3 I enter python3.3 at the prompt. If I enter python it defaults to > 2.7.3 > > In the shebang #!/usr/bin/env python3.3 > Yes. > > -- > Jay Lozier > jslozier at gmail.com > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From shennig93 at googlemail.com Sat Oct 26 05:09:48 2013 From: shennig93 at googlemail.com (Sven Hennig) Date: Sat, 26 Oct 2013 05:09:48 +0200 Subject: [Tutor] taking a tuple with input Message-ID: Hey Guys, i'm running Python 3.3.2 on Windows 7 64 Bit I am writing a little script for practice and got a little problem. I wrote a class which got two points in the constructor (p1 and p2). With the function distanceOf from my class i measure the distance between these two points. Everything works fine. But when i want to use input to get the points i does not work... So how can i get an int tuple with input? Some Code: class points: def __init__(self, p1, p2): self.p1 = p1 self.p2 = p2 def distanceOf(self): diff = (self.p2[0] - self.p1[0], self.p2[1] - self.p1[1]) a = diff[0] b = diff[1] result = math.sqrt(a**2 + b**2) return "The distance between the two points:", round(result) When i type test = points((25.0, 30.0), (40.0, 55.0)) and test.distanceOf() everything is ok. Now i wont to get input. (In the input prompt i write: (25.0, 30.0) p1 = input('Please type in some coordinates') p2 = input('Please type in some coordinates') test = points(p1, p2) points.distanceOf() Traceback (most recent call last): File "lines.py", line 16, in line.distanceOf() File "lines.py", line 6, in distanceOf diff = (self.p2[0] - self.p1[0], self.p2[1] - self.p1[1]) TypeError: unsupported operand type(s) for -: 'str' and 'str' i get this error can anyone help me out? How can i get an tuple with int values from user input? Greetings -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Sat Oct 26 11:49:45 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 26 Oct 2013 10:49:45 +0100 Subject: [Tutor] taking a tuple with input In-Reply-To: References: Message-ID: On 26/10/2013 04:09, Sven Hennig wrote: > Hey Guys, > > i'm running Python 3.3.2 on Windows 7 64 Bit > > I am writing a little script for practice and got a little problem. > I wrote a class which got two points in the constructor (p1 and p2). > With the function distanceOf from my class i measure the distance > between these two points. Everything works fine. But when i want to use > input to get the points i does not work... > > So how can i get an int tuple with input? > > Some Code: > > class points: > def __init__(self, p1, p2): > self.p1 = p1 > self.p2 = p2 > def distanceOf(self): > diff = (self.p2[0] - self.p1[0], self.p2[1] - self.p1[1]) > a = diff[0] > b = diff[1] > result = math.sqrt(a**2 + b**2) > return "The distance between the two points:", round(result) > > When i type test = points((25.0, 30.0), (40.0, 55.0)) and > test.distanceOf() everything is ok. Now i wont to get input. (In the > input prompt i write: (25.0, 30.0) > p1 = input('Please type in some coordinates') > p2 = input('Please type in some coordinates') > test = points(p1, p2) > points.distanceOf() > > Traceback (most recent call last): > File "lines.py", line 16, in > line.distanceOf() > File "lines.py", line 6, in distanceOf > diff = (self.p2[0] - self.p1[0], self.p2[1] - self.p1[1]) > TypeError: unsupported operand type(s) for -: 'str' and 'str' > > i get this error > > can anyone help me out? How can i get an tuple with int values from user > input? > > Greetings > Twp options from the top of my head. Either enter the coordinates separately and build your tuples (or lists) before passing them to your points class, or use the ast module literal_eval call. Note that if you choose the latter, you don't need to enter the parentheses, it's the comma that makes the tuple. -- Python is the second best programming language in the world. But the best has yet to be invented. Christian Tismer Mark Lawrence From alan.gauld at btinternet.com Sat Oct 26 12:58:27 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 26 Oct 2013 11:58:27 +0100 Subject: [Tutor] taking a tuple with input In-Reply-To: References: Message-ID: On 26/10/13 04:09, Sven Hennig wrote: > So how can i get an int tuple with input? You can't. input() reads strings. (assuming Python v3) You need to convert the string yourself. For simple floats you just call float() but there isn't an equivalent conversion function for tuples. You probably want to split the string by commas and then convert each part to a float. Something like instr = input('Enter a point (x,y): ') inList = [float(n) for n in instr.split(',')] # check for parens too? point = tuple(inList] You can add extra checks or combine more lines but something along those lines should work. The bigget problem is likely to be getting users to enter the correct format. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From steve at pearwood.info Sat Oct 26 14:20:16 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 26 Oct 2013 23:20:16 +1100 Subject: [Tutor] Python and memory allocation In-Reply-To: References: <4d9f0ebe72ca4454a0d5f0cf2bb70152@SIXPR01MB093.apcprd01.prod.exchangelabs.com> Message-ID: <20131026122015.GS7989@ando> On Thu, Oct 24, 2013 at 05:21:56PM +0000, Dave Angel wrote: > If you > want a surprise, try the following simple program some time. > > import sys > print(sys.modules) > > when I tried that interactively on 2.7, it printed some 240+ names. Wow. What were you doing? Ah, I bet you had imported numpy or similar! numpy brings in a lot. [steve at ando ~]$ python2.7 -c "import sys, numpy; print len(sys.modules)" 233 Here are the results you get with a freshly-started Python interpreter on Linux, for various versions of Python, excluding numpy. Starting with ancient Python 1.5, and going right up the most recent 3.4 alpha version. [steve at ando ~]$ python1.5 -c "import sys; print len(sys.modules)" 12 [steve at ando ~]$ python2.4 -c "import sys; print len(sys.modules)" 29 [steve at ando ~]$ python2.5 -c "import sys; print len(sys.modules)" 27 [steve at ando ~]$ python2.6 -c "import sys; print len(sys.modules)" 30 [steve at ando ~]$ python2.7 -c "import sys; print len(sys.modules)" 39 [steve at ando ~]$ python3.2 -c "import sys; print(len(sys.modules))" 52 [steve at ando ~]$ python3.3 -c "import sys; print(len(sys.modules))" 54 [steve at ando ~]$ python3.4 -c "import sys; print(len(sys.modules))" 34 And a few others: steve at orac:~$ jython -c "import sys; print len(sys.modules)" 31 steve at orac:~$ ipy -c "import sys; print len(sys.modules)" 21 steve at orac:~$ ipython -c "import sys; print len(sys.modules)" 269 ipython also brings in a lot of modules, even more than numpy. Oooh, now there's a thought! steve at orac:~$ ipython -c "import sys, numpy; print len(sys.modules)" 397 -- Steven From breamoreboy at yahoo.co.uk Sat Oct 26 16:48:36 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 26 Oct 2013 15:48:36 +0100 Subject: [Tutor] Python and memory allocation In-Reply-To: <20131026122015.GS7989@ando> References: <4d9f0ebe72ca4454a0d5f0cf2bb70152@SIXPR01MB093.apcprd01.prod.exchangelabs.com> <20131026122015.GS7989@ando> Message-ID: On 26/10/2013 13:20, Steven D'Aprano wrote: > On Thu, Oct 24, 2013 at 05:21:56PM +0000, Dave Angel wrote: > >> If you >> want a surprise, try the following simple program some time. >> >> import sys >> print(sys.modules) >> >> when I tried that interactively on 2.7, it printed some 240+ names. > > Wow. What were you doing? Ah, I bet you had imported numpy or similar! > numpy brings in a lot. > This reminded me that work has been done to reduce the number of imports at startup, see http://bugs.python.org/issue19205 and http://bugs.python.org/issue19325 -- Python is the second best programming language in the world. But the best has yet to be invented. Christian Tismer Mark Lawrence From fomcl at yahoo.com Sat Oct 26 18:39:58 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sat, 26 Oct 2013 09:39:58 -0700 (PDT) Subject: [Tutor] why does platform.architecture default to sys.executable? Message-ID: <1382805598.74713.YahooMailNeo@web163803.mail.gq1.yahoo.com> Hi, Why does the "executable" parameter default to sys.executable? Yesterday I was surprised to see platform.architecture return "32bit" on a 64-bit system, just because a 32-bit Python interpreter was installed. Wouldn't this make more sense: import sys, platform pf = sys.platform.lower()[:3] executable = "iexplore.exe" if pf[:3] == "win" else "/bin/ls" arch = platform.architecture(executable)[0] ? Regards, Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -------------- next part -------------- An HTML attachment was scrubbed... URL: From amitsaha.in at gmail.com Sat Oct 26 18:51:17 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Sun, 27 Oct 2013 02:51:17 +1000 Subject: [Tutor] why does platform.architecture default to sys.executable? In-Reply-To: <1382805598.74713.YahooMailNeo@web163803.mail.gq1.yahoo.com> References: <1382805598.74713.YahooMailNeo@web163803.mail.gq1.yahoo.com> Message-ID: On Sun, Oct 27, 2013 at 2:39 AM, Albert-Jan Roskam wrote: > Hi, > > Why does the "executable" parameter default to sys.executable? Yesterday I > was surprised to see platform.architecture return "32bit" on a 64-bit > system, just because a 32-bit Python interpreter was installed. Wouldn't > this make more sense: > > import sys, platform > pf = sys.platform.lower()[:3] > executable = "iexplore.exe" if pf[:3] == "win" else "/bin/ls" I think it's mainly because of avoiding choosing arbitrary programs, although they are most certainly guaranteed to be present. Besides, there are better ways to find the platform architecture, I think. os.uname() comes to mind. -Amit. From amitsaha.in at gmail.com Sat Oct 26 19:13:33 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Sun, 27 Oct 2013 03:13:33 +1000 Subject: [Tutor] why does platform.architecture default to sys.executable? In-Reply-To: References: <1382805598.74713.YahooMailNeo@web163803.mail.gq1.yahoo.com> Message-ID: On Oct 27, 2013 2:51 AM, "Amit Saha" wrote: > > On Sun, Oct 27, 2013 at 2:39 AM, Albert-Jan Roskam wrote: > > Hi, > > > > Why does the "executable" parameter default to sys.executable? Yesterday I > > was surprised to see platform.architecture return "32bit" on a 64-bit > > system, just because a 32-bit Python interpreter was installed. Wouldn't > > this make more sense: > > > > import sys, platform > > pf = sys.platform.lower()[:3] > > executable = "iexplore.exe" if pf[:3] == "win" else "/bin/ls" > > I think it's mainly because of avoiding choosing arbitrary programs, > although they are most certainly guaranteed to be present. Besides, > there are better ways to find the platform architecture, I think. > os.uname() comes to mind. Although that will lie if you have, for example a 32-bit os installed on a 64-bit system. Then, you can read /proc/cpuinfo and look for the lm flag. If it is present, it is a 64-bit system, else a 32-bit one. This is specific to Intel, i think. > > -Amit. -------------- next part -------------- An HTML attachment was scrubbed... URL: From fomcl at yahoo.com Sat Oct 26 19:16:24 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sat, 26 Oct 2013 10:16:24 -0700 (PDT) Subject: [Tutor] why does platform.architecture default to sys.executable? In-Reply-To: Message-ID: <1382807784.865.YahooMailBasic@web163801.mail.gq1.yahoo.com> ------------------------------------------- On Sat, 10/26/13, Amit Saha wrote: Subject: Re: [Tutor] why does platform.architecture default to sys.executable? To: "Albert-Jan Roskam" Cc: "Python Mailing List" Date: Saturday, October 26, 2013, 6:51 PM On Sun, Oct 27, 2013 at 2:39 AM, Albert-Jan Roskam wrote: > Hi, > > Why does the "executable" parameter default to sys.executable? Yesterday I > was surprised to see platform.architecture return "32bit" on a 64-bit > system, just because a 32-bit Python interpreter was installed. Wouldn't > this make more sense: > > import sys, platform > pf = sys.platform.lower()[:3] > executable = "iexplore.exe" if pf[:3] == "win" else "/bin/ls" I think it's mainly because of avoiding choosing arbitrary programs, although they are most certainly guaranteed to be present. Besides, there are better ways to find the platform architecture, I think. os.uname() comes to mind. ===> os.uname is Unix-only: http://docs.python.org/2/library/os.html#os.uname os.uname() Return a 5-tuple containing information identifying the current operating system. The tuple contains 5 strings: (sysname, nodename, release, version, machine). Some systems truncate the nodename to 8 characters or to the leading component; a better way to get the hostname is socket.gethostname() or even socket.gethostbyaddr(socket.gethostname()). Availability: recent flavors of Unix. From alan.gauld at btinternet.com Sat Oct 26 23:46:41 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 26 Oct 2013 22:46:41 +0100 Subject: [Tutor] why does platform.architecture default to sys.executable? In-Reply-To: References: <1382805598.74713.YahooMailNeo@web163803.mail.gq1.yahoo.com> Message-ID: On 26/10/13 18:13, Amit Saha wrote: > a 64-bit system. Then, you can read /proc/cpuinfo and look for the lm > flag. If it is present, it is a 64-bit system, But that will only work on *nix systems I assume? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From eryksun at gmail.com Sun Oct 27 00:45:11 2013 From: eryksun at gmail.com (eryksun) Date: Sat, 26 Oct 2013 18:45:11 -0400 Subject: [Tutor] why does platform.architecture default to sys.executable? In-Reply-To: <1382805598.74713.YahooMailNeo@web163803.mail.gq1.yahoo.com> References: <1382805598.74713.YahooMailNeo@web163803.mail.gq1.yahoo.com> Message-ID: On Sat, Oct 26, 2013 at 12:39 PM, Albert-Jan Roskam wrote: > > Why does the "executable" parameter default to sys.executable? In general platform.architecture() parses the output of the UNIX "file" command. But on Windows the linkage is hard coded to 'WindowsPE', and bits is the default value calculated from the pointer size in the current process (i.e. python.exe). Use ctypes or PyWin32 instead. ctypes: windll.kernel32.GetBinaryTypeW PyWin32: win32file.GetBinaryType, win32file.SCS_64BIT_BINARY, etc http://msdn.microsoft.com/en-us/library/aa364819 From cnsiva.in at gmail.com Sat Oct 26 21:32:56 2013 From: cnsiva.in at gmail.com (Siva Cn) Date: Sun, 27 Oct 2013 01:02:56 +0530 Subject: [Tutor] taking a tuple with input Message-ID: p1 = tuple([float(ele) for ele in input('Please type ...').split()]) p2 = tuple([float(ele) for ele in input('Please type ...').split()]) # input format is : 25.0 30.0 --------------------- *Siva Cn* *Python Developer* *http://www.cnsiva.com* --------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From shelby.martin at gmail.com Sat Oct 26 21:13:22 2013 From: shelby.martin at gmail.com (Shelby Martin) Date: Sat, 26 Oct 2013 12:13:22 -0700 Subject: [Tutor] Question about conditions and empty values Message-ID: For the program below, if I enter "0" at the prompt, it provides the reply "Please, sit. It may be a while". However, if I just press the Enter key, it shuts the program down without a reply from the Maitre D'. My question is this - the author of this exercise states the condition is False if either zero or "empty" is the value. I'm assuming he means that empty is just pressing Enter without entering a number? He talks about testing for empty values, but I'm not seeing that entering an empty value here yields the response he is talking about. Unless I'm mistaken about something. Thanks in advance for your assistance! #Maitre D' #Demonstrates treating a value as a condition print("Welcome to the Chateau D' Food") print("It seems we are quite full this evening.\n") money = int(input("How many dollars do you slip the Maitre D'?")) if money: print("Ah, I am reminded of a table. Right this way.") else: print("Please, sit. It may be a while.") input("\n\nPress the enter key to exit.") -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Oct 27 01:45:01 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 27 Oct 2013 00:45:01 +0100 Subject: [Tutor] Question about conditions and empty values In-Reply-To: References: Message-ID: On 26/10/13 20:13, Shelby Martin wrote: > My question is this - the author of this exercise states the condition > is False if either zero or "empty" is the value. I'm assuming he means > that empty is just pressing Enter without entering a number? Normally that would be correct but... > > money = int(input("How many dollars do you slip the Maitre D'?")) Here we try to convert the string to an int. and int() fails when given an empty string so your program never reaches the if test. Which begs the question: GHOw are you running your programs? If you used a console or an IDE it should have shown you the error message which would have explained what and where things went wrong. You would need to either use a try/except clause around the conversion or check for an empty string before converting. try/except is the preferred route but you may not have covered that yet. > if money: > print("Ah, I am reminded of a table. Right this way.") > else: > print("Please, sit. It may be a while.") If you did get the error message then please, in future, include any such in their entirety in posts because they greatly simplify diagnosing more complex issues. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Sun Oct 27 01:39:49 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 27 Oct 2013 00:39:49 +0100 Subject: [Tutor] taking a tuple with input In-Reply-To: References: Message-ID: On 26/10/13 20:32, Siva Cn wrote: > > p1 = tuple([float(ele) for ele in input('Please type ...').split()]) If you do it all in one line like that you dpn;t need the [] inside the tuple() call. The generator expressoion will work directly. But of course a single line like that will be hard to debug if you get anything wrong. You have to decide which trade off you prefer, size v complexity. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From breamoreboy at yahoo.co.uk Sun Oct 27 02:01:19 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 27 Oct 2013 01:01:19 +0100 Subject: [Tutor] taking a tuple with input In-Reply-To: References: Message-ID: On 26/10/2013 20:32, Siva Cn wrote: > > p1 = tuple([float(ele) for ele in input('Please type ...').split()]) > p2 = tuple([float(ele) for ele in input('Please type ...').split()]) > > # input format is : 25.0 30.0 > > --------------------- > *Siva Cn* > *Python Developer* > *http://www.cnsiva.com* > --------------------- > Congratulations, for managing to break threading you have won tonight's star prize, a two week, all expenses paid holiday to Three Mile Island, Pennsylvania :) -- Python is the second best programming language in the world. But the best has yet to be invented. Christian Tismer Mark Lawrence From amitsaha.in at gmail.com Sun Oct 27 02:16:26 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Sun, 27 Oct 2013 11:16:26 +1000 Subject: [Tutor] why does platform.architecture default to sys.executable? In-Reply-To: References: <1382805598.74713.YahooMailNeo@web163803.mail.gq1.yahoo.com> Message-ID: On Sun, Oct 27, 2013 at 7:46 AM, Alan Gauld wrote: > On 26/10/13 18:13, Amit Saha wrote: > >> a 64-bit system. Then, you can read /proc/cpuinfo and look for the lm >> flag. If it is present, it is a 64-bit system, > > > But that will only work on *nix systems I assume? Indeed, both my answers assumed a Linux system. Sorry about that. -- http://echorand.me From marc at marcd.org Sun Oct 27 14:25:01 2013 From: marc at marcd.org (Marc) Date: Sun, 27 Oct 2013 09:25:01 -0400 Subject: [Tutor] Parsing multiple lines from text file using regex Message-ID: <002601ced317$f4e993a0$debcbae0$@org> Hi, I am having an issue with something that would seem have an easy solution, which escapes me. I have configuration files that I would like to parse. The data I am having issue with is a multi-line attribute that has the following structure: banner